Skip to content

Commit

Permalink
fix warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
wiz0u committed Jul 5, 2024
1 parent ee4bcb2 commit 7da94ad
Show file tree
Hide file tree
Showing 12 changed files with 59 additions and 93 deletions.
2 changes: 1 addition & 1 deletion Console.Advanced/Abstract/IReceiverService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Telegram.Bot.Abstract;
namespace Console.Advanced.Abstract;

/// <summary>
/// A marker interface for Update Receiver service
Expand Down
2 changes: 1 addition & 1 deletion Console.Advanced/Abstract/PollingServiceBase.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Telegram.Bot.Abstract;
namespace Console.Advanced.Abstract;

// A background service consuming a scoped service.
// See more: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services#consuming-a-scoped-service-in-a-background-task
Expand Down
5 changes: 3 additions & 2 deletions Console.Advanced/Abstract/ReceiverServiceBase.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
using Telegram.Bot;
using Telegram.Bot.Polling;
using Telegram.Bot.Types.Enums;

namespace Telegram.Bot.Abstract;
namespace Console.Advanced.Abstract;

/// <summary>
/// An abstract class to compose Receiver Service and Update Handler classes
Expand Down Expand Up @@ -34,7 +35,7 @@ public async Task ReceiveAsync(CancellationToken stoppingToken)
// ToDo: we can inject ReceiverOptions through IOptions container
var receiverOptions = new ReceiverOptions()
{
AllowedUpdates = Array.Empty<UpdateType>(),
AllowedUpdates = [],
DropPendingUpdates = true,
};

Expand Down
6 changes: 6 additions & 0 deletions Console.Advanced/BotConfiguration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Console.Advanced;

public class BotConfiguration
{
public string BotToken { get; init; } = default!;
}
16 changes: 0 additions & 16 deletions Console.Advanced/Extensions.cs

This file was deleted.

23 changes: 7 additions & 16 deletions Console.Advanced/Program.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
using Microsoft.Extensions.Options;
using Telegram.Bot;
using Telegram.Bot.Services;
using Console.Advanced;
using Console.Advanced.Services;

IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
// Register Bot configuration
services.Configure<BotConfiguration>(
context.Configuration.GetSection(BotConfiguration.Configuration));
services.Configure<BotConfiguration>(context.Configuration.GetSection("BotConfiguration"));
// Register named HttpClient to benefits from IHttpClientFactory
// and consume it with ITelegramBotClient typed client.
Expand All @@ -16,8 +17,9 @@
services.AddHttpClient("telegram_bot_client").RemoveAllLoggers()
.AddTypedClient<ITelegramBotClient>((httpClient, sp) =>
{
BotConfiguration? botConfig = sp.GetConfiguration<BotConfiguration>();
TelegramBotClientOptions options = new(botConfig.BotToken);
BotConfiguration? botConfiguration = sp.GetService<IOptions<BotConfiguration>>()?.Value;
ArgumentNullException.ThrowIfNull(botConfiguration);
TelegramBotClientOptions options = new(botConfiguration.BotToken);
return new TelegramBotClient(options, httpClient);
});
Expand All @@ -28,14 +30,3 @@
.Build();

await host.RunAsync();

#pragma warning disable CA1050 // Declare types in namespaces
#pragma warning disable RCS1110 // Declare type inside namespace.
public class BotConfiguration
#pragma warning restore RCS1110 // Declare type inside namespace.
#pragma warning restore CA1050 // Declare types in namespaces
{
public static readonly string Configuration = "BotConfiguration";

public string BotToken { get; set; } = "";
}
13 changes: 4 additions & 9 deletions Console.Advanced/Services/PollingService.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
using Telegram.Bot.Abstract;
using Console.Advanced.Abstract;

namespace Telegram.Bot.Services;
namespace Console.Advanced.Services;

// Compose Polling and ReceiverService implementations
public class PollingService : PollingServiceBase<ReceiverService>
{
public PollingService(IServiceProvider serviceProvider, ILogger<PollingService> logger)
: base(serviceProvider, logger)
{
}
}
public class PollingService(IServiceProvider serviceProvider, ILogger<PollingService> logger)
: PollingServiceBase<ReceiverService>(serviceProvider, logger);
17 changes: 5 additions & 12 deletions Console.Advanced/Services/ReceiverService.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
using Telegram.Bot.Abstract;
using Console.Advanced.Abstract;
using Telegram.Bot;

