public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                var channelSecret = System.Configuration.ConfigurationManager.AppSettings["ChannelSecret"];
                var events        = await req.GetWebhookEventsAsync(channelSecret);

                var connectionString = System.Configuration.ConfigurationManager.AppSettings["AzureWebJobsStorage"];
                var eventSourceState = await TableStorage <EventSourceState> .CreateAsync(connectionString, "eventsourcestate");

                var blobStorage = await BlobStorage.CreateAsync(connectionString, "linebotcontainer");

                //var app = new LineBotApp(lineMessagingClient, eventSourceState, blobStorage, log);

                //Samples app
                //var app = new DateTimePickerSampleApp(lineMessagingClient, log);
                //var app = new ImagemapSampleApp(lineMessagingClient, blobStorage, log);
                //var app = new ImageCarouselSampleApp(lineMessagingClient, blobStorage, log);
                //var app = new RichMenuSampleApp(lineMessagingClient, log);
                //var eventSourceLocation = await TableStorage<EventSourceLocation>.CreateAsync(connectionString, "eventsourcelocation");
                //var app = new PostbackMessageSampleApp(lineMessagingClient, eventSourceLocation, log);
                //var app = new ButtonsTemplateSampleApp(lineMessagingClient, blobStorage, log);
                var app = new CarouselTemplateSampleApp(lineMessagingClient, blobStorage, log);
                await app.RunAsync(events);
            }
            catch (InvalidSignatureException e)
            {
                return(req.CreateResponse(HttpStatusCode.Forbidden, new { Message = e.Message }));
            }
            catch (LineResponseException e)
            {
                log.Error(e.ToString());
                var debugUserId = System.Configuration.ConfigurationManager.AppSettings["DebugUser"];
                if (debugUserId != null)
                {
                    await lineMessagingClient.PushMessageAsync(debugUserId, $"{e.StatusCode}({(int)e.StatusCode}), {e.ResponseMessage.ToString()}");
                }
            }
            catch (Exception e)
            {
                log.Error(e.ToString());
                var debugUserId = System.Configuration.ConfigurationManager.AppSettings["DebugUser"];
                if (debugUserId != null)
                {
                    await lineMessagingClient.PushMessageAsync(debugUserId, e.Message);
                }
            }

            return(req.CreateResponse(HttpStatusCode.OK));
        }
Example #2
0
        /// <summary>
        /// Main run method
        /// </summary>
        /// <param name="req">HttpRequestMessage</param>
        /// <param name="log">TraceWriter</param>
        /// <returns>Result</returns>
        public static async Task <IActionResult> Run(HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                log.Info("C# HTTP trigger function processed a request.");

                var channelAccessToken  = Environment.GetEnvironmentVariable("ChannelAccessToken");
                var channelSecret       = Environment.GetEnvironmentVariable("ChannelSecret");
                var lineMessagingClient = new LineMessagingClient(channelAccessToken);
                var events = await req.GetWebhookEventsAsync(channelSecret);

                var connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
                var eventSourceState = await TableStorage <EventSourceState> .CreateAsync(connectionString, "eventsourcestate");

                var blobStorage = await BlobStorage.CreateAsync(connectionString, "linebotcontainer");

                // Create the LineBotApp and run it.
                var app = new LineBotApp(lineMessagingClient, eventSourceState, blobStorage, log);
                await app.RunAsync(events);
            }
            catch (InvalidSignatureException e)
            {
                return(new ObjectResult(e.Message)
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }
            catch (LineResponseException e)
            {
                log.Error(e.ToString());
                var debugUserId = Environment.GetEnvironmentVariable("DebugUser");
                if (debugUserId != null)
                {
                    await lineMessagingClient.PushMessageAsync(debugUserId, $"{e.StatusCode}({(int)e.StatusCode}), {e.ResponseMessage.ToString()}");
                }
            }
            catch (Exception e)
            {
                log.Error(e.ToString());
                var debugUserId = Environment.GetEnvironmentVariable("DebugUser");
                if (debugUserId != null)
                {
                    await lineMessagingClient.PushMessageAsync(debugUserId, e.Message);
                }
            }

            return(new OkObjectResult("OK"));
        }
