Skip to content

Instantly share code, notes, and snippets.

@karb0f0s
Created September 7, 2020 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karb0f0s/7d16f99dbfcee5d495d91f2055c42f85 to your computer and use it in GitHub Desktop.
Save karb0f0s/7d16f99dbfcee5d495d91f2055c42f85 to your computer and use it in GitHub Desktop.
System.Threading.Channels + Telegram.Bot polling
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