/// <summary>
        /// リポジトリ登録
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task SetRepository(SlackRequest.Active <RepositoryData> data)
        {
            // 保存するトークンを入れたentityを作成
            var entity = new ChannelIdEntity(data.Channel.Id, data.Channel.Name, data.Submission.UserName + "/" + data.Submission.Repository);

            // Entityがなければ挿入、あれば更新する
            var insertResult = EntityOperationChannelId.InsertOrUpdateEntityResult(entity, "channel");

            string text;

            // 結果があるかどうか
            if (insertResult != null)
            {
                text = "リポジトリの登録に成功しました。" + Environment.NewLine + "https://github.com/" + data.Submission.UserName + "/" + data.Submission.Repository;
            }
            else
            {
                text = "リポジトリの登録に失敗しました";
            }

            var model = new PostMessageModel()
            {
                Channel       = data.Channel.Id,
                Text          = text,
                Response_type = "in_channel",
                Unfurl_links  = true
            };

            await SlackApi.ExecutePostApiAsJson(model, "https://slack.com/api/chat.postMessage", data.Team.Id);
        }
Example #2
0
        public static async void RunAsync([TimerTrigger("0 0 11 * * MON-FRI")] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation("Firing chron trigger.");

            //get environment variables
            var postMessageUrl = Helper.GetEnvironmentVariable(PostMessageUrl);
            var botToken       = Helper.GetEnvironmentVariable(BotToken);
            var channelName    = Helper.GetEnvironmentVariable(ChannelName);

            try
            {
                var message = new PostMessageModel
                {
                    text    = "Give us this day our daily bread.",
                    channel = channelName
                };

                var content = JsonConvert.SerializeObject(message);
                using (var client = new HttpClient())
                {
                    log.LogInformation("Posting message.");
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", botToken);
                    await client.PostAsync(postMessageUrl, new StringContent(content, Encoding.UTF8, "application/json"));
                }
            }
            catch (Exception ex)
            {
                log.LogInformation(ex.Message);
            }
        }
        /// <summary>
        /// リポジトリ照会
        /// </summary>
        /// <param name="channelId"></param>
        /// <param name="responseUrl"></param>
        /// <param name="teamId"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static async Task GetRepository(string channelId, string responseUrl, string teamId, Func <string, Task> func)
        {
            // PartitionKeyがチャンネルIDのEntityを取得するクエリ
            var query = new TableQuery <ChannelIdEntity>()
                        .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, channelId));

            // クエリ実行
            var entityList = StorageOperation.GetTableIfNotExistsCreate("channel").ExecuteQuery(query);

            // クエリ実行結果で要素がひとつでもあるかどうか
            var channelIdEntities = entityList.ToList();

            if (channelIdEntities.Any())
            {
                await func(channelIdEntities.First().Repository);
            }
            else
            {
                var model = new PostMessageModel()
                {
                    Channel       = channelId,
                    Text          = "登録リポジトリが存在しません。",
                    Response_type = "ephemeral"
                };

                var slackApi = new SlackApi();

                await slackApi.ExecutePostApiAsJson(model, responseUrl, teamId);
            }
        }
Example #4
0
        public FeedDetailsPage(PostMessageModel postMessage)
        {
            var feedDetailsViewModel = new FeedDetailsViewModel(postMessage);

            this.BindingContext = feedDetailsViewModel;

            InitializeComponent();
        }
Example #5
0
        public async Task LoginGitHub(HttpRequestMessage request)
        {
            var content = await request.Content.ReadAsStringAsync();

            var data = HttpUtility.ParseQueryString(content);

            // アクセストークン保存の為のユーザデータを格納
            _userData = data;

            // ===========================
            // GitHub OauthURL取得
            // ===========================
            var csrf = Membership.GeneratePassword(20, 0);

            var oauthRequest = new OauthLoginRequest(ConfigurationManager.AppSettings["client_id"])
            {
                Scopes = { "repo", "user" },
                State  = csrf
            };

            var url = _githubClient.Oauth.GetGitHubLoginUrl(oauthRequest).ToString();

            // ==============================
            // Oauth用リダイレクトボタン作成
            // ==============================
            var model = new PostMessageModel()
            {
                Channel       = data["channel_id"],
                Text          = "GitHubへログインしてください",
                Response_type = "ephemeral",
                Attachments   = new List <Attachment>()
                {
                    new Attachment()
                    {
                        Fallback = "The GitHub Oauth URL",
                        Actions  = new List <Action>()
                        {
                            new Action()
                            {
                                Type  = "button",
                                Name  = "github_oauth_url",
                                Text  = "ログイン",
                                Url   = url,
                                Style = "primary"
                            }
                        }
                    }
                }
            };

            await SlackApi.ExecutePostApiAsJson(model, data["response_url"], data["team_id"]);
        }
Example #6
0
        /// <summary>
        /// GitHubユーザ認証エラーハンドリング
        /// </summary>
        /// <param name="teamId"></param>
        /// <param name="func"></param>
        /// <param name="channelId"></param>
        /// <param name="responseUrl"></param>
        /// <returns></returns>
        public static async Task AuthorizationExceptionHandler(string channelId, string responseUrl, string teamId, Func <Task> func)
        {
            try
            {
                await func();
            }
            catch (AuthorizationException)
            {
                PostMessageModel model = new PostMessageModel()
                {
                    Channel       = channelId,
                    Text          = "ユーザ情報が不正、もしくは存在しません。",
                    Response_type = "ephemeral"
                };

                await SlackApi.ExecutePostApiAsJson(model, responseUrl, teamId);
            }
        }
        /// <summary>
        /// Issue作成
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task CreateIssue(SlackRequest.Active <IssueData> data)
        {
            // =============================
            // Issueオブジェクト作成
            // =============================
            var newIssue = new NewIssue(data.Submission.Title)
            {
                Body = data.Submission.Body
            };

            newIssue.Labels.Add(data.Submission.Label);

            // =============================
            // GitHubアクセストークンの設定
            // =============================
            GitHubApi.SetCredential(data.User.Id);

            // =============================
            // 登録リポジトリ取得
            // =============================
            await GetRepository(data.Channel.Id, data.Response_url, data.Team.Id, async repository =>
            {
                // GitHub認証エラーハンドリング
                await AuthorizationExceptionHandler(data.Channel.Id, data.Response_url, data.Team.Id, async() =>
                {
                    // =============================
                    // Issue作成
                    // =============================
                    var issue = await GitHubApi.Client.Issue.Create(repository.Split('/')[0], repository.Split('/')[1], newIssue);

                    var model = new PostMessageModel()
                    {
                        Channel       = data.Channel.Id,
                        Text          = "Issueが登録されました" + Environment.NewLine + "https://github.com/" + repository + "/issues/" + issue.Number,
                        Response_type = "in_channel",
                        Unfurl_links  = true
                    };

                    await SlackApi.ExecutePostApiAsJson(model, data.Response_url, data.Team.Id);
                });
            });
        }
Example #8
0
        /// <summary>
        /// エラーハンドラー
        /// </summary>
        /// <param name="data"></param>
        /// <param name="cancel"></param>
        /// <returns></returns>
        public static async Task Handler(NameValueCollection data, Canceler cancel)
        {
            try
            {
                //なにかしらの処理
                await cancel();
            }
            //操作キャンセル時の処理
            catch (OperationCanceledException)
            {
            }
            //ユーザ情報不正時の処理
            catch (AuthorizationException)
            {
                var model = new PostMessageModel()
                {
                    Channel       = data["channel_id"],
                    Text          = "ユーザ情報が不正、もしくは存在しません。",
                    Response_type = "ephemeral"
                };

                await SlackApi.ExecutePostApiAsJson(model, data["response_url"], data["team_id"]);
            }
            //それ以外の例外処理
            catch (Exception)
            {
                var model = new PostMessageModel()
                {
                    Channel       = data["channel_id"],
                    Text          = "予期せぬエラーが発生しました。",
                    Response_type = "ephemeral"
                };

                await SlackApi.ExecutePostApiAsJson(model, data["response_url"], data["team_id"]);
            }
        }