Example #3
0
        private void button1_Click(object sender, EventArgs e)
        {
            var message = $"商品が見つかりました。\n下記URLから商品購入を行ってください。\nhttps://www.toysrus.co.jp/search/?q=4902370537789";
            LineMessagingClient lineMessagingClient = new LineMessagingClient("42ndcVVsa4VFSJD9vtyuslUG6VLkWz+i96cu5AFJlsjdOgyQx0SZO0k/4sDu7dE7iFoMl34+qBkUKnjecyjWDItkpWmIOtAxGGupCH/93zeKW/jsY4oS5UDXkBPYZunZxlbP8Qv2wH9slZLA5N+3ZAdB04t89/1O/w1cDnyilFU=");

            lineMessagingClient.PushMessageAsync("U40ab91bbe212e2256a52157bf13c5705", message);
        }
 public async Task SendPayConfirm(Reserve reserve)
 {
     await messagingClient.PushMessageAsync(reserve.Mid, new List <ISendMessage>(){
         new StickerMessage("2", "144"),
         new TextMessage("ありがとうございます、チョコレートの決済が完了しました。")
     });
 }
Example #5
0
        public static void Run([TimerTrigger("0 * * * * *")] TimerInfo myTimer, TraceWriter log)
        {
            //log.Info($"{DateTime.Now}:スタート");

            try
            {
                // 商品検索
                var janCode   = ConfigurationManager.AppSettings["TargetGoods"].Split(',')[0];
                var goodsName = ConfigurationManager.AppSettings["TargetGoods"].Split(',')[1];
                Core.Crawler.Toysrus        crawler = new Core.Crawler.Toysrus();
                Core.Crawler.Toysrus.Result result  = crawler.Run(janCode);

                if (result.Exist)
                {
                    var message = $"【{goodsName}】が見つかりました。\n下記URLから購入を行ってください。\n{result.TargetUrl}";
                    LineMessagingClient lineMessagingClient = new LineMessagingClient(ConfigurationManager.AppSettings["AccessToken"]);
                    lineMessagingClient.PushMessageAsync(ConfigurationManager.AppSettings["SendUserID"], message);
                }
            }
            catch (Exception ex)
            {
                log.Verbose($"{DateTime.Now}:{ex.ToString()}");
            }
            finally
            {
                //log.Info($"{DateTime.Now}:エンド");
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                var channelSecret = System.Configuration.ConfigurationManager.AppSettings["ChannelSecret"];
                var events        = await req.GetWebhookEventsAsync(channelSecret);

                var connectionString = System.Configuration.ConfigurationManager.AppSettings["AzureWebJobsStorage"];
                var botStatus        = await TableStorage <BotStatus> .CreateAsync(connectionString, "botstatus");

                var blobStorage = await BlobStorage.CreateAsync(connectionString, "linebotcontainer");

                //var app = new LineBotApp(lineMessagingClient, botStatus, blobStorage, log);

                ///* To run sample apps in the samples directory, comment out the above line and cancel this comment out.
                var app = await AppSwitcher.SwitchAppsAsync(events, lineMessagingClient, botStatus, blobStorage, log);

                // */

                await app.RunAsync(events);
            }
            catch (InvalidSignatureException e)
            {
                return(req.CreateResponse(HttpStatusCode.Forbidden, new { e.Message }));
            }
            catch (LineResponseException e)
            {
                log.Error(e.ToString());
                var debugUserId = System.Configuration.ConfigurationManager.AppSettings["DebugUser"];
                if (debugUserId != null)
                {
                    await lineMessagingClient.PushMessageAsync(debugUserId, $"{e.StatusCode}({(int)e.StatusCode}), {e.ResponseMessage.ToString()}");
                }
            }
            catch (Exception e)
            {
                log.Error(e.ToString());
                var debugUserId = System.Configuration.ConfigurationManager.AppSettings["DebugUser"];
                if (debugUserId != null)
                {
                    await lineMessagingClient.PushMessageAsync(debugUserId, e.Message);
                }
            }

            return(req.CreateResponse(HttpStatusCode.OK));
        }
 public async Task PushLineMessage(ISendMessage replyMessage)
 {
     LineMessagingClient lineMessagingClient = new LineMessagingClient(System.Configuration.ConfigurationManager.AppSettings["ChannelAccessToken"]);
     var debugUserId = System.Configuration.ConfigurationManager.AppSettings["DebugUser"];
     await lineMessagingClient.PushMessageAsync(debugUserId, new List <ISendMessage> {
         replyMessage
     });
 }
