-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBotHandler.cs
128 lines (112 loc) · 4.28 KB
/
BotHandler.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
using System.Globalization;
using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
public enum WeekOption
{
Current,
Next
}
public enum DayOption
{
Today,
Tomorrow,
}
// ReSharper disable once InconsistentNaming
public record HealthCheck(string? type);
namespace ReSchedule
{
public class BotHandler
{
private const string SetUpFunctionName = "setup";
private const string UpdateFunctionName = "handleupdate";
private readonly ILogger _logger;
private readonly Bot _bot;
private readonly string _accessKey;
public BotHandler(ILogger<BotHandler> logger, Bot bot)
{
_logger = logger;
_bot = bot;
var accessKey = Environment.GetEnvironmentVariable("AccessKey",
EnvironmentVariableTarget.Process);
if (accessKey == null)
{
_logger.LogError("Access key is not set");
throw new Exception("Access key is not set!");
}
_accessKey = accessKey;
}
[Function("setup")]
public async Task<HttpResponseData> Setup(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",Route="setup/{key}")] HttpRequestData req,
string key)
{
_logger.LogInformation($"Called {nameof(Setup)}");
var response = req.CreateResponse(HttpStatusCode.OK);
if (key != _accessKey)
{
_logger.LogWarning("Keys didn't match");
response = req.CreateResponse(HttpStatusCode.Forbidden);
response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
await response.WriteStringAsync($"Your key {key} was not accepted");
return response;
}
var ngrokUrl = Environment.GetEnvironmentVariable("NGROK");
var isDevelopment = !string.IsNullOrEmpty(ngrokUrl);
if (isDevelopment) System.Diagnostics.Trace.WriteLine("Using ngrok");
var handleUpdateFunctionUrl = isDevelopment
? $"{ngrokUrl}/api/handleupdate/{_accessKey}"
: req.Url.ToString().Replace(SetUpFunctionName, UpdateFunctionName,
ignoreCase: true, culture: CultureInfo.InvariantCulture);
System.Diagnostics.Trace.WriteLine(handleUpdateFunctionUrl);
_logger.LogInformation("{}",handleUpdateFunctionUrl);
await _bot.SetWebhook(handleUpdateFunctionUrl);
response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
await response.WriteStringAsync($"Your key was accepted");
return response;
}
[Function(UpdateFunctionName)]
public async Task Run([HttpTrigger(AuthorizationLevel.Anonymous, "post",Route="handleupdate/{key}")] HttpRequestData req, string key)
{
if (key != _accessKey)
{
_logger.LogInformation("Key was not accepted");
return;
}
var request = await req.ReadAsStringAsync();
if (request == null)
{
_logger.LogInformation("Got null request");
return;
}
if (JsonConvert.DeserializeObject<HealthCheck>(request) is var healthCheck && healthCheck?.type!=null)
{
_logger.LogInformation("Received healthcheck request");
return;
}
var update = JsonConvert.DeserializeObject<Update>(request);
if (update==null)
{
_logger.LogInformation("Can't deserialize request");
return;
}
try
{
var handler = update.Type switch
{
UpdateType.Message => _bot.BotOnMessageReceived(update.Message!),
_ => Bot.UnknownUpdateHandlerAsync(update)
};
await handler;
}
catch (Exception exception)
{
_logger.LogError(exception,"Error while calling handler");
}
}
}
}