Example #9
0
 private static bool IsModelValid(PostMessageModel model)
 {
     return(null != model && false == String.IsNullOrEmpty(model.Text));
 }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="alias"></param>
        /// <param name="model"></param>
        /// <returns>
        /// </returns>
        public async Task <IHttpActionResult> Post([FromUri(Name = "id")] string alias, [FromBody] PostMessageModel model)
        {
            if (String.IsNullOrEmpty(alias))
            {
                return(NotFound());
            }

            if (false == IsModelValid(model))
            {
                return(BadRequest());
            }

            var chat = GrainClient.GrainFactory.GetGrain <IChat>(0);

            await chat.PublishMessageAsync(alias, model.Author, new UserMessage
            {
                Text = model.Text
            });

            var link = Url.Link("DefaultApi", new
            {
                id = Guid.NewGuid()
            });

            return(Created(new Uri(link), new PostedMessageModel()));
        }
Example #11
0
        public FeedDetailsViewModel(PostMessageModel postMessage)
        {
            //Pull all ReplyMessageModels from the database where ReplyMessageModel.PostMessageId == postMessage.Id
            PostUserProfileUrl = postMessage.PostUser.PictureUrl;
            PostUserName       = postMessage.PostUser.Name;
            PostUserPostText   = postMessage.PostText;

            if (postMessage.NumberOfReplies == 1)
            {
                NumberOfReplies = $"{postMessage.NumberOfReplies} Reply";
            }
            else
            {
                NumberOfReplies = $"{postMessage.NumberOfReplies} Replies";
            }

            PostButtonCommand = new Command(() =>
            {
                var dummyPostMessage = new ReplyMessageModel
                {
                    Id        = "This was created via Command",
                    ReplyText = "This was created via Command",
                    ReplyUser = new UserProfileModel
                    {
                        PictureUrl = "http://www.profightdb.com/img/wrestlers/thumbs-600/6baee11272the-rock.jpg",
                    }
                };

                FeedDetailsListViewItemSource.Add(dummyPostMessage);
            });

            FeedDetailsListViewItemSource = new ObservableCollection <ReplyMessageModel>
            {
                new ReplyMessageModel
                {
                    ReplyText = "And the only way to do great work is to love what you do. ",
                    ReplyUser = new UserProfileModel
                    {
                        PictureUrl = "http://www.profightdb.com/img/wrestlers/thumbs-600/6baee11272the-rock.jpg",
                    }
                },
                new ReplyMessageModel
                {
                    ReplyText = "Everything around you that you call life was made up by people that were no smarter than you",
                    ReplyUser = new UserProfileModel
                    {
                        PictureUrl = "https://cdn.inquisitr.com/wp-content/uploads/2016/04/kylie-jenner-paper-photoshoot.png"
                    }
                },
                new ReplyMessageModel
                {
                    ReplyText = "What's the best pizza joint around campus? ",
                    ReplyUser = new UserProfileModel
                    {
                        PictureUrl = "https://healthyceleb.com/wp-content/uploads/2016/07/Kevin-Hart-headshot.jpg",
                    }
                },
                new ReplyMessageModel
                {
                    ReplyText = "Everything around you that you call life was made up by people that were no smarter than you",
                    ReplyUser = new UserProfileModel
                    {
                        PictureUrl = "https://i.ytimg.com/vi/RnSgCv2X0ns/hqdefault.jpg",
                    }
                },
                new ReplyMessageModel
                {
                    ReplyText = "Everything around you that you call life was made up by people that were no smarter than you",
                    ReplyUser = new UserProfileModel
                    {
                        PictureUrl = "http://www.profightdb.com/img/wrestlers/thumbs-600/6baee11272the-rock.jpg",
                    }
                },
                new ReplyMessageModel
                {
                    ReplyText = "Everything around you that you call life was made up by people that were no smarter than you",
                    ReplyUser = new UserProfileModel
                    {
                        PictureUrl = "http://www.profightdb.com/img/wrestlers/thumbs-600/6baee11272the-rock.jpg",
                    }
                }
            };
        }
