TeleTok/TelegramListener.cs

92 lines
3.0 KiB
C#
Raw Permalink Normal View History

2023-02-14 12:29:11 -05:00
using System;
using System.Configuration;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
2023-02-14 13:59:20 -05:00
using Telegram.Bot.Extensions.Polling;
2023-02-14 12:29:11 -05:00
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace TeleTok
{
public class TelegramListener
{
2023-02-14 13:59:20 -05:00
public void RunListener()
2023-02-14 12:29:11 -05:00
{
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,
2023-02-14 13:59:20 -05:00
errorHandler: HandlePollingErrorAsync,
2023-02-14 12:29:11 -05:00
receiverOptions: receiverOptions,
cancellationToken: cts.Token
);
while (true)
{
// Do nothing until the stuff happens
2023-02-14 13:59:20 -05:00
};
2023-02-14 12:29:11 -05:00
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)
{
2023-02-14 14:48:47 -05:00
try
2023-02-14 12:29:11 -05:00
{
2023-02-14 14:48:47 -05:00
if(messageText.Contains("tiktok.com"))
{
proxyUrl = VidDownload.TikTokURL(messageText);
2023-02-14 12:29:11 -05:00
2023-02-14 14:48:47 -05:00
Message ttVideo = await botClient.SendVideoAsync(
chatId: chatId,
video: proxyUrl,
cancellationToken: cancellationToken
);
}
}
catch
{
Console.WriteLine("Valid TikTok URI was sent, but was not a video!");
2023-02-14 12:29:11 -05:00
}
}
}
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;
}
}
}