-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
128 lines (93 loc) · 4.22 KB
/
Program.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
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
var botClient = new TelegramBotClient("BOT_TOKEN");
using CancellationTokenSource cts = new();
// StartReceiving does not block the caller thread. Receiving is done on the ThreadPool.
ReceiverOptions receiverOptions = new()
{
AllowedUpdates = Array.Empty<UpdateType>() // receive all update types except ChatMember related updates
};
botClient.StartReceiving(
updateHandler: HandleUpdateAsync,
pollingErrorHandler: HandlePollingErrorAsync,
receiverOptions: receiverOptions,
cancellationToken: cts.Token
);
// Fetch information about the bot's identity using GetMeAsync() and display a message to start listening for messages from the bot's username.
var me = await botClient.GetMeAsync();
Console.WriteLine($"Start listening for @{me.Username}");
Console.ReadLine();
// Send cancellation request to stop bot
cts.Cancel();
async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
// Only process Message updates
if (update.Message is not { } message)
return;
// Only process text messages
if (message.Text is not { } messageText)
return;
long chatId = update.Message.Chat.Id; // Get the chat ID from the incoming message (dynamic chatId)
//Display user entered command details in console
if (messageText.StartsWith("/"))
{
// Get the current date and time (to show in console)
DateTime currentTime = DateTime.Now;
// Display the user's chat ID, date, and time in console
Console.WriteLine($"User with Chat ID {message.Chat.Id}, Username: @{message.Chat.Username ?? "N/A"}, sent the command '{messageText}' at {currentTime.ToLocalTime()}.");
}
if (messageText.Equals("/start", StringComparison.InvariantCultureIgnoreCase))
{
var inlineKeyboard = new InlineKeyboardMarkup(new List<List<InlineKeyboardButton>>
{
// First row
new List<InlineKeyboardButton>
{
InlineKeyboardButton.WithUrl("My Owner", "https://t.me/ideepakpg"),
InlineKeyboardButton.WithUrl("Repo", "https://github.com/ideepakpg/password-generator-bot")
}
});
Message newMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "Welcome to the Password Generator Bot",
parseMode: ParseMode.MarkdownV2,
disableNotification: true,
replyToMessageId: update.Message.MessageId,
replyMarkup: inlineKeyboard,
cancellationToken: cancellationToken);
}
if (messageText.Equals("/generate", StringComparison.InvariantCultureIgnoreCase))
{
string randomPassword = GenerateRandomPassword(25);
string message1 = "Generated Password: `" + randomPassword + "`";
await botClient.SendTextMessageAsync(chatId, message1, parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown, replyToMessageId: update.Message.MessageId, replyMarkup: null, cancellationToken: cancellationToken);
}
static string GenerateRandomPassword(int length)
{
const string validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890@#$&&-()=%\"*':/!?+,.£€¥~¿[]{}<>^¡`;÷|¦¬×";
var random = new Random();
var passwordChars = new char[length];
for (int i = 0; i < length; i++)
{
passwordChars[i] = validChars[random.Next(0, validChars.Length)];
}
return new string(passwordChars);
}
}
//Handles errors that occur during the polling process of the Telegram bot.
//Logs error messages to the console, providing detailed information about the exception.
Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
var ErrorMessage = exception switch
{
ApiRequestException apiRequestException
=> $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
_ => exception.ToString()
};
Console.WriteLine(ErrorMessage);
return Task.CompletedTask;
}