Example #8
0
        public async Task <IActionResult> Get()
        {
            var message = GetMessage();

            logger.LogInformation("message: {message}", message);
            if (!string.IsNullOrWhiteSpace(message))
            {
                await lineMessagingClient.PushMessageAsync(configuration["RoomId"], message);
            }
            return(Content(message));
        }
 /// <summary>
 /// Send LINE messages to LINE Channel. If reply fails, try push instead.
 /// </summary>
 /// <param name="messages">LINE messages</param>
 /// <param name="replyToken">ReplyToken</param>
 /// <param name="userId">UserId</param>
 /// <returns></returns>
 public async Task SendAsync(List <ISendMessage> messages, string userId, string replyToken)
 {
     try
     {
         // If messages contain more than 5 items, then do reply for first 5, then push the rest.
         for (int i = 0; i < (double)messages.Count / 5; i++)
         {
             if (i == 0)
             {
                 await messagingClient.ReplyMessageAsync(replyToken, messages.Take(5).ToList());
             }
             else
             {
                 await messagingClient.PushMessageAsync(replyToken, messages.Skip(i * 5).Take(5).ToList());
             }
         }
     }
     catch (LineResponseException ex)
     {
         if (ex.Message == "Invalid reply token")
         {
             try
             {
                 for (int i = 0; i < (double)messages.Count / 5; i++)
                 {
                     await messagingClient.PushMessageAsync(userId, messages.Skip(i * 5).Take(5).ToList());
                 }
             }
             catch (LineResponseException innerEx)
             {
                 await messagingClient.PushMessageAsync(userId, innerEx.Message);
             }
         }
     }
     catch (Exception ex)
     {
         await messagingClient.PushMessageAsync(userId, ex.Message);
     }
 }