namespace Telegram.Bot.Services;
namespace Console.Advanced.Services;

// Compose Receiver and UpdateHandler implementation
public class ReceiverService : ReceiverServiceBase<UpdateHandler>
{
public ReceiverService(
ITelegramBotClient botClient,
UpdateHandler updateHandler,
ILogger<ReceiverServiceBase<UpdateHandler>> logger)
: base(botClient, updateHandler, logger)
{
}
}
public class ReceiverService(ITelegramBotClient botClient, UpdateHandler updateHandler, ILogger<ReceiverServiceBase<UpdateHandler>> logger)
: ReceiverServiceBase<UpdateHandler>(botClient, updateHandler, logger);
61 changes: 27 additions & 34 deletions Console.Advanced/Services/UpdateHandler.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,20 @@
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InlineQueryResults;
using Telegram.Bot.Types.ReplyMarkups;

namespace Telegram.Bot.Services;
namespace Console.Advanced.Services;

public class UpdateHandler : IUpdateHandler
public class UpdateHandler(ITelegramBotClient bot, ILogger<UpdateHandler> logger) : IUpdateHandler
{
private readonly ITelegramBotClient _bot;
private readonly ILogger<UpdateHandler> _logger;
private static readonly InputPollOption[] PollOptions = ["Hello", "World!"];

public UpdateHandler(ITelegramBotClient bot, ILogger<UpdateHandler> logger)
public async Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, HandleErrorSource source, CancellationToken cancellationToken)
{
_bot = bot;
_logger = logger;
}

public async Task HandleErrorAsync(ITelegramBotClient bot, Exception exception, HandleErrorSource source, CancellationToken cancellationToken)
{
_logger.LogInformation("HandleError: {exception}", exception);
logger.LogInformation("HandleError: {exception}", exception);

Check warning on line 17 in Console.Advanced/Services/UpdateHandler.cs

View workflow job for this annotation

GitHub Actions / build

For improved performance, use the LoggerMessage delegates instead of calling 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])' (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1848)

Check warning on line 17 in Console.Advanced/Services/UpdateHandler.cs

View workflow job for this annotation

GitHub Actions / build

Use PascalCase for named placeholders in the logging message template (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1727)
// Cooldown in case of network connection error
if (exception is RequestException)
await Task.Delay(TimeSpan.FromSeconds(2));

Check warning on line 20 in Console.Advanced/Services/UpdateHandler.cs

View workflow job for this annotation

GitHub Actions / build

Forward the 'cancellationToken' parameter to the 'Delay' method or pass in 'CancellationToken.None' explicitly to indicate intentionally not propagating the token (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2016)
Expand Down Expand Up @@ -49,7 +42,7 @@ public async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update,

private async Task OnMessage(Message msg)
{
_logger.LogInformation("Receive message type: {MessageType}", msg.Type);
logger.LogInformation("Receive message type: {MessageType}", msg.Type);

Check warning on line 45 in Console.Advanced/Services/UpdateHandler.cs

View workflow job for this annotation

GitHub Actions / build

For improved performance, use the LoggerMessage delegates instead of calling 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])' (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1848)
if (msg.Text is not { } messageText)
return;

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

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

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

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

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

async Task<Message> RemoveKeyboard(Message msg)
{
return await _bot.SendTextMessageAsync(msg.Chat, "Removing keyboard", replyMarkup: new ReplyKeyboardRemove());
return await bot.SendTextMessageAsync(msg.Chat, "Removing keyboard", replyMarkup: new ReplyKeyboardRemove());
}

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

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

async Task<Message> SendPoll(Message msg)
{
return await _bot.SendPollAsync(msg.Chat, "Question", PollOptions, isAnonymous: false);
return await bot.SendPollAsync(msg.Chat, "Question", PollOptions, isAnonymous: false);
}

async Task<Message> SendAnonymousPoll(Message msg)
{
return await _bot.SendPollAsync(chatId: msg.Chat, "Question", PollOptions);
return await bot.SendPollAsync(chatId: msg.Chat, "Question", PollOptions);
}

