Created
September 7, 2020 14:28
-
-
Save karb0f0s/7d16f99dbfcee5d495d91f2055c42f85 to your computer and use it in GitHub Desktop.
System.Threading.Channels + Telegram.Bot polling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Threading.Channels; | |
using System.Threading.Tasks; | |
using Telegram.Bot; | |
using Telegram.Bot.Types; | |
namespace ChannelPolling | |
{ | |
internal static class Program | |
{ | |
static Channel<Update> updateChannel; | |
static ITelegramBotClient botClient; | |
static async Task Main(string[] args) | |
{ | |
updateChannel = Channel.CreateUnbounded<Update>( | |
new UnboundedChannelOptions() | |
{ | |
SingleWriter = true, | |
SingleReader = true | |
}); | |
botClient = new TelegramBotClient("123456:ABCDEFGHI"); | |
using var cts = new CancellationTokenSource(); | |
var producer = Task.Run(async () => await Producer(cts)); | |
var consumer = Task.Run(async () => await Consumer()); | |
Console.WriteLine("Start receiving updates. Press Enter to stop..."); | |
Console.ReadLine(); | |
cts.Cancel(); | |
await Task.WhenAll(producer, consumer); | |
} | |
private static async Task Consumer() | |
{ | |
Console.WriteLine("Starting consumer..."); | |
await foreach (var update in updateChannel.Reader.ReadAllAsync()) | |
{ | |
Console.WriteLine($"{update.Id.ToString()} {update.Type} {update.Message?.Text}"); | |
} | |
Console.WriteLine("Stopping consumer..."); | |
} | |
private static async Task Producer(CancellationTokenSource cts) | |
{ | |
Console.WriteLine("Starting producer..."); | |
var offset = -1; | |
while (!cts.IsCancellationRequested) | |
{ | |
var updates = await botClient.GetUpdatesAsync(offset: offset); | |
offset = updates.Length > 0 ? updates[^1].Id + 1 : -1; | |
foreach (var update in updates) | |
{ | |
await updateChannel.Writer.WriteAsync(update); | |
} | |
} | |
Console.WriteLine("Stopping producer..."); | |
updateChannel.Writer.Complete(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment