forked from wiz0u/YourEasyBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBotBase.cs
358 lines (325 loc) · 11.6 KB
/
BotBase.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using static System.Threading.Tasks.Task;
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable MemberCanBeProtected.Global
namespace Wizou.EasyBot;
/// <summary>
/// Derive from this class to create your simple bot
/// </summary>
public class BotBase
{
private int _lastUpdateId = -1;
readonly CancellationTokenSource _cancel = new();
readonly Dictionary<long, TaskInfo> _tasks = new();
/// <summary>
/// <see cref="TelegramBotClient" /> for sending Messages etc.
/// </summary>
public readonly TelegramBotClient Bot;
/// <summary>
/// Public base constructor that takes Bot Token for <see cref="TelegramBotClient" />
/// </summary>
/// <param name="logger">A logger for your needs</param>
/// <param name="botToken">Telegram Bot Token</param>
// ReSharper disable once SuggestBaseTypeForParameterInConstructor
public BotBase(string botToken, ILogger<BotBase>? logger = null)
{
Bot = new(botToken);
Me = Task.Run(() => Bot.GetMeAsync()).Result;
Logger = logger;
CommandHandler = new('/');
CommandHandler.OnWrongScopeCommand += async (ctx, command, isPrivateChat) =>
{
var scope = $"{(isPrivateChat ? "Private" : "Group")} chat";
await Bot.SendTextMessageAsync(ctx.Chat, $"Sorry, I can't do {command.Name} in {scope}");
Logger?.LogWarning("{UserId} invoked command '{CommandName}' in wrong scope: {Scope} Context: {ctx}",
ctx.User.Id, command.Name, scope, JsonConvert.SerializeObject(ctx));
};
CommandHandler.OnUnknownCommand += async (ctx, _) => await Bot.SendTextMessageAsync(ctx.Chat, UnknownCommandResponse);
}
/// <summary>
/// An <see cref="ILogger" /> for your needs
/// </summary>
public ILogger? Logger { get; }
/// <summary>
/// Response for unknown commands
/// </summary>
public string UnknownCommandResponse { get; set; } = "I don't know that command";
/// <summary>
/// Basic information about Bot
/// </summary>
public User Me { get; private set; } = null!;
/// <summary>
/// Your Bot's <see cref="User.Username" />
/// </summary>
public string BotName => Me.Username!;
/// <summary>
/// A simple Command Handler
/// </summary>
public CommandHandler CommandHandler { get; }
/// <summary>
/// When overriden Handles the updates in Private chats
/// </summary>
/// <param name="updateContext"></param>
/// <returns></returns>
public virtual Task OnPrivateChat(UpdateContext updateContext)
=> CompletedTask;
/// <summary>
/// When overriden Handles the updates in Group chats
/// </summary>
/// <param name="updateContext">Update event context</param>
/// <returns></returns>
public virtual Task OnGroupChat(UpdateContext updateContext)
=> CompletedTask;
/// <summary>
/// When overriden Handles the updates in Channels
/// </summary>
/// <param name="channel">Object that represents a channel</param>
/// <param name="update">Update event information</param>
/// <returns></returns>
public virtual Task OnChannel(Chat channel, UpdateInfo update)
=> CompletedTask;
/// <summary>
/// </summary>
/// <param name="update">Update event information</param>
/// <returns></returns>
public virtual Task OnOtherEvents(UpdateInfo update)
=> CompletedTask;
/// <summary>
/// Synchronous version of <see cref="RunAsync" />
/// </summary>
public void Run()
=> RunAsync().Wait();
/// <summary>
/// Delegate that handles the exceptions in update loop
/// </summary>
public event Func<Exception, Task> OnException = _ => CompletedTask;
/// <summary>
/// Starts the bot
/// </summary>
/// <returns></returns>
public async Task RunAsync()
{
Logger?.LogInformation("Press Escape to stop the bot");
while (true)
{
Update[] updates;
try
{
updates = await Bot.GetUpdatesAsync(_lastUpdateId + 1, timeout: 5);
}
catch (Exception e)
{
await OnException.Invoke(e);
continue;
}
foreach (var update in updates)
HandleUpdate(update);
if (!Console.KeyAvailable)
continue;
if (Console.ReadKey().Key == ConsoleKey.Escape)
break;
}
_cancel.Cancel();
}
public async Task<string> CheckWebhook(string url)
{
var webhookInfo = await Bot.GetWebhookInfoAsync();
string result = $"{BotName} is running";
if (webhookInfo.Url != url)
{
await Bot.SetWebhookAsync(url);
result += " and now registered as Webhook";
}
return $"{result}\n\nLast webhook error: {webhookInfo.LastErrorDate} {webhookInfo.LastErrorMessage}";
}
/// <summary>Use this method in your WebHook controller</summary>
public void HandleUpdate(Update update)
{
if (update.Id < _lastUpdateId)
return;
_lastUpdateId = update.Id;
switch (update.Type)
{
case UpdateType.Message:
HandleUpdate(update, UpdateKind.NewMessage, update.Message!);
break;
case UpdateType.EditedMessage:
HandleUpdate(update, UpdateKind.EditedMessage, update.EditedMessage!);
break;
case UpdateType.ChannelPost:
HandleUpdate(update, UpdateKind.NewMessage, update.ChannelPost!);
break;
case UpdateType.EditedChannelPost:
HandleUpdate(update, UpdateKind.EditedMessage, update.EditedChannelPost!);
break;
case UpdateType.CallbackQuery:
HandleUpdate(update, UpdateKind.CallbackQuery, update.CallbackQuery!.Message!);
break;
case UpdateType.MyChatMember:
HandleUpdate(update, UpdateKind.OtherUpdate, chat: update.MyChatMember!.Chat);
break;
case UpdateType.ChatMember:
HandleUpdate(update, UpdateKind.OtherUpdate, chat: update.ChatMember!.Chat);
break;
case UpdateType.Poll:
case UpdateType.Unknown:
case UpdateType.PollAnswer:
case UpdateType.InlineQuery:
case UpdateType.ShippingQuery:
case UpdateType.ChatJoinRequest:
case UpdateType.PreCheckoutQuery:
case UpdateType.ChosenInlineResult:
default:
HandleUpdate(update, UpdateKind.OtherUpdate);
break;
}
}
void HandleUpdate(Update update, UpdateKind updateKind, Message? message = null!, Chat? chat = null!)
{
TaskInfo taskInfo;
// ReSharper disable once ConstantNullCoalescingCondition
// ReSharper disable ConstantConditionalAccessQualifier
chat ??= message?.Chat;
var chatId = chat?.Id ?? 0;
lock (_tasks)
{
if (!_tasks.TryGetValue(chatId, out taskInfo!))
_tasks[chatId] = taskInfo = new();
}
var updateInfo = new UpdateInfo(taskInfo) { UpdateKind = updateKind, Update = update, Message = message! };
if (update.Type is UpdateType.CallbackQuery)
updateInfo.CallbackData = update.CallbackQuery!.Data!;
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (taskInfo._task != null)
{
lock (taskInfo._updates)
{
taskInfo._updates.Enqueue(updateInfo);
}
taskInfo._semaphore.Release();
return;
}
Func<Task> taskStarter = chat?.Type switch
{
ChatType.Private or ChatType.Group or ChatType.Supergroup when updateKind is UpdateKind.NewMessage && message!.Type is MessageType.Text &&
message.Text!.StartsWith(CommandHandler.Prefix) => async ()
=> await CommandHandler.HandleCommand(new(chat, message?.From!, updateInfo), chat.Type is ChatType.Private, BotName),
ChatType.Private => () => OnPrivateChat(new(chat, message?.From!, updateInfo)),
ChatType.Group or ChatType.Supergroup => () => OnGroupChat(new(chat, message?.From!, updateInfo)),
ChatType.Channel => () => OnChannel(chat, updateInfo),
_ => () => OnOtherEvents(updateInfo)
};
taskInfo._task = Task.Run(taskStarter).ContinueWith(_ => taskInfo._task = null!);
}
/// <summary>
/// Returns the next update kind, and changes current update info to new one
/// </summary>
/// <param name="update"></param>
/// <param name="ct"></param>
/// <returns></returns>
public async Task<UpdateKind> NextEvent(UpdateInfo update, CancellationToken ct = default)
{
using var bothCt = CancellationTokenSource.CreateLinkedTokenSource(ct, _cancel.Token);
var newUpdate = await ((IUpdateGetter)update).NextUpdate(bothCt.Token);
update.Message = newUpdate.Message;
update.CallbackData = newUpdate.CallbackData;
update.Update = newUpdate.Update;
return update.UpdateKind = newUpdate.UpdateKind;
}
/// <summary>
/// Returns the next button click update ignoring others
/// </summary>
/// <param name="update">Update Information</param>
/// <param name="buttonedMessage">Message with attached buttons</param>
/// <param name="ct">Cancellation Token</param>
/// <returns>Clicked buttons Callback Data. <br /> If the task is canceled - null</returns>
/// <exception cref="LeftTheChatException">If user left the chat while wait</exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public async Task<string?> NewButtonClick(UpdateInfo update, Message? buttonedMessage = null, CancellationToken ct = default)
{
while (true)
{
if (ct.IsCancellationRequested)
return null;
switch (await NextEvent(update, ct))
{
case UpdateKind.CallbackQuery:
if (buttonedMessage is null || update.Message.MessageId == buttonedMessage.MessageId)
return update.CallbackData;
break;
case UpdateKind.OtherUpdate when update.Update.MyChatMember is { NewChatMember.Status: ChatMemberStatus.Left or ChatMemberStatus.Kicked }:
throw new LeftTheChatException();
default:
throw new ArgumentOutOfRangeException(null);
case UpdateKind.None:
case UpdateKind.EditedMessage:
case UpdateKind.NewMessage:
break;
}
}
}
/// <summary>
/// Returns the next message category, and changes current update info to new one
/// </summary>
/// <param name="update"></param>
/// <param name="ct"></param>
/// <returns></returns>
/// <exception cref="LeftTheChatException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public async Task<MsgCategory> NewMessage(UpdateInfo update, CancellationToken ct = default)
{
while (true)
switch (await NextEvent(update, ct))
{
case UpdateKind.NewMessage when update.MsgCategory is MsgCategory.Text or MsgCategory.MediaOrDoc or MsgCategory.StickerOrDice:
return update.MsgCategory; // NewMessage only returns for messages from these 3 categories
case UpdateKind.OtherUpdate when update.Update.MyChatMember is
{
NewChatMember.Status: ChatMemberStatus.Left or ChatMemberStatus.Kicked
}:
throw new LeftTheChatException(); // abort the calling method
case UpdateKind.None:
case UpdateKind.EditedMessage:
case UpdateKind.CallbackQuery:
break;
default:
throw new ArgumentOutOfRangeException(null);
}
}
/// <summary>
/// Returns the next text message ignoring other kind of updates
/// </summary>
/// <param name="update"></param>
/// <param name="ct"></param>
/// <returns></returns>
public async Task<string?> NewTextMessage(UpdateInfo update, CancellationToken ct = default)
{
while (await NewMessage(update, ct) != MsgCategory.Text)
await Delay(1, CancellationToken.None);
return update.Message.Text;
}
/// <summary>
/// Replyes to the callback query
/// </summary>
/// <param name="update"></param>
/// <param name="text"></param>
/// <exception cref="InvalidOperationException"></exception>
public void ReplyCallback(UpdateInfo update, string text = null!)
{
if (update.Update.Type != UpdateType.CallbackQuery)
throw new InvalidOperationException("This method can be called only for CallbackQuery updates");
_ = Bot.AnswerCallbackQueryAsync(update.Update.CallbackQuery!.Id, text);
}
}
/// <summary>
/// Thrown when user lefts the chat
/// </summary>
public class LeftTheChatException : Exception
{
/// <summary></summary>
public LeftTheChatException() : base("The chat was left") { }
}