implement reading bot token from file or console

This commit is contained in:
Slavasil 2025-04-20 00:33:43 +03:00
parent a79a8a81c7
commit 454ebd1581
3 changed files with 52 additions and 5 deletions

19
SimpleTGBot/Config.cs Normal file
View File

@ -0,0 +1,19 @@
using System.IO;
namespace SimpleTGBot;
internal class Config
{
public const string DEFAULT_BOT_TOKEN_FILENAME = "telegram_token.txt";
public static string? TryReadBotTokenFile()
{
try
{
return File.ReadAllText(DEFAULT_BOT_TOKEN_FILENAME).Trim();
} catch (FileNotFoundException)
{
return null;
}
}
}

View File

@ -10,7 +10,21 @@ public static class Program
// Православная кодировка
Console.OutputEncoding = Encoding.UTF8;
TelegramBot telegramBot = new TelegramBot();
string? botToken = Config.TryReadBotTokenFile();
if (botToken == null)
{
Console.WriteLine($"Файл {Config.DEFAULT_BOT_TOKEN_FILENAME} не найден. Вы можете указать токен вручную:");
Console.Write("$ ");
botToken = Console.ReadLine();
}
if (botToken == null)
{
return 1;
}
TelegramBot telegramBot = new TelegramBot(botToken);
await telegramBot.Run();
}
}

View File

@ -8,14 +8,19 @@ namespace SimpleTGBot;
public class TelegramBot
{
private const string BotToken = "ВАШ_ТОКЕН_ИДЕНТИФИКАЦИИ_БОТА";
private string token;
public TelegramBot(string token)
{
this.token = token;
}
/// <summary>
/// Инициализирует и обеспечивает работу бота до нажатия клавиши Esc
/// </summary>
public async Task Run()
{
var botClient = new TelegramBotClient(BotToken);
var botClient = new TelegramBotClient(token);
using CancellationTokenSource cts = new CancellationTokenSource();
ReceiverOptions receiverOptions = new ReceiverOptions()
@ -29,11 +34,20 @@ public class TelegramBot
cancellationToken: cts.Token
);
try
{
var me = await botClient.GetMeAsync(cancellationToken: cts.Token);
Console.WriteLine($"Бот @{me.Username} запущен.\nДля остановки нажмите клавишу Esc...");
}
catch (ApiRequestException)
{
Console.WriteLine("Указан неправильный токен");
goto botQuit;
}
while (Console.ReadKey().Key != ConsoleKey.Escape){}
botQuit:
cts.Cancel();
}