Example #12
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
        {
            log.LogInformation("Slack Endpoint received a request.");
            try
            {
                var requestBody = await new StreamReader(req.Body).ReadToEndAsync();

                //determine if this is a verification challenge request
                if (requestBody.Contains("challenge"))
                {
                    log.LogInformation("Attempting to verify Endpoint");

                    var verificationEventModel = JsonConvert.DeserializeObject <SlackUrlVerificationEventModel>(requestBody);

                    log.LogInformation("Endpoint Verification sent.");

                    return(new OkObjectResult(verificationEventModel.Challenge));
                }

                //get environment variables
                var postMessageUrl = Helper.GetEnvironmentVariable(PostMessageUrl);
                var botToken       = Helper.GetEnvironmentVariable(BotToken);
                var channelName    = Helper.GetEnvironmentVariable(ChannelName);

                //deserialize request to a model
                //var eventRequest = JsonConvert.DeserializeObject<EventRequestModel>(requestBody);

                //check if the event request was an app_mention
                //if (eventRequest.Type == "app_mention")
                //{
                log.LogInformation("Receieved app mention request type.");

                var botText = new Dictionary <int, string>
                {
                    { 0, "Let's get this bread!" },
                    { 1, "Let's yeet this wheat." },
                    { 2, "There is not a thing that is more positive than bread. – Fyodor Dostoevsky" },
                    { 3, "With bread, all sorrows are less - from Don Quixote" },
                    { 4, "Rather a piece of bread with a happy heart than wealth with grief. – Egyptian Proverb" },
                    { 5, "Check before you bite if it is bread or a stone. - Croatian Proverb" },
                    { 6, "Let them eat cake! - Marie Antoinnette" },
                    { 7, "The sky is the daily bread of the eyes. - Ralph Waldo Emerson" },
                    { 8, "Bread is the king of the table, and all else is merely the court that surrounds the king. - Louis Bromfield" },
                    { 9, "Without bread, all is misery. - William Cobbett" },
                    { 10, "How do you get a raise at the bread factory? Butter up your boss." },
                    { 11, "We gon' keep bakin' to the day we get cake - Kanye West" },
                    { 12, "Team! Let's Get that Bread! - Jake R. Martin" },
                    { 13, "There's bread and then there's BREAD. Get that BREAD! - Mark Robustelli" },
                    { 14, "Let us obtain the grain." },
                    { 15, "Let's go with the dough." },
                    { 16, "Let's finagle that bagel." },
                    { 17, "What do DevEx and ducks have in common? We both get this bread." }
                };

                var random = new Random();
                var key    = random.Next(0, botText.Count);

                var message = new PostMessageModel
                {
                    text    = botText[key],
                    channel = channelName
                };

                var content = JsonConvert.SerializeObject(message);
                using (var client = new HttpClient())
                {
                    log.LogInformation("Posting message.");
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", botToken);
                    await client.PostAsync(postMessageUrl, new StringContent(content, Encoding.UTF8, "application/json"));
                }
                return(new OkResult());
                //}

                //log.LogInformation("Request does not match a valid criteria");
                //return new BadRequestResult();
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new InternalServerErrorResult());
            }
        }
Example #13
0
        public async Task Operation(HttpRequestMessage request)
        {
            // ===========================
            // リクエストの取得・整形
            // ===========================
            NameValueCollection data = await GetBody(request);

            // 引数の値
            var method = data["text"];

            // ===========================
            // 引数の値で処理を分ける
            // ===========================
            switch (method)
            {
            // ===========================
            // リポジトリ登録
            // ===========================
            case "set":
            {
                // ====================================
                // リポジトリ登録用ダイアログモデル作成
                // ====================================
                var model = CreateDialogModelForSetRespotory(data["trigger_id"]);

                // =============================
                // ダイアログAPI実行
                // =============================
                await SlackApi.ExecutePostApiAsJson(model, "https://slack.com/api/dialog.open", data["team_id"]);

                break;
            }

            // ===========================
            // 登録リポジトリ照会
            // ===========================
            case "get":
            {
                await GetRepository(data["channel_id"], data["response_url"], data["team_id"], async repository =>
                    {
                        var model = new PostMessageModel()
                        {
                            Channel       = data["channel_id"],
                            Text          = "登録リポジトリのURLを照会します" + Environment.NewLine + "https://github.com/" + repository,
                            Response_type = "ephemeral"
                        };

                        await SlackApi.ExecutePostApiAsJson(model, data["response_url"], data["team_id"]);
                    });

                break;
            }

            // ===========================
            // それ以外
            // ===========================
            default:
            {
                var model = new PostMessageModel()
                {
                    Channel       = data["channel_id"],
                    Text          = "引数を入力してください",
                    Response_type = "ephemeral"
                };

                await SlackApi.ExecutePostApiAsJson(model, data["response_url"], data["team_id"]);

                break;
            }
            }
        }
