-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
219 lines (194 loc) · 10.2 KB
/
Program.cs
File metadata and controls
219 lines (194 loc) · 10.2 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
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;
namespace BotTgInfo
{
class Program
{
private static ITelegramBotClient _botClient;
private static ReceiverOptions _receiverOptions;
private static string apiToken = "7283410447:AAEcWC3I9IeaP-UrJlo4m69VHr7tT27mCiA";
private static string changeToken = "2504c5fb-05a4-4e77-8241-e87582a15eac";
private static string ChanteType = "ChangeUrl";
private static string EuropeLink = "";
private static string UsaLink = "";
private static string CISLink = "";
static async Task Main()
{
_botClient = new TelegramBotClient(apiToken);
_receiverOptions = new ReceiverOptions
{
AllowedUpdates = new[]
{
UpdateType.Message,
},
// Параметр, отвечающий за обработку сообщений, пришедших за то время, когда ваш бот был оффлайн
// True - не обрабатывать, False (стоит по умолчанию) - обрабаывать
ThrowPendingUpdates = false,
};
using var cts = new CancellationTokenSource();
_botClient.StartReceiving(UpdateHandler, ErrorHandler, _receiverOptions, cts.Token); // Запускаем бота
var me = await _botClient.GetMeAsync();
Console.WriteLine($"{me.FirstName} запущен!");
await Task.Delay(-1);
}
private static async Task UpdateHandler(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
try
{
var a = 1;
switch (update.Type)
{
case UpdateType.Message:
{
var message = update.Message;
var chat = message.Chat;
if (message.Text == "/start")
{
var user = message.From;
Console.WriteLine($"{user.FirstName} ({user.Id}) написал сообщение: {message.Text}");
await botClient.SendTextMessageAsync(
chat.Id,
"Приветствую! Для дальнейшего использования бота подтвердите свой возраст. Сколько вам полных лет?."
);
}
else if (Int32.TryParse(message.Text, out int age))
{
if (age >= 21)
{
await botClient.SendTextMessageAsync(
chat.Id,
text: $"Спасибо, вы подтвердили свой возраст.");
SendCountryButtons(botClient, chat.Id);
}
else
{
await botClient.SendTextMessageAsync(chat.Id, text: "Извините. Этот бот недоступен для Вас.");
}
}
else if (message.Text == "Европа 🇪🇺")
{
await botClient.SendTextMessageAsync(
chatId: chat.Id,
text: $"Ваш доступ: {EuropeLink}",
parseMode: ParseMode.Markdown
);
}
else if (message.Text == "США 🇺🇸")
{
await botClient.SendTextMessageAsync(
chatId: chat.Id,
text: $"Ваш доступ: {UsaLink}",
parseMode: ParseMode.Markdown
);
}
else if (message.Text == "СНГ 🌍")
{
await botClient.SendTextMessageAsync(
chatId: chat.Id,
text: $"Ваш доступ: {CISLink}",
parseMode: ParseMode.Markdown
);
}
else if (message.Text.Contains(changeToken))
{
if (message.Text.ToLower().Contains(ChanteType.ToLower()))
{
// format ChangeUrl::token::country::newUrl
var changeUrlArr = message.Text.Split("::");
if (changeUrlArr.Length < 4)
{
await botClient.SendTextMessageAsync(
chat.Id,
text: "неверный формат смены url, formatL: ChangeUrl::token::country::newUrl. Counties: europe, usa, cis."
);
}
else
{
if (changeUrlArr[2].ToLower() == "europe")
{
EuropeLink = changeUrlArr[3];
}
else if (changeUrlArr[2].ToLower() == "usa")
{
UsaLink = changeUrlArr[3];
}
else if (changeUrlArr[2].ToLower() == "cis")
{
CISLink = changeUrlArr[3];
}
else
{
await botClient.SendTextMessageAsync(chat.Id, text: $"Не удалось распознать страну. Counties format: europe, usa, cis.");
return;
}
await botClient.SendTextMessageAsync(chat.Id, text: $"Url для страны {changeUrlArr[2].ToLower()} был успешно сменён на {changeUrlArr[3].ToLower()}.");
}
}
}
else
{
await botClient.SendTextMessageAsync(
chat.Id,
text: "Извините, я не понял вашего сообщения, возможно Вы ввели некорректно Ваш возраст."
);
}
return;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
RestartBotReceiving(botClient);
}
}
private static async Task SendCountryButtons(ITelegramBotClient botClient, long chatId)
{
var replyKeyboard = new ReplyKeyboardMarkup(
new List<KeyboardButton[]>()
{
new KeyboardButton[]
{
new KeyboardButton("Европа 🇪🇺"),
},
new KeyboardButton[]
{
new KeyboardButton("США 🇺🇸")
},
new KeyboardButton[]
{
new KeyboardButton("СНГ 🌍")
}
})
{
ResizeKeyboard = true,
};
await botClient.SendTextMessageAsync(
chatId: chatId,
text: "Выберите ваш регион проживания:",
replyMarkup: replyKeyboard
);
}
private static Task ErrorHandler(ITelegramBotClient botClient, Exception error, CancellationToken cancellationToken)
{
// Тут создадим переменную, в которую поместим код ошибки и её сообщение
var ErrorMessage = error switch
{
ApiRequestException apiRequestException
=> $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
_ => error.ToString()
};
Console.WriteLine(ErrorMessage);
return Task.CompletedTask;
}
private static void RestartBotReceiving(ITelegramBotClient botClient)
{
// Restart bot receiving here
botClient.StartReceiving(UpdateHandler, ErrorHandler, _receiverOptions, new CancellationTokenSource().Token);
}
}
}