-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTelegramListener.cs
84 lines (71 loc) · 2.74 KB
/
TelegramListener.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
using System;
using System.Configuration;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace TeleTok
{
public class TelegramListener
{
public void RunListener()
{
var botClient = new TelegramBotClient(TeleTok.token);
using var cts = new CancellationTokenSource();
// StartReceiving does not block the caller thread. Receiving is done on the ThreadPool.
ReceiverOptions receiverOptions = new ()
{
AllowedUpdates = Array.Empty<UpdateType>() // receive all update types
};
botClient.StartReceiving(
updateHandler: HandleUpdateAsync,
errorHandler: HandlePollingErrorAsync,
receiverOptions: receiverOptions,
cancellationToken: cts.Token
);
while (true)
{
// Do nothing until the stuff happens
};
cts.Cancel();
}
async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
// Only process Message updates: https://core.telegram.org/bots/api#message
if (update.Message is not { } message)
return;
// Only process text messages
if (message.Text is not { } messageText)
return;
var chatId = message.Chat.Id;
string proxyUrl;
// Checks if the text contains a valid URL
bool isUri = Uri.IsWellFormedUriString(messageText, UriKind.RelativeOrAbsolute);
// Passes the url along to the video downloader if it is valid AND a tiktok link
if (isUri)
{
if(messageText.Contains("tiktok.com"))
{
proxyUrl = VidDownload.TikTokURL(messageText);
Message ttVideo = await botClient.SendVideoAsync(
chatId: chatId,
video: proxyUrl,
cancellationToken: cancellationToken
);
}
}
}
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()
};
TeleTok.LogMessage(ErrorMessage);
return Task.CompletedTask;
}
}
}