Example #14
0
        public async Task Create(HttpRequestMessage request)
        {
            // ===========================
            // リクエストの取得・整形
            // ===========================
            var data = await GetBody(request);

            // 引数の値
            var method = data["text"];


            // ===========================
            // 引数の値で処理を分ける
            // ===========================
            switch (method)
            {
            // ===========================
            // issue登録
            // ===========================
            case "create":
            {
                // =============================
                // GitHubアクセストークンの設定
                // =============================
                GitHubApi.SetCredential(data["user_id"]);

                // =============================
                // 登録リポジトリ照会
                // =============================

                await GetRepository(data["channel_id"], data["response_url"], data["team_id"], async repository =>
                    {
                        List <string> labelNameList = null;

                        // GitHub認証エラーハンドリング
                        await AuthorizationExceptionHandler(data["channel_id"], data["response_url"], data["team_id"],
                                                            async() =>
                        {
                            // クライアントを用いてリポジトリ名からIssueのラベルを取得
                            var labelList =
                                await GitHubApi.Client.Issue.Labels.GetAllForRepository(repository.Split('/')[0],
                                                                                        repository.Split('/')[1]);

                            // ラベル変数リストを文字列リストに変換
                            labelNameList = labelList.ToList().ConvertAll(x => x.Name);
                        });

                        // ===============================
                        // Issue作成用ダイアログモデル作成
                        // ===============================
                        var model = CreateDialogModelForCreateIssue(data["trigger_id"], labelNameList);

                        // =============================
                        // ダイアログAPI実行
                        // =============================
                        await SlackApi.ExecutePostApiAsJson(model, "https://slack.com/api/dialog.open",
                                                            data["team_id"]);
                    });

                break;
            }

            case "export":
            {
                List <Issue> issueList = null;

                // =============================
                // 登録リポジトリ照会
                // =============================
                await GetRepository(data["channel_id"], data["response_url"], data["team_id"], async repository =>
                    {
                        // GitHub認証エラーハンドリング
                        await AuthorizationExceptionHandler(data["channel_id"], data["response_url"], data["team_id"],
                                                            async() =>
                        {
                            var issueROList = await GitHubApi.Client.Issue.GetAllForRepository(
                                repository.Split('/')[0],
                                repository.Split('/')[1]);
                            issueList = issueROList.ToList();
                        });
                    });

                var issueText = string.Empty;
                foreach (var issue in issueList)
                {
                    var assigneesString = issue.Assignees.Any() ? string.Join(" ", issue.Assignees.Select(x => x.Login)) : "";

                    issueText +=
                        $"```\n***issueID***\n{issue.Number}\n***アサイン者***\n{assigneesString}\n***タイトル***\n{issue.Title}\n***本文***\n{issue.Body}\n***登録者?***{issue.User.Login}\n***状態***\n{issue.State.StringValue}\n```";
                }

                var model = new PostMessageModel()
                {
                    Channel       = data["channel_id"],
                    Text          = issueText,
                    Response_type = "ephemeral"
                };

                await SlackApi.ExecutePostApiAsJson(model, data["response_url"], data["team_id"]);

                break;
            }

            // ===========================
            // それ以外
            // ===========================
            default:
            {
                var model = new PostMessageModel()
                {
                    Channel       = data["channel_id"],
                    Text          = "引数を入力してください",
                    Response_type = "ephemeral"
                };

                await SlackApi.ExecutePostApiAsJson(model, data["response_url"], data["team_id"]);

                break;
            }
            }

            #endregion
        }