Utils/IoT/Connector/User/Telegram.cs

70 lines
2.7 KiB
C#
Raw Normal View History

2017-10-03 00:51:08 +02:00
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;
2017-10-03 00:51:08 +02:00
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<String, String> 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, ParseMode.Default, false, false, 0, new ReplyKeyboardRemove());
2017-10-03 00:51:08 +02:00
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;
}
2017-10-03 00:51:08 +02:00
}
public override void Dispose() {
this.bot.StopReceiving();
this.bot = null;
}
public async override void Send(String message, String[] buttons) {
try {
KeyboardButton[][] button = new KeyboardButton[(Int32)Math.Ceiling(((Double)buttons.Length)/2)][];
for(Int32 i = 0; i < buttons.Length; i++) {
Int32 j = (Int32)Math.Floor(((Double)i) / 2);
if (i % 2 == 0) {
button[j] = new KeyboardButton[(j == button.Length - 1) ? ((buttons.Length % 2 == 0) ? 2 : buttons.Length % 2) : 2];
}
button[j][i % 2] = 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;
}
}
2017-10-03 00:51:08 +02:00
}
}