-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
251 lines (217 loc) · 8.99 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
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InlineQueryResults;
using Telegram.Bot.Types.InputFiles;
using Telegram.Bot.Types.ReplyMarkups;
namespace Telegram.Bot.Examples.Echo
{
public static class Program
{
private static TelegramBotClient Bot;
public static async Task Main()
{
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var botSettings = configuration.GetSection("BotSettings").Get<BotSettings>();
var cts = new CancellationTokenSource();
try {
Bot = new TelegramBotClient(botSettings.BotToken);
var me = await Bot.GetMeAsync();
Console.Title = me.Username;
Console.WriteLine("GetMe:" + me.Username);
Console.WriteLine($"Start listening for @{me.Username}");
await Bot.ReceiveAsync(new DefaultUpdateHandler(HandleUpdateAsync, HandleErrorAsync), cts.Token);
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
// Send cancellation request to stop bot
cts.Cancel();
}
}
public static async Task HandleUpdateAsync(Update update, CancellationToken cancellationToken)
{
var handler = update.Type switch
{
UpdateType.Message => BotOnMessageReceived(update.Message),
UpdateType.EditedMessage => BotOnMessageReceived(update.Message),
UpdateType.CallbackQuery => BotOnCallbackQueryReceived(update.CallbackQuery),
UpdateType.InlineQuery => BotOnInlineQueryReceived(update.InlineQuery),
UpdateType.ChosenInlineResult => BotOnChosenInlineResultReceived(update.ChosenInlineResult),
// UpdateType.Unknown:
// UpdateType.ChannelPost:
// UpdateType.EditedChannelPost:
// UpdateType.ShippingQuery:
// UpdateType.PreCheckoutQuery:
// UpdateType.Poll:
_ => UnknownUpdateHandlerAsync(update)
};
try
{
await handler;
}
catch (Exception exception)
{
await HandleErrorAsync(exception, cancellationToken);
}
}
private static async Task BotOnMessageReceived(Message message)
{
Console.WriteLine($"Receive message type: {message.Type}");
if (message.Type != MessageType.Text)
return;
var action = (message.Text.Split(' ').First()) switch
{
"/inline" => SendInlineKeyboard(message),
"/keyboard" => SendReplyKeyboard(message),
"/photo" => SendFile(message),
"/request" => RequestContactAndLocation(message),
_ => Usage(message)
};
await action;
// Send inline keyboard
// You can process responses in BotOnCallbackQueryReceived handler
static async Task SendInlineKeyboard(Message message)
{
await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);
// Simulate longer running task
await Task.Delay(500);
var inlineKeyboard = new InlineKeyboardMarkup(new[]
{
// first row
new []
{
InlineKeyboardButton.WithCallbackData("1.1", "11"),
InlineKeyboardButton.WithCallbackData("1.2", "12"),
},
// second row
new []
{
InlineKeyboardButton.WithCallbackData("2.1", "21"),
InlineKeyboardButton.WithCallbackData("2.2", "22"),
}
});
await Bot.SendTextMessageAsync(
chatId: message.Chat.Id,
text: "Choose",
replyMarkup: inlineKeyboard
);
}
static async Task SendReplyKeyboard(Message message)
{
var replyKeyboardMarkup = new ReplyKeyboardMarkup(
new KeyboardButton[][]
{
new KeyboardButton[] { "1.1", "1.2" },
new KeyboardButton[] { "2.1", "2.2" },
},
resizeKeyboard: true
);
await Bot.SendTextMessageAsync(
chatId: message.Chat.Id,
text: "Choose",
replyMarkup: replyKeyboardMarkup
);
}
static async Task SendFile(Message message)
{
await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto);
const string filePath = @"Files/tux.png";
using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
var fileName = filePath.Split(Path.DirectorySeparatorChar).Last();
await Bot.SendPhotoAsync(
chatId: message.Chat.Id,
photo: new InputOnlineFile(fileStream, fileName),
caption: "Nice Picture"
);
}
static async Task RequestContactAndLocation(Message message)
{
var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[]
{
KeyboardButton.WithRequestLocation("Location"),
KeyboardButton.WithRequestContact("Contact"),
});
await Bot.SendTextMessageAsync(
chatId: message.Chat.Id,
text: "Who or Where are you?",
replyMarkup: RequestReplyKeyboard
);
}
static async Task Usage(Message message)
{
const string usage = "Usage:\n" +
"/inline - send inline keyboard\n" +
"/keyboard - send custom keyboard\n" +
"/photo - send a photo\n" +
"/request - request location or contact";
await Bot.SendTextMessageAsync(
chatId: message.Chat.Id,
text: usage,
replyMarkup: new ReplyKeyboardRemove()
);
}
}
// Process Inline Keyboard callback data
private static async Task BotOnCallbackQueryReceived(CallbackQuery callbackQuery)
{
await Bot.AnswerCallbackQueryAsync(
callbackQuery.Id,
$"Received {callbackQuery.Data}"
);
await Bot.SendTextMessageAsync(
callbackQuery.Message.Chat.Id,
$"Received {callbackQuery.Data}"
);
}
#region Inline Mode
private static async Task BotOnInlineQueryReceived(InlineQuery inlineQuery)
{
Console.WriteLine($"Received inline query from: {inlineQuery.From.Id}");
InlineQueryResultBase[] results = {
// displayed result
new InlineQueryResultArticle(
id: "3",
title: "TgBots",
inputMessageContent: new InputTextMessageContent(
"hello"
)
)
};
await Bot.AnswerInlineQueryAsync(
inlineQuery.Id,
results,
isPersonal: true,
cacheTime: 0
);
}
private static async Task BotOnChosenInlineResultReceived(ChosenInlineResult chosenInlineResult)
{
Console.WriteLine($"Received inline result: {chosenInlineResult.ResultId}");
}
#endregion
private static async Task UnknownUpdateHandlerAsync(Update update)
{
Console.WriteLine($"Unknown update type: {update.Type}");
}
public static async Task HandleErrorAsync(Exception exception, CancellationToken cancellationToken)
{
var ErrorMessage = exception switch
{
ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
_ => exception.ToString()
};
Console.WriteLine(ErrorMessage);
}
}
}