Skip to content

Commit dabaf50

Browse files
committed
harmonize with Console.Advanced
1 parent 7da94ad commit dabaf50

File tree

4 files changed

+36
-40
lines changed

4 files changed

+36
-40
lines changed

.editorconfig

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ indent_size = 2
2828
# RCS1090: Call 'ConfigureAwait(false)'.
2929
dotnet_diagnostic.RCS1090.severity = none
3030

31+
# CA1848: Use the LoggerMessage delegates
32+
dotnet_diagnostic.CA1848.severity = silent
33+
3134
[*.md]
3235
trim_trailing_whitespace = false
3336
indent_size = 2

Webhook.Controllers/Controllers/BotController.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,25 +11,25 @@ namespace Webhook.Controllers.Controllers;
1111
public class BotController(IOptions<BotConfiguration> Config) : ControllerBase
1212
{
1313
[HttpGet("setWebhook")]
14-
public async Task<string> SetWebHook([FromServices] TelegramBotClient bot, CancellationToken ct)
14+
public async Task<string> SetWebHook([FromServices] ITelegramBotClient bot, CancellationToken ct)
1515
{
1616
var webhookUrl = Config.Value.BotWebhookUrl.AbsoluteUri;
1717
await bot.SetWebhookAsync(webhookUrl, allowedUpdates: [], secretToken: Config.Value.SecretToken, cancellationToken: ct);
1818
return $"Webhook set to {webhookUrl}";
1919
}
2020

2121
[HttpPost]
22-
public async Task<IActionResult> Post([FromBody] Update update, [FromServices] UpdateHandler handleUpdateService, CancellationToken ct)
22+
public async Task<IActionResult> Post([FromBody] Update update, [FromServices] ITelegramBotClient bot, [FromServices] UpdateHandler handleUpdateService, CancellationToken ct)
2323
{
2424
if (Request.Headers["X-Telegram-Bot-Api-Secret-Token"] != Config.Value.SecretToken)
2525
return Forbid();
2626
try
2727
{
28-
await handleUpdateService.HandleUpdateAsync(update, ct);
28+
await handleUpdateService.HandleUpdateAsync(bot, update, ct);
2929
}
3030
catch (Exception exception)
3131
{
32-
await handleUpdateService.HandleErrorAsync(exception, ct);
32+
await handleUpdateService.HandleErrorAsync(bot, exception, Telegram.Bot.Polling.HandleErrorSource.HandleUpdateError, ct);
3333
}
3434
return Ok();
3535
}

Webhook.Controllers/Program.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@
66
// Setup bot configuration
77
var botConfigSection = builder.Configuration.GetSection("BotConfiguration");
88
builder.Services.Configure<BotConfiguration>(botConfigSection);
9-
builder.Services.AddHttpClient("tgwebhook").RemoveAllLoggers().AddTypedClient(
9+
builder.Services.AddHttpClient("tgwebhook").RemoveAllLoggers().AddTypedClient<ITelegramBotClient>(
1010
httpClient => new TelegramBotClient(botConfigSection.Get<BotConfiguration>()!.BotToken, httpClient));
11-
builder.Services.AddScoped<Webhook.Controllers.Services.UpdateHandler>();
11+
builder.Services.AddSingleton<Webhook.Controllers.Services.UpdateHandler>();
1212
builder.Services.ConfigureTelegramBotMvc();
1313

1414
builder.Services.AddControllers();

Webhook.Controllers/Services/UpdateHandler.cs

Lines changed: 27 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,26 @@
11
using Telegram.Bot;
22
using Telegram.Bot.Exceptions;
3+
using Telegram.Bot.Polling;
34
using Telegram.Bot.Types;
45
using Telegram.Bot.Types.Enums;
56
using Telegram.Bot.Types.InlineQueryResults;
67
using Telegram.Bot.Types.ReplyMarkups;
78

89
namespace Webhook.Controllers.Services;
910

10-
public class UpdateHandler
11+
public class UpdateHandler(ITelegramBotClient bot, ILogger<UpdateHandler> logger) : IUpdateHandler
1112
{
12-
private readonly TelegramBotClient _bot;
13-
private readonly ILogger<UpdateHandler> _logger;
1413
private static readonly InputPollOption[] PollOptions = ["Hello", "World!"];
1514

16-
public UpdateHandler(TelegramBotClient bot, ILogger<UpdateHandler> logger)
15+
public async Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, HandleErrorSource source, CancellationToken cancellationToken)
1716
{
18-
_bot = bot;
19-
_logger = logger;
20-
}
21-
22-
public async Task HandleErrorAsync(Exception exception, CancellationToken cancellationToken)
23-
{
24-
_logger.LogInformation("HandleError: {exception}", exception);
17+
logger.LogInformation("HandleError: {exception}", exception);
2518
// Cooldown in case of network connection error
2619
if (exception is RequestException)
2720
await Task.Delay(TimeSpan.FromSeconds(2));
2821
}
2922

30-
public async Task HandleUpdateAsync(Update update, CancellationToken cancellationToken)
23+
public async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
3124
{
3225
cancellationToken.ThrowIfCancellationRequested();
3326
await (update switch
@@ -49,7 +42,7 @@ public async Task HandleUpdateAsync(Update update, CancellationToken cancellatio
4942

5043
private async Task OnMessage(Message msg)
5144
{
52-
_logger.LogInformation("Receive message type: {MessageType}", msg.Type);
45+
logger.LogInformation("Receive message type: {MessageType}", msg.Type);
5346
if (msg.Text is not { } messageText)
5447
return;
5548

@@ -66,7 +59,7 @@ private async Task OnMessage(Message msg)
6659
"/throw" => FailingHandler(msg),
6760
_ => Usage(msg)
6861
});
69-
_logger.LogInformation("The message was sent with id: {SentMessageId}", sentMessage.MessageId);
62+
logger.LogInformation("The message was sent with id: {SentMessageId}", sentMessage.MessageId);
7063
}
7164

7265
async Task<Message> Usage(Message msg)
@@ -83,15 +76,15 @@ async Task<Message> Usage(Message msg)
8376
/poll_anonymous - send an anonymous poll
8477
/throw - what happens if handler fails
8578
""";
86-
return await _bot.SendTextMessageAsync(msg.Chat, usage, parseMode: ParseMode.Html, replyMarkup: new ReplyKeyboardRemove());
79+
return await bot.SendTextMessageAsync(msg.Chat, usage, parseMode: ParseMode.Html, replyMarkup: new ReplyKeyboardRemove());
8780
}
8881

8982
async Task<Message> SendPhoto(Message msg)
9083
{
91-
await _bot.SendChatActionAsync(msg.Chat, ChatAction.UploadPhoto);
84+
await bot.SendChatActionAsync(msg.Chat, ChatAction.UploadPhoto);
9285
await Task.Delay(2000); // simulate a long task
9386
await using var fileStream = new FileStream("Files/bot.gif", FileMode.Open, FileAccess.Read);
94-
return await _bot.SendPhotoAsync(msg.Chat, fileStream, caption: "Read https://telegrambots.github.io/book/");
87+
return await bot.SendPhotoAsync(msg.Chat, fileStream, caption: "Read https://telegrambots.github.io/book/");
9588
}
9689

9790
// Send inline keyboard. You can process responses in OnCallbackQuery handler
@@ -105,7 +98,7 @@ async Task<Message> SendInlineKeyboard(Message msg)
10598
InlineKeyboardButton.WithUrl("WithUrl", "https://github.com/TelegramBots/Telegram.Bot")
10699
],
107100
];
108-
return await _bot.SendTextMessageAsync(msg.Chat, "Inline buttons:", replyMarkup: new InlineKeyboardMarkup(buttons));
101+
return await bot.SendTextMessageAsync(msg.Chat, "Inline buttons:", replyMarkup: new InlineKeyboardMarkup(buttons));
109102
}
110103

111104
async Task<Message> SendReplyKeyboard(Message msg)
@@ -115,12 +108,12 @@ async Task<Message> SendReplyKeyboard(Message msg)
115108
["1.1", "1.2", "1.3"],
116109
["2.1", "2.2"],
117110
];
118-
return await _bot.SendTextMessageAsync(msg.Chat, "Keyboard buttons:", replyMarkup: new ReplyKeyboardMarkup(keys) { ResizeKeyboard = true });
111+
return await bot.SendTextMessageAsync(msg.Chat, "Keyboard buttons:", replyMarkup: new ReplyKeyboardMarkup(keys) { ResizeKeyboard = true });
119112
}
120113

121114
async Task<Message> RemoveKeyboard(Message msg)
122115
{
123-
return await _bot.SendTextMessageAsync(msg.Chat, "Removing keyboard", replyMarkup: new ReplyKeyboardRemove());
116+
return await bot.SendTextMessageAsync(msg.Chat, "Removing keyboard", replyMarkup: new ReplyKeyboardRemove());
124117
}
125118

126119
async Task<Message> RequestContactAndLocation(Message msg)
@@ -130,24 +123,24 @@ async Task<Message> RequestContactAndLocation(Message msg)
130123
KeyboardButton.WithRequestLocation("Location"),
131124
KeyboardButton.WithRequestContact("Contact"),
132125
];
133-
return await _bot.SendTextMessageAsync(msg.Chat, "Who or Where are you?", replyMarkup: new ReplyKeyboardMarkup(buttons));
126+
return await bot.SendTextMessageAsync(msg.Chat, "Who or Where are you?", replyMarkup: new ReplyKeyboardMarkup(buttons));
134127
}
135128

136129
async Task<Message> StartInlineQuery(Message msg)
137130
{
138131
var button = InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("Inline Mode");
139-
return await _bot.SendTextMessageAsync(msg.Chat, "Press the button to start Inline Query\n\n" +
132+
return await bot.SendTextMessageAsync(msg.Chat, "Press the button to start Inline Query\n\n" +
140133
"(Make sure you enabled Inline Mode in @BotFather)", replyMarkup: new InlineKeyboardMarkup(button));
141134
}
142135

143136
async Task<Message> SendPoll(Message msg)
144137
{
145-
return await _bot.SendPollAsync(msg.Chat, "Question", PollOptions, isAnonymous: false);
138+
return await bot.SendPollAsync(msg.Chat, "Question", PollOptions, isAnonymous: false);
146139
}
147140

148141
async Task<Message> SendAnonymousPoll(Message msg)
149142
{
150-
return await _bot.SendPollAsync(chatId: msg.Chat, "Question", PollOptions);
143+
return await bot.SendPollAsync(chatId: msg.Chat, "Question", PollOptions);
151144
}
152145

153146
static Task<Message> FailingHandler(Message msg)
@@ -158,48 +151,48 @@ static Task<Message> FailingHandler(Message msg)
158151
// Process Inline Keyboard callback data
159152
private async Task OnCallbackQuery(CallbackQuery callbackQuery)
160153
{
161-
_logger.LogInformation("Received inline keyboard callback from: {CallbackQueryId}", callbackQuery.Id);
162-
await _bot.AnswerCallbackQueryAsync(callbackQuery.Id, $"Received {callbackQuery.Data}");
163-
await _bot.SendTextMessageAsync(callbackQuery.Message!.Chat, $"Received {callbackQuery.Data}");
154+
logger.LogInformation("Received inline keyboard callback from: {CallbackQueryId}", callbackQuery.Id);
155+
await bot.AnswerCallbackQueryAsync(callbackQuery.Id, $"Received {callbackQuery.Data}");
156+
await bot.SendTextMessageAsync(callbackQuery.Message!.Chat, $"Received {callbackQuery.Data}");
164157
}
165158

166159
#region Inline Mode
167160

168161
private async Task OnInlineQuery(InlineQuery inlineQuery)
169162
{
170-
_logger.LogInformation("Received inline query from: {InlineQueryFromId}", inlineQuery.From.Id);
163+
logger.LogInformation("Received inline query from: {InlineQueryFromId}", inlineQuery.From.Id);
171164

172165
InlineQueryResult[] results = [ // displayed result
173166
new InlineQueryResultArticle("1", "Telegram.Bot", new InputTextMessageContent("hello")),
174167
new InlineQueryResultArticle("2", "is the best", new InputTextMessageContent("world"))
175168
];
176-
await _bot.AnswerInlineQueryAsync(inlineQuery.Id, results, cacheTime: 0, isPersonal: true);
169+
await bot.AnswerInlineQueryAsync(inlineQuery.Id, results, cacheTime: 0, isPersonal: true);
177170
}
178171

179172
private async Task OnChosenInlineResult(ChosenInlineResult chosenInlineResult)
180173
{
181-
_logger.LogInformation("Received inline result: {ChosenInlineResultId}", chosenInlineResult.ResultId);
182-
await _bot.SendTextMessageAsync(chosenInlineResult.From.Id, $"You chose result with Id: {chosenInlineResult.ResultId}");
174+
logger.LogInformation("Received inline result: {ChosenInlineResultId}", chosenInlineResult.ResultId);
175+
await bot.SendTextMessageAsync(chosenInlineResult.From.Id, $"You chose result with Id: {chosenInlineResult.ResultId}");
183176
}
184177

185178
#endregion
186179

187180
private Task OnPoll(Poll poll)
188181
{
189-
_logger.LogInformation($"Received Pull info: {poll.Question}");
182+
logger.LogInformation($"Received Pull info: {poll.Question}");
190183
return Task.CompletedTask;
191184
}
192185

193186
private async Task OnPollAnswer(PollAnswer pollAnswer)
194187
{
195188
var answer = pollAnswer.OptionIds.FirstOrDefault();
196189
var selectedOption = PollOptions[answer];
197-
await _bot.SendTextMessageAsync(pollAnswer.User.Id, $"You've chosen: {selectedOption.Text} in poll");
190+
await bot.SendTextMessageAsync(pollAnswer.User.Id, $"You've chosen: {selectedOption.Text} in poll");
198191
}
199192

200193
private Task UnknownUpdateHandlerAsync(Update update)
201194
{
202-
_logger.LogInformation("Unknown update type: {UpdateType}", update.Type);
195+
logger.LogInformation("Unknown update type: {UpdateType}", update.Type);
203196
return Task.CompletedTask;
204197
}
205198
}

0 commit comments

Comments
 (0)