Example #10
0
        /// <summary>
        /// Send Messages to LIne Messaging API
        /// </summary>
        /// <param name="replyToId">Reply Id</param>
        /// <param name="lineMessages">Line Messages</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task SendMessageToLine(string replyToId, IList <ISendMessage> lineMessages)
        {
            if (string.IsNullOrWhiteSpace(replyToId))
            {
                throw new ArgumentNullException(nameof(replyToId));
            }

            if (lineMessages == null)
            {
                throw new ArgumentNullException(nameof(lineMessages));
            }

            await _lineMessagingClient.PushMessageAsync(replyToId, lineMessages).ConfigureAwait(false);
        }
        public static async Task <IActionResult> Line([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ExecutionContext context, ILogger log)
        {
            var client     = new ClovaClient();
            var cekRequest = await client.GetRequest(req.Headers["SignatureCEK"], req.Body);

            var cekResponse = new CEKResponse();

            switch (cekRequest.Request.Type)
            {
            case RequestType.LaunchRequest:
                cekResponse.AddText(IntroductionMessage);
                cekResponse.ShouldEndSession = false;
                break;

            case RequestType.IntentRequest:
            {
                var r = await HandleIntentAsync(cekRequest.Request.Intent.Name);

                cekResponse.AddText(r.ResponseMessage);

                // 最新記事が見つかったので LINE にプッシュ通知する
                if (r.Blog != null)
                {
                    var config = new ConfigurationBuilder()
                                 .SetBasePath(context.FunctionAppDirectory)
                                 .AddJsonFile("local.settings.json", true)
                                 .AddEnvironmentVariables()
                                 .Build();

                    var secret = config.GetValue <string>("LineMessagingApiSecret");

                    var messagingClient = new LineMessagingClient(secret);
                    await messagingClient.PushMessageAsync(
                        to : cekRequest.Session.User.UserId,
                        messages : new List <ISendMessage>
                        {
                            new TextMessage($"ちょまどさんの最新記事はこちら!"),
                            new TextMessage($@"タイトル『{r.Blog.Title}』
{r.Blog.Url}"),
                        });
                }
            }
            break;
            }

            return(new OkObjectResult(cekResponse));
        }
Example #12
0
        public async Task <IActionResult> Post()
        {
            CEKRequest request = await _client.GetRequest(
                Request.Headers["SignatureCEK"],
                Request.Body
                );

            var response = new CEKResponse();

            switch (request.Request.Type)
            {
            case RequestType.LaunchRequest:
            {
                response.AddText("こんにちは!これ食べれるニャンボットです。人間の食べ物を入力すると、これは猫が食べて大丈夫かどうかを答えるよ");
                response.ShouldEndSession = false;
                break;
            }

            case RequestType.SessionEndedRequest:
            {
                response.AddText("またね~");
                break;
            }

            case RequestType.IntentRequest:
            {
                switch (request.Request.Intent.Name)
                {
                case "CatIntent":             // "パン"
                {
                    var food = request.Request.Intent.Slots.FirstOrDefault().Value.Value;
                    // 食べれるものが渡ってくるので何か処理をする TODO!
                    response.AddText(text: $"{food}の話ですか?");

                    // LINE messaging に push
                    string accessToken = _configuration.GetValue <string>("LINEMessaginAPIKey");

                    var messagingClient = new LineMessagingClient(channelAccessToken: accessToken);
                    await messagingClient.PushMessageAsync(
                        to : request.Session.User.UserId,
                        messages : new List <ISendMessage>
                            {
                                new TextMessage($"{food}"),
                            }
                        );

                    response.ShouldEndSession = false;
                    break;
                }

                case "ChomadoIntent":             // "ちょまど"
                {
                    response.AddText("ちょまどさん、さすがオトナです!素敵!すばらしい!松屋!");
                    response.ShouldEndSession = false;
                    break;
                }

                case "Clova.GuideIntent":
                {
                    response.AddText("パン、と言ってみてください。");
                    response.ShouldEndSession = false;
                    break;
                }
                }
                break;
            }
            }
            return(new OkObjectResult(response));
        }
Example #13
0
        public void Push(string targetUserID, string message)
        {
            LineMessagingClient lineMessagingClient = new LineMessagingClient(_accessToken);

            lineMessagingClient.PushMessageAsync(targetUserID, message);
        }
Example #14
0
        public static async Task <IActionResult> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            string requestContent = await req.Content.ReadAsStringAsync();

            if (string.IsNullOrWhiteSpace(requestContent))
            {
                return(new BadRequestObjectResult("Empty content is given"));
            }

            var eventGridSubscriber = new TraceableEventGridSubscriber();

            eventGridSubscriber.AddOrUpdateCustomEventMapping(typeof(MessagesEventReply).FullName, typeof(MessagesEventReply));
            var eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestContent).ToList();

            var subscriptionValidationEvent =
                eventGridEvents.FirstOrDefault(x => x.Data is SubscriptionValidationEventData);

            if (subscriptionValidationEvent != null)
            {
                var eventData = (SubscriptionValidationEventData)subscriptionValidationEvent.Data;
                log.Info($"Got SubscriptionValidation event data, validationCode: {eventData.ValidationCode},  validationUrl: {eventData.ValidationUrl}, topic: {subscriptionValidationEvent.Topic}");

                return(new OkObjectResult(new SubscriptionValidationResponse
                {
                    ValidationResponse = eventData.ValidationCode
                }));
            }

            var eventGridEndpoint     = Environment.GetEnvironmentVariable("EventGridTopicEndpoint", EnvironmentVariableTarget.Process);
            var eventGridKey          = Environment.GetEnvironmentVariable("EventGridTopicKey", EnvironmentVariableTarget.Process);
            var redisConnectionString = Environment.GetEnvironmentVariable("RedisConnectionString", EnvironmentVariableTarget.Process);

            if (string.IsNullOrWhiteSpace(eventGridEndpoint) || string.IsNullOrWhiteSpace(eventGridKey) || string.IsNullOrWhiteSpace(redisConnectionString))
            {
                throw new Exception(
                          "Lacks of Environment Variable: 'EventGridTopicEndpoint' or 'EventGridTopicKey' or 'RedisConnectionString'");
            }

            Parallel.ForEach(eventGridEvents, eventGridEvent =>
            {
                try
                {
                    var traceableEventData = (TraceableEventData)eventGridEvent.Data;

                    if (traceableEventData.Data is MessagesEventReply messagesEventReply)
                    {
                        var redisHelper  = new AzureRedisHelper(redisConnectionString);
                        var configString = redisHelper.GetRedis(traceableEventData.TraceToken) ??
                                           throw new Exception($"Get empty serialized LineMessagingApiConfig string with key '{traceableEventData.TraceToken}'");
                        var config = JsonConvert.DeserializeObject <LineMessagingApiConfig>(configString) ??
                                     throw new Exception($"Failed to deserialize LineMessagingApiConfig string with '{configString}'");

                        Parallel.ForEach(messagesEventReply.MessageReplys.GroupBy(x => x.ReplyToken), messageReplyGroupByReplyToken =>
                        {
                            var sendMessages = messageReplyGroupByReplyToken.Select(messageReply => SendMessageConverter.ConvertToISendMessages(messageReply, log)).ToList();
                            var lineId       = messageReplyGroupByReplyToken.First().LineId;
                            var lineClient   = new LineMessagingClient(config.ChannelAccessToken);
                            try
                            {
                                lineClient.ReplyMessageAsync(
                                    messageReplyGroupByReplyToken.Key,
                                    sendMessages
                                    ).GetAwaiter().GetResult();
                            }
                            catch (LineResponseException ex)
                            {
                                log.Warning(ex.ToString());
                                try
                                {
                                    lineClient.PushMessageAsync(
                                        lineId,
                                        sendMessages
                                        ).GetAwaiter().GetResult();
                                }
                                catch (Exception exi)
                                {
                                    log.Warning(exi.ToString());
                                }
                            }
                            catch (Exception ex)
                            {
                                log.Warning(ex.ToString());
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.ToString());
                }
            });

            return(new OkObjectResult("Ok"));
        }
Example #15
0
        public static async Task <IActionResult> Line(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ExecutionContext context,
            ILogger log)
        {
            var client     = new ClovaClient();
            var cekRequest = await client.GetRequest(req.Headers["SignatureCEK"], req.Body);

            var cekResponse = new CEKResponse();

            switch (cekRequest.Request.Type)
            {
            // 起動時に飛んでくる intent
            case RequestType.LaunchRequest:
                cekResponse.AddText(IntroductionMessage[0]);
                cekResponse.ShouldEndSession = false;
                break;

            // ユーザ定義の intent
            case RequestType.IntentRequest:
            {
                // slot を抜き出す
                CEK.CSharp.Models.Slot when = null;
                cekRequest.Request.Intent.Slots?.TryGetValue(key: "when", value: out when);
                // intent ごとに処理を振り分け
                var texts = await HandleIntentAsync(cekRequest.Request.Intent.Name, when?.Value ?? "今日", Platforms.Clova);

                if (texts.Any())
                {
                    foreach (var text in texts)
                    {
                        cekResponse.AddText(text);
                    }
                }
                else
                {
                    cekResponse.AddText("予定はありません。");
                }

                // 予定があったら LINE にプッシュ通知する
                if (texts.Any())
                {
                    var config = Models.AuthenticationConfigModel.ReadFromJsonFile("appsettings.json");
                    var secret = config.LineMessagingApiSecret;

                    var textMessages = new List <ISendMessage>();

                    textMessages.Add(new TextMessage("ちょまどさんの予定はこちら!"));
                    foreach (var text in texts)
                    {
                        textMessages.Add(new TextMessage(text));
                    }

                    var messagingClient = new LineMessagingClient(secret);
                    await messagingClient.PushMessageAsync(
                        //to: cekRequest.Session.User.UserId,
                        to : config.MessagingUserId,
                        messages : textMessages
                        );
                }
            }
            break;
            }
            return(new OkObjectResult(cekResponse));
        }
Example #16
0
        private static async Task <Task> HandleIntentRequestAsync(CEKRequest request, CEKResponse response)
        {
            void fillSlotIfExist(string slotName, ref string word)
            {
                if (request.Request.Intent.Slots?.ContainsKey(slotName) ?? false)
                {
                    word = request.Request.Intent.Slots[slotName].Value;
                }
            }

            switch (request.Request.Intent.Name)
            {
            case IntentNames.DefaultIntent:
            {
                string word = null;
                fillSlotIfExist(SlotNames.NamamugiNamagomeNamatamago, ref word);
                fillSlotIfExist(SlotNames.SyusyaSentaku, ref word);

                // 滑舌オーケー
                if (!string.IsNullOrEmpty(word))
                {
                    // LINE messaging に投げる
                    var messagingClient = new LineMessagingClient(channelAccessToken: Keys.token);
                    await messagingClient.PushMessageAsync(
                        to : Keys.userId,
                        messages : new List <ISendMessage>
                        {
                            new TextMessage(string.Format(Messages.LineCongratsMessage, word)),
                        }
                        );

                    // Clova に喋らせる
                    response.ShouldEndSession = true;
                    response.AddText(Messages.GenerateCongratsMessage(word));
                }
                // 滑舌ダメです
                else
                {
                    var messagingClient = new LineMessagingClient(channelAccessToken: Keys.token);
                    await messagingClient.PushMessageAsync(
                        to : Keys.userId,
                        messages : new List <ISendMessage>
                        {
                            new TextMessage(Messages.LineWrongMessage),
                        }
                        );

                    response.ShouldEndSession = false;
                    response.AddText(Messages.WrongPronunciationMessage);
                }

                break;
            }

            default:
                // noop
                break;
            }

            return(Task.CompletedTask);
        }
Example #17
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ExecutionContext context, ILogger log)
        {
            //リクエストボディのJSONを検証してC#のクラスに変換
            var clovaRequest = await new ClovaClient().GetRequest(req.Headers["SignatureCEK"], req.Body);
            //返事を作成
            var clovaResponse = new CEKResponse();

            switch (clovaRequest.Request.Type)
            {
            case RequestType.LaunchRequest:
                //起動時の処理
                clovaResponse.AddText(IntroductionMessage);
                clovaResponse.ShouldEndSession = false;
                break;

            case RequestType.SessionEndedRequest:
                //終了時の処理
                clovaResponse.AddText(SessionEndedMessege);
                break;

            case RequestType.IntentRequest:
                // インテントの処理
                switch (clovaRequest.Request.Intent.Name)
                {
                case MenuIntent:
                    // インテント
                    var timeZone = "";
                    if (clovaRequest.Request.Intent.Slots != null && clovaRequest.Request.Intent.Slots.TryGetValue(SlotTimeZone, out var timeZoneSlot))
                    {
                        // 対象がある場合は、スロットから取得する
                        timeZone = timeZoneSlot.Value;
                    }
                    var menu = "ごはん";
                    // メニューを朝、昼、夜、で分けてランダムで取得しています。
                    if (timeZone.Equals("朝"))
                    {
                        menu = new[] { "卵焼き", "目玉焼き", "おにぎり", "ホットドッグ", "ヨーグルト" }[new Random().Next(5)];
                    }
                    else if (timeZone.Equals("昼"))
                    {
                        menu = new[] { "ラーメン", "ざるそば", "たこ焼き", "豚ヒレカツでふわふわカツ丼", "焼きそばナポリタン" }[new Random().Next(5)];
                    }
                    else if (timeZone.Equals("夜"))
                    {
                        menu = new[] { "オムライス", "山椒たっぷりの讃岐うどん", "ドライカレー", "じゃがいもステーキのタルタルソースがけ", "チキン南蛮弁当" }[new Random().Next(5)];
                    }
                    else
                    {
                        clovaResponse.AddText(NoSlotMessege);
                        clovaResponse.ShouldEndSession = false;
                        break;
                    }
                    // LINE にプッシュ通知する
                    var config = new ConfigurationBuilder()
                                 .SetBasePath(context.FunctionAppDirectory)
                                 .AddJsonFile("local.settings.json", true)
                                 .AddEnvironmentVariables()
                                 .Build();

                    var secret          = config.GetValue <string>("LineMessagingApiSecret");
                    var messagingClient = new LineMessagingClient(secret);

                    await messagingClient.PushMessageAsync(
                        to : clovaRequest.Session.User.UserId,
                        messages : new List <ISendMessage>
                    {
                        new TextMessage($"今日あなたが食べたい{timeZone}ご飯は {menu} です。"),
                    });

                    clovaResponse.AddText($"今日あなたが食べたい{timeZone}ご飯は {menu} です。");


                    break;

                default:
                    // 認識できなかったインテント
                    clovaResponse.AddText(NoSlotMessege);
                    clovaResponse.ShouldEndSession = false;     // スキルを終わらせないように設定する
                    break;
                }
                break;
            }
            // レスポンスとして作成した返事の内容を返す
            return(new OkObjectResult(clovaResponse));
        }
Example #18
0
        public static async Task Run(
            [QueueTrigger("aladin-newbooks")] CloudQueueMessage message,
            [Table("BookEntity")] CloudTable bookTable,
            [Table("LineAccount")] CloudTable lineAccountTable,
            [Table("Credentials", "Twitter")] CloudTable credentialsTable,
            ILogger log,
            CancellationToken cancellationToken)
        {
            try
            {
                var    queueItem  = JsonConvert.DeserializeObject <QueueItem>(message.AsString);
                string categoryId = queueItem.CategoryId;

                var itemList       = new List <ItemLookUpResult.Item>();
                var batchOperation = new TableBatchOperation();

                foreach (int itemId in queueItem.ItemList)
                {
                    var lookUpResult = await LookUpItemAsync(itemId);

                    foreach (var item in lookUpResult.item)
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        var bookEntity = new BookEntity();
                        bookEntity.PartitionKey = categoryId;
                        bookEntity.RowKey       = itemId.ToString();
                        bookEntity.Name         = item.title;

                        batchOperation.InsertOrReplace(bookEntity);
                        itemList.Add(item);
                    }
                }

                if (itemList.Count > 0 && !cancellationToken.IsCancellationRequested)
                {
                    var tokens = await Twitter.Utils.CreateTokenAsync(credentialsTable, queueItem.CategoryId);

                    var tweetTask = tokens != null?TweetItemsAsync(tokens, itemList, cancellationToken) : Task.CompletedTask;

                    // 배치처리는 파티션 키가 동일해야하고, 100개까지 가능하다는데...
                    // 일단 파티션 키는 전부 동일하게 넘어올테고, 100개 넘을일은 없겠...지?
                    var tableTask = bookTable.ExecuteBatchAsync(batchOperation);

                    // 트위터와 테이블 쓰기 작업을 먼저한다.
                    await Task.WhenAll(tweetTask, tableTask);

                    // 라인 메시지를 보낼때 리미트가 걸려 예외가 발생하므로 라인만 따로 한다.
                    if (queueItem.CategoryId == Aladin.Const.CategoryID.Comics)
                    {
                        await SendLineMessageAsync(lineAccountTable, itemList, log);
                    }
                }
            }
            catch (Exception e)
            {
                log.LogError(e.Message);

                if (e is LineResponseException lineEx)
                {
                    if (lineEx.StatusCode != HttpStatusCode.TooManyRequests)
                    {
                        // 에러 발생시 내 계정으로 예외 정보를 보냄.
                        string adminLineId = Environment.GetEnvironmentVariable("LINE_ADMIN_USER_ID");
                        var    error       = new
                        {
                            Type       = e.GetType().ToString(),
                            Message    = e.Message,
                            StackTrace = e.StackTrace
                        };
                        string json = JsonConvert.SerializeObject(error, Formatting.Indented);
                        await lineMessagingClient.PushMessageAsync(adminLineId, json);
                    }
                }
            }
        }
Example #19
0
        public static async Task <IActionResult> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            string requestContent = await req.Content.ReadAsStringAsync();

            if (string.IsNullOrWhiteSpace(requestContent))
            {
                return(new BadRequestObjectResult("Empty content is given"));
            }

            var eventGridSubscriber = new TraceableEventGridSubscriber();

            eventGridSubscriber.AddOrUpdateCustomEventMapping(typeof(MessagesEventReply).FullName, typeof(MessagesEventReply));
            var eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestContent).ToList();

            var subscriptionValidationEvent =
                eventGridEvents.FirstOrDefault(x => x.Data is SubscriptionValidationEventData);

            if (subscriptionValidationEvent != null)
            {
                var eventData = (SubscriptionValidationEventData)subscriptionValidationEvent.Data;
                log.Info($"Got SubscriptionValidation event data, validationCode: {eventData.ValidationCode},  validationUrl: {eventData.ValidationUrl}, topic: {subscriptionValidationEvent.Topic}");

                return(new OkObjectResult(new SubscriptionValidationResponse
                {
                    ValidationResponse = eventData.ValidationCode
                }));
            }

            var eventGridEndpoint    = Environment.GetEnvironmentVariable("EventGridTopicEndpoint", EnvironmentVariableTarget.Process);
            var eventGridKey         = Environment.GetEnvironmentVariable("EventGridTopicKey", EnvironmentVariableTarget.Process);
            var storageConnectString =
                Environment.GetEnvironmentVariable("AzureStorageConnectionString", EnvironmentVariableTarget.Process);

            if (string.IsNullOrWhiteSpace(eventGridEndpoint) || string.IsNullOrWhiteSpace(eventGridKey) || string.IsNullOrWhiteSpace(storageConnectString))
            {
                throw new Exception(
                          "Lacks of Environment Variable: 'EventGridTopicEndpoint' or 'EventGridTopicKey' or 'AzureStorageConnectionString'");
            }

            var cachedConfig = new ConcurrentDictionary <string, LineMessagingApiConfig>();

            Parallel.ForEach(eventGridEvents, eventGridEvent =>
            {
                try
                {
                    var traceableEventData = (TraceableEventData)eventGridEvent.Data;
                    if (traceableEventData.Data is MessagesEventReply messagesEventReply)
                    {
                        if (!cachedConfig.TryGetValue(messagesEventReply.ChannelId, out LineMessagingApiConfig config))
                        {
                            var azureTableHelper = new AzureTableHelper <LineMessagingApiConfig>(
                                storageConnectString,
                                "LineMessagingApiConfigs");
                            config = azureTableHelper.Select($"ibo-line-{messagesEventReply.ChannelId}", "channel-config");
                            if (!cachedConfig.TryAdd(messagesEventReply.ChannelId, config))
                            {
                                log.Warning("Failed to cached line config");
                            }
                        }

                        Parallel.ForEach(messagesEventReply.MessageReplys, async messageReply =>
                        {
                            var sendMessage = SendMessageConverter.ConvertToISendMessages(messageReply, log);
                            var lineClient  = new LineMessagingClient(config.ChannelAccessToken);
                            try
                            {
                                await lineClient.PushMessageAsync(
                                    messageReply.LineId,
                                    new List <ISendMessage>
                                {
                                    sendMessage
                                }
                                    );
                            }
                            catch (Exception ex)
                            {
                                log.Warning(ex.ToString());
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    log.Warning(ex.ToString());
                }
            });

            return(new OkObjectResult("Ok"));
        }
Example #20
0
 public async Task SendTextMessage(string to, string[] messages)
 {
     await _lineMessagingClient.PushMessageAsync(to, messages).ConfigureAwait(false);
 }
Example #21
0
        public async Task <IActionResult> Post()
        {
            CEKRequest request = await _client.GetRequest(
                Request.Headers["SignatureCEK"],
                Request.Body
                );

            var response = new CEKResponse();

            try
            {
                switch (request.Request.Type)
                {
                case RequestType.LaunchRequest:
                {
                    response.AddText("こんにちは!これ食べれるニャンボットです。人間の食べ物を入力すると、これは猫が食べて大丈夫かどうかを答えるよ");
                    response.ShouldEndSession = false;
                    break;
                }

                case RequestType.SessionEndedRequest:
                {
                    response.AddText("またね~");
                    break;
                }

                case RequestType.IntentRequest:
                {
                    switch (request.Request.Intent.Name)
                    {
                    case "HelloIntent":
                    {
                        response.AddText("こんにちは!これ食べれるニャンボットだよ!");
                        response.ShouldEndSession = false;
                        break;
                    }

                    case "ChomadoIntent":             // "ちょまど"
                    {
                        response.AddText("ちょまどさん、さすがオトナです!素敵!すばらしい!松屋!");
                        response.ShouldEndSession = false;
                        break;
                    }

                    case "Clova.GuideIntent":
                    {
                        response.AddText("パン、と言ってみてください。");
                        response.ShouldEndSession = false;
                        break;
                    }

                    case "CatIntent":             // "パン"
                    {
                        var food = request.Request.Intent.Slots.FirstOrDefault().Value.Value;
                        // 食べれるものが渡ってくるので何か処理をする TODO!
                        response.AddText(text: $"{food}の話ですね?");

                        // QnA から答えを取り出す
                        var client = _httpClientFactory.CreateClient();
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("EndpointKey", _configuration.GetValue <string>("EndpointKey"));
                        var content          = new StringContent(JsonConvert.SerializeObject(new { question = food }), Encoding.UTF8, "application/json");
                        var qnaMakerResponse = await client.PostAsync(
                            $"{_configuration.GetValue<string>("Hostname")}/knowledgebases/{_configuration.GetValue<string>("KbId")}/generateAnswer",
                            content);

                        qnaMakerResponse.EnsureSuccessStatusCode();
                        var answers = await qnaMakerResponse.Content.ReadAsAsync <QnAMakerResponse>();

                        // LINE messaging に push
                        string accessToken = _configuration.GetValue <string>("LINEMessaginAPIKey");
                        string myUserId    = _configuration.GetValue <string>("myUserID");

                        var answer = answers.Answers?.FirstOrDefault()?.AnswerText;
                        if (!string.IsNullOrEmpty(answer))
                        {
                            response.AddText(answer.Contains("OK") ? $"{food}は食べられます。詳細を LINE に送ります。" : $"{food}は食べられません。");
                            var messagingClient = new LineMessagingClient(channelAccessToken: accessToken);
                            await messagingClient.PushMessageAsync(
                                // to: request.Session.User.UserId,
                                to : myUserId,
                                messages : new List <ISendMessage>
                                    {
                                        new TextMessage($"{food}"),
                                        new TextMessage($"解説はこれだよ"),
                                        new TextMessage(answer),
                                    }
                                );
                        }
                        else
                        {
                            response.AddText($"{food}が見つかりませんでした。");
                        }
                        break;
                    }
                    }
                    break;
                }
                }
            }
            catch (Exception ex)
            {
                response.AddText(ex.ToString());
            }

            return(new OkObjectResult(response));
        }
        public async Task SendTextMessage(LineMessageRequestModel lineMessageRequest)
        {
            _lineMessagingClient = new LineMessagingClient(lineMessageRequest.LineChannelAccessToken);

            await _lineMessagingClient.PushMessageAsync(lineMessageRequest.To, lineMessageRequest.Messages).ConfigureAwait(false);
        }