using System; using System.Collections.Generic; using Telegram.Bot; using Telegram.Bot.Args; using Telegram.Bot.Exceptions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; namespace BlubbFish.Utils.IoT.Connector.User { public class Telegram : AUserBackend { private TelegramBotClient bot; private ChatId chat; public override event TelegramMessage MessageIncomming; public override event TelegramMessage MessageSending; public Telegram(Dictionary settings) : base(settings) { this.bot = new TelegramBotClient(settings["telegram-key"]); this.bot.OnMessage += this.Bot_OnMessage; this.Connect(); } private void Bot_OnMessage(Object sender, MessageEventArgs e) { this.MessageIncomming?.Invoke(this, new UserMessageEventArgs(e.Message.Text, e.Message.Chat.Id, e.Message.Date)); } private void Connect() { this.bot.StartReceiving(); this.chat = new ChatId(this.settings["chatid"]); } public async override void Send(String message) { try { Message x = await this.bot.SendTextMessageAsync(this.chat, message); this.MessageSending?.Invoke(this, new UserMessageEventArgs(x.Text, x.Chat.Id, x.Date)); } catch(ApiRequestException e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e.Message+" "+e.ErrorCode+" "+e.Parameters); Console.ForegroundColor = ConsoleColor.White; } } public override void Dispose() { this.bot.StopReceiving(); this.bot = null; } public async override void Send(String message, String[] buttons) { try { KeyboardButton[] button = new KeyboardButton[buttons.Length]; for(Int32 i = 0; i < button.Length; i++) { button[i] = new KeyboardButton(buttons[i]); } Message x = await this.bot.SendTextMessageAsync(this.chat, message, ParseMode.Default, false, false, 0, new ReplyKeyboardMarkup(button,true,true)); this.MessageSending?.Invoke(this, new UserMessageEventArgs(x.Text, x.Chat.Id, x.Date)); } catch (ApiRequestException e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e.Message + " " + e.ErrorCode + " " + e.Parameters); Console.ForegroundColor = ConsoleColor.White; } } } }