static Task<Message> FailingHandler(Message msg)
Expand All @@ -158,48 +151,48 @@ static Task<Message> FailingHandler(Message msg)
// Process Inline Keyboard callback data
private async Task OnCallbackQuery(CallbackQuery callbackQuery)
{
_logger.LogInformation("Received inline keyboard callback from: {CallbackQueryId}", callbackQuery.Id);
await _bot.AnswerCallbackQueryAsync(callbackQuery.Id, $"Received {callbackQuery.Data}");
await _bot.SendTextMessageAsync(callbackQuery.Message!.Chat, $"Received {callbackQuery.Data}");
logger.LogInformation("Received inline keyboard callback from: {CallbackQueryId}", callbackQuery.Id);
await bot.AnswerCallbackQueryAsync(callbackQuery.Id, $"Received {callbackQuery.Data}");
await bot.SendTextMessageAsync(callbackQuery.Message!.Chat, $"Received {callbackQuery.Data}");
}

#region Inline Mode

private async Task OnInlineQuery(InlineQuery inlineQuery)
{
_logger.LogInformation("Received inline query from: {InlineQueryFromId}", inlineQuery.From.Id);
logger.LogInformation("Received inline query from: {InlineQueryFromId}", inlineQuery.From.Id);

InlineQueryResult[] results = [ // displayed result
new InlineQueryResultArticle("1", "Telegram.Bot", new InputTextMessageContent("hello")),
new InlineQueryResultArticle("2", "is the best", new InputTextMessageContent("world"))
];
await _bot.AnswerInlineQueryAsync(inlineQuery.Id, results, cacheTime: 0, isPersonal: true);
await bot.AnswerInlineQueryAsync(inlineQuery.Id, results, cacheTime: 0, isPersonal: true);
}

private async Task OnChosenInlineResult(ChosenInlineResult chosenInlineResult)
{
_logger.LogInformation("Received inline result: {ChosenInlineResultId}", chosenInlineResult.ResultId);
await _bot.SendTextMessageAsync(chosenInlineResult.From.Id, $"You chose result with Id: {chosenInlineResult.ResultId}");
logger.LogInformation("Received inline result: {ChosenInlineResultId}", chosenInlineResult.ResultId);
await bot.SendTextMessageAsync(chosenInlineResult.From.Id, $"You chose result with Id: {chosenInlineResult.ResultId}");
}

#endregion

private Task OnPoll(Poll poll)
{
_logger.LogInformation($"Received Pull info: {poll.Question}");
logger.LogInformation($"Received Pull info: {poll.Question}");
return Task.CompletedTask;
}

private async Task OnPollAnswer(PollAnswer pollAnswer)
{
var answer = pollAnswer.OptionIds.FirstOrDefault();
var selectedOption = PollOptions[answer];
await _bot.SendTextMessageAsync(pollAnswer.User.Id, $"You've chosen: {selectedOption.Text} in poll");
await bot.SendTextMessageAsync(pollAnswer.User.Id, $"You've chosen: {selectedOption.Text} in poll");

Check warning on line 190 in Console.Advanced/Services/UpdateHandler.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
}

private Task UnknownUpdateHandlerAsync(Update update)
{
_logger.LogInformation("Unknown update type: {UpdateType}", update.Type);
logger.LogInformation("Unknown update type: {UpdateType}", update.Type);
return Task.CompletedTask;
}
}
2 changes: 2 additions & 0 deletions Webhook.Controllers/BotConfiguration.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
namespace Webhook.Controllers;

public class BotConfiguration
{
public string BotToken { get; init; } = default!;
Expand Down
1 change: 1 addition & 0 deletions Webhook.Controllers/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Telegram.Bot;
using Webhook.Controllers;

var builder = WebApplication.CreateBuilder(args);

Expand Down
4 changes: 2 additions & 2 deletions Webhook.MinimalAPIs/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
using Telegram.Bot.Types;

var builder = WebApplication.CreateBuilder(args);
var token = builder.Configuration.GetValue("BotToken", "{set your bot token in appsettings.json")!;
var webhookUrl = builder.Configuration.GetValue("BotWebhookUrl", "{set your bot webhook url in appsettings.json")!;
var token = builder.Configuration["BotToken"]!; // set your bot token in appsettings.json
var webhookUrl = builder.Configuration["BotWebhookUrl"]!; // set your bot webhook public url in appsettings.json

builder.Services.ConfigureTelegramBot<Microsoft.AspNetCore.Http.Json.JsonOptions>(opt => opt.SerializerOptions);
builder.Services.AddHttpClient("tgwebhook").RemoveAllLoggers().AddTypedClient(httpClient => new TelegramBotClient(token, httpClient));
Expand Down

0 comments on commit 7da94ad

Please sign in to comment.