-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWorker.cs
208 lines (162 loc) · 8.23 KB
/
Worker.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#nullable disable
using Newtonsoft.Json;
using System.Reflection;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using HortBot.Model;
using HortBot.Model.Kids;
using HortBot.Model.Presences;
using HortBot.Service;
using Microsoft.Extensions.Options;
namespace HortBot
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly Config _telegramBotConfig;
private string chatIdFilePath = string.Empty;
private List<long> ChatIds = new();
private List<PresencesPerUser> presencesPerUsers = new();
private TelegramBotClient botClient;
public Worker(ILogger<Worker> logger, IOptions<Config> configuration)
{
Console.WriteLine("TelegramBotToken from Config: " + configuration.Value.TelegramBotToken);
if (string.IsNullOrEmpty(configuration.Value.TelegramBotToken))
{
Console.WriteLine("Environment Variables not emtpy");
_telegramBotConfig = new Config();
_telegramBotConfig.TelegramBotToken = Environment.GetEnvironmentVariable("TELEGRAMBOTTOKEN");
_telegramBotConfig.HortProLogin = new HortProLogin();
_telegramBotConfig.HortProLogin.Email = Environment.GetEnvironmentVariable("EMAIL");
_telegramBotConfig.HortProLogin.Email = Environment.GetEnvironmentVariable("PASSWORD");
}
else
{
Console.WriteLine("Environment Variables are emtpy");
_telegramBotConfig = configuration.Value;
}
Console.WriteLine("TELEGRAMBOTTOKEN: " + _telegramBotConfig.TelegramBotToken);
Console.WriteLine("EMAIL: " + _telegramBotConfig.HortProLogin.Email);
Console.WriteLine("PASSWORD: " + _telegramBotConfig.HortProLogin.Password);
chatIdFilePath = "ChatIds.json"; /*Path.Combine(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location), "ChatIds.json");*/
if (System.IO.File.Exists(chatIdFilePath))
ChatIds = JsonConvert.DeserializeObject<List<long>>(System.IO.File.ReadAllText(chatIdFilePath));
else
ChatIds = JsonConvert.DeserializeObject<List<long>>(System.IO.File.ReadAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location), "ChatIds.json")));
botClient = new TelegramBotClient(_telegramBotConfig.TelegramBotToken);
using CancellationTokenSource cts = new();
ReceiverOptions receiverOptions = new()
{
//ThrowPendingUpdates = false,
AllowedUpdates = Array.Empty<UpdateType>()
};
botClient.StartReceiving(
updateHandler: HandleUpdateAsync,
pollingErrorHandler: HandlePollingErrorAsync,
receiverOptions: receiverOptions,
cancellationToken: cts.Token
);
var me = botClient.GetMeAsync().Result;
_logger = logger;
_logger.LogInformation($"Ich bin der Bot {me.Username}");
}
async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
// Only process Message updates: https://core.telegram.org/bots/api#message
if (update.Message is not { } message)
return;
if (message.Text is not { } messageText)
return;
var chatId = message.Chat.Id;
if (message.Entities?.Length == 1 && message.EntityValues.First() == "/start")
{
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "Willkommen im Hort-Bot von Denis",
cancellationToken: cancellationToken);
if (ChatIds.Find(x => x == chatId) == 0) { ChatIds.Add(chatId); }
System.IO.File.WriteAllText(chatIdFilePath, JsonConvert.SerializeObject(ChatIds));
}
Console.WriteLine($"Received a '{messageText}' message in chat {chatId}.");
}
Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
var ErrorMessage = exception switch
{
ApiRequestException apiRequestException
=> $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
_ => exception.ToString()
};
Console.WriteLine(ErrorMessage);
return Task.CompletedTask;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var api = new HortApi(_telegramBotConfig);
var kid = await api.GetObjectAsync<Kids>("https://elternportal.hortpro.de/api/kids");
if (kid != null && kid.Success)
{
foreach (var chatid in ChatIds)
{
//Message sentMessage = await botClient.SendTextMessageAsync(
//chatId: chatid,
//text: "Der Hort-Bot wurde neugestartet");
}
while (!stoppingToken.IsCancellationRequested)
{
try
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
var presences = await api.GetObjectAsync<Presences>($"https://elternportal.hortpro.de/api/kids/{kid.Data[0].Id}/presences?start=0&limit=5");
var today = presences.Data.Rows.Find(x => x.DateStart.Value.OnlyDate() == DateTime.Now.Date.OnlyDate());
var StartDate = today?.DateStart;
var EndDate = today?.DateEnd;
foreach (var chatid in ChatIds)
{
var p = presencesPerUsers.Find(x => x.ChatId == chatid);
if (p == null)
{
presencesPerUsers.Add(new PresencesPerUser { ChatId = chatid });
p = presencesPerUsers.Find(x => x.ChatId == chatid);
}
p.DateStart = StartDate;
p.DateEnd = EndDate;
if (StartDate == null)
p.StartMsgSent = false;
if (EndDate == null)
p.EndMsgSent = false;
if (p.DateStart != null && p.DateEnd == null && (p.StartMsgSent != true))
{
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatid,
text: $"{kid.Data[0].FirstName} ist seit {p.DateStart:HH:mm} Uhr im Hort");
p.StartMsgSent = true;
}
else if (p.DateStart != null && p.DateEnd != null && (p.EndMsgSent != true))
{
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatid,
text: $"{kid.Data[0].FirstName} ist um {p.DateEnd:HH:mm} Uhr losgefahren");
p.EndMsgSent = true;
}
else if (p.DateStart == null && p.DateEnd == null)
{
//Message sentMessage = await botClient.SendTextMessageAsync(
//chatId: chatid,
//text: $"{kid.Data[0].FirstName} ist nicht im Hort");
}
}
await Task.Delay(60_000, stoppingToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Worker Exception at: {time}", DateTimeOffset.Now);
}
}
}
}
}
}