Skip to content

Instantly share code, notes, and snippets.

@isammour
Created February 28, 2022 21:42
Show Gist options
  • Select an option

  • Save isammour/537c46e8cdc263017e94404df99f1944 to your computer and use it in GitHub Desktop.

Select an option

Save isammour/537c46e8cdc263017e94404df99f1944 to your computer and use it in GitHub Desktop.
C# telegram messaging bot
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace Telegram_Messaging_Bot_2022
{
struct BotUpdate
{
public string text;
public long id;
public string? username;
}
class Program
{
static TelegramBotClient Bot = new TelegramBotClient("5247803834:AAErgMm37PSfCQByxJoGacgn8yQqLSFJ2sw");
static string fileName = "updates.json";
static List<BotUpdate> botUpdates = new List<BotUpdate>();
static void Main(string[] args)
{
//Read all saved updates
try
{
var botUpdatesString = System.IO.File.ReadAllText(fileName);
botUpdates = JsonConvert.DeserializeObject<List<BotUpdate>>(botUpdatesString) ?? botUpdates;
}
catch(Exception ex)
{
Console.WriteLine($"Error reading or deserializing {ex}");
}
var receiverOptions = new ReceiverOptions
{
AllowedUpdates = new UpdateType[]
{
UpdateType.Message,
UpdateType.EditedMessage,
}
};
Bot.StartReceiving(UpdateHandler, ErrorHandler, receiverOptions);
Console.ReadLine();
}
private static Task ErrorHandler(ITelegramBotClient arg1, Exception arg2, CancellationToken arg3)
{
throw new NotImplementedException();
}
private static async Task UpdateHandler(ITelegramBotClient bot, Update update, CancellationToken arg3)
{
if(update.Type == UpdateType.Message)
{
if(update.Message.Type == MessageType.Text)
{
//write an update
var _botUpdate = new BotUpdate
{
text = update.Message.Text,
id = update.Message.Chat.Id,
username = update.Message.Chat.Username
};
botUpdates.Add(_botUpdate);
var botUpdatesString = JsonConvert.SerializeObject(botUpdates);
System.IO.File.WriteAllText(fileName, botUpdatesString);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment