forked from javiermolinar/ServerlessTelegramBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTelegramBotWebHook.cs
84 lines (72 loc) · 3.15 KB
/
TelegramBotWebHook.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Telegram.Bot;
using Telegram.Bot.Types;
using Microsoft.Azure.EventGrid;
using Microsoft.Azure.EventGrid.Models;
using System;
using System.Collections.Generic;
namespace TelegramBot
{
public class TelegramBotWebHook
{
private const string menu = "🍔 Hamburger\n🍅 Gazpacho\n🥚Tortilla";
private string topicHostname = new Uri(Environment.GetEnvironmentVariable("TopicHostName")).Host;
private readonly ITelegramBotClient botClient;
private readonly IEventGridClient eGClient;
public TelegramBotWebHook(ITelegramBotClient client, IEventGridClient eventGridClient){
botClient = client;
eGClient = eventGridClient;
}
[FunctionName("TelegramBotWebHook")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ExecutionContext context)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var update = JsonConvert.DeserializeObject<Update>(requestBody);
await HandleResponseAsync(update);
return new OkResult();
}
private async Task HandleResponseAsync(Update update){
switch(update.Message?.Text){
case "/start" : await HandleStartAsync(update.Message.Chat);
break;
case string message when message.Contains("/order") : await HandleOrderAsync(update.Message.Chat,message);
break;
default: await HandleUnexpectedMessageAsync(update.Message.Chat);
break;
}
}
private async Task HandleOrderAsync(ChatId chat, string message){
var order = message.Split("/order")[1];
await eGClient.PublishEventsAsync(topicHostname, new List<EventGridEvent>() { GetEventGridEventForOrder(order, chat.Identifier) });
await botClient.SendTextMessageAsync(
chatId: chat,
text: $"Tu pedido de {order} ha sido procesado");
}
private static EventGridEvent GetEventGridEventForOrder(string order, long chatId) =>
new EventGridEvent()
{
Id = chatId.ToString(),
EventTime = DateTime.UtcNow,
DataVersion = "v1",
EventType = "Bot.Order.Received",
Data = order,
Subject = "Order"
};
private async Task HandleUnexpectedMessageAsync(ChatId chat){
await botClient.SendTextMessageAsync(
chatId: chat,
text: "Perdona no te he entendido:\n" + menu);
}
private async Task HandleStartAsync(ChatId chat) =>
await botClient.SendTextMessageAsync(
chatId: chat,
text: "Para pedir cualquier plato del menu escribe /order seguido del nombre del plato:\n" + menu);
}
}