Skip to content

Commit 3ca7345

Browse files
committed
Refactor code and update logging configuration
- Improved operator precedence clarity in `PhoneController.cs` and `CafeController.cs` by adding parentheses. - Added logging configuration to `appsettings.json` and updated the bot token. - Refactored `InlineQueryHandler.cs` for better readability and maintainability, including simplifying conditions and removing redundant comments. - Provided a default value for `BotControllerMethodsContainer` in `TelegramBotHostedService.cs` to ensure backward compatibility.
1 parent f104421 commit 3ca7345

File tree

5 files changed

+22
-25
lines changed

5 files changed

+22
-25
lines changed

Sources/TelegramBot.AspNetCoreTest/Controllers/PhoneController.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public IActionResult AddDigit(int digit)
3232
_logger.LogWarning("Phone number exceeds 11 digits.");
3333
return Void();
3434
}
35-
value = value * 10 + digit;
35+
value = (value * 10) + digit;
3636
SetPhoneValue(value);
3737
_logger.LogInformation("Phone changed: {Value}", value);
3838
return CreateCounterResponse(value);

Sources/TelegramBot.ConsoleTest/Controllers/CafeController.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ private static MemoryStream DrawImage()
110110
{
111111
byte r = (byte)(x % size);
112112
byte g = (byte)(y % size);
113-
byte b = (byte)((x + y) / 2 % size);
113+
byte b = (byte)(((x + y) / 2) % size);
114114
image[x, y] = new Rgba32(r, g, b);
115115
}
116116
}
Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
{
2-
"TelegramBotToken": "YOUR_API_KEY",
3-
"CustomTelegramApiUrl": ""
4-
}
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
},
8+
"TelegramBotToken": "123"
9+
}

Sources/TelegramBot/Handlers/InlineQueryHandler.cs

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -59,15 +59,10 @@ private bool IsValidMethod(MethodInfo method, string command)
5959

6060
foreach (var attribute in attributes)
6161
{
62-
if (!(attribute is InlineCommandAttribute botAttribute))
62+
if (!(attribute is InlineCommandAttribute botAttribute) // Skip if the attribute is not of type InlineCommandAttribute
63+
|| (method.GetParameters().Length == 0 && botAttribute.Command != command)) // Skip methods without parameters if the command does not match
6364
{
64-
continue; // Skip if the attribute is not of type InlineCommandAttribute
65-
}
66-
67-
// Если метод не имеет параметров, проверяем точное совпадение команды
68-
if (method.GetParameters().Length == 0 && botAttribute.Command != command)
69-
{
70-
continue; // Skip methods without parameters if the command does not match
65+
continue;
7166
}
7267

7368
string[] controllerCommandParts = botAttribute.Command.Split('/');
@@ -87,10 +82,8 @@ private bool IsValidMethod(MethodInfo method, string command)
8782
break;
8883
}
8984

90-
// Если это параметр в маршруте, добавляем его в аргументы
91-
if (controllerCommandParts[i].StartsWith("{") && controllerCommandParts[i].EndsWith("}"))
85+
if (controllerCommandParts[i].StartsWith('{') && controllerCommandParts[i].EndsWith('}'))
9286
{
93-
// Проверка типа аргумента
9487
var parameter = method.GetParameters().FirstOrDefault(p => p.Name == controllerCommandParts[i].Trim('{', '}'));
9588
if (parameter != null)
9689
{
@@ -116,29 +109,27 @@ private bool TryConvertToType(string value, Type targetType)
116109
{
117110
try
118111
{
119-
// Попробуем привести строку к требуемому типу
120112
if (targetType == typeof(int))
121113
{
122-
return int.TryParse(value, out _); // Проверяем, может ли строка быть приведена к int
114+
return int.TryParse(value, out _);
123115
}
124116
if (targetType == typeof(long))
125117
{
126-
return long.TryParse(value, out _); // Проверяем на long
118+
return long.TryParse(value, out _);
127119
}
128120
if (targetType == typeof(double))
129121
{
130-
return double.TryParse(value, out _); // Проверяем на double
122+
return double.TryParse(value, out _);
131123
}
132124
if (targetType == typeof(bool))
133125
{
134-
return bool.TryParse(value, out _); // Проверяем на bool
126+
return bool.TryParse(value, out _);
135127
}
136128
if (targetType == typeof(Guid))
137129
{
138-
return Guid.TryParse(value, out _); // Проверяем на Guid
130+
return Guid.TryParse(value, out _);
139131
}
140132

141-
// Если тип не поддерживается, пробуем использовать конструктор (например, для строк или других типов)
142133
Convert.ChangeType(value, targetType);
143134
return true;
144135
}

Sources/TelegramBot/Services/TelegramBotHostedService.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,16 @@ internal class TelegramBotHostedService : IHostedService
3030

3131
public TelegramBotHostedService(BotConfiguration botConfiguration, ITelegramBotClient telegramBotClient,
3232
ILogger<TelegramBotHostedService> logger, IServiceProvider serviceProvider,
33-
BotControllerMethodsContainer? botControllerMethodsContainer)
33+
BotControllerMethodsContainer? botControllerMethodsContainer = null)
3434
{
3535
_logger = logger;
3636
_client = telegramBotClient;
3737
_serviceProvider = serviceProvider;
3838
_botConfiguration = botConfiguration;
3939
_cancellationTokenSource = new CancellationTokenSource();
4040
_methods = botControllerMethodsContainer?.Methods ?? new List<MethodInfo>();
41-
_logger.LogInformation("Telegram bot hosted service initialized with {methodCount} methods.", _methods.Count);
41+
_logger.LogInformation("Telegram bot hosted service initialized with {methodCount} methods. " +
42+
"If you wanted to add controllers, make sure to call 'AddBotControllers' extension method during service registration.", _methods.Count);
4243
}
4344

4445
public async Task StartAsync(CancellationToken cancellationToken)

0 commit comments

Comments
 (0)