66 lines
2.1 KiB
C#
66 lines
2.1 KiB
C#
using System;
|
|
using Telegram.Bot;
|
|
using Telegram.Bot.Args;
|
|
using Telegram.Bot.Exceptions;
|
|
using Telegram.Bot.Types;
|
|
|
|
namespace BlubbFish.Utils.IoT.Connector {
|
|
public class Telegram {
|
|
private static Telegram instance;
|
|
private TelegramBotClient bot;
|
|
private ChatId chat;
|
|
|
|
public delegate void TelegramMessage(Object sender, TelegramEventArgs e);
|
|
|
|
public event TelegramMessage MessageIncomming;
|
|
public event TelegramMessage MessageSending;
|
|
|
|
private Telegram() {
|
|
this.bot = new TelegramBotClient(InIReader.GetInstance("settings.ini").GetValue("general", "telegram-key"));
|
|
this.bot.OnMessage += this.Bot_OnMessage;
|
|
this.Connect();
|
|
}
|
|
|
|
private void Bot_OnMessage(Object sender, MessageEventArgs e) {
|
|
this.MessageIncomming?.Invoke(this, new TelegramEventArgs(e.Message.Text, e.Message.Chat.Id, e.Message.Date));
|
|
}
|
|
|
|
public static Telegram Instance {
|
|
get {
|
|
if(instance == null) {
|
|
instance = new Telegram();
|
|
}
|
|
return instance;
|
|
}
|
|
}
|
|
|
|
private void Connect() {
|
|
this.bot.StartReceiving();
|
|
this.chat = new ChatId(InIReader.GetInstance("settings.ini").GetValue("general", "chatid"));
|
|
}
|
|
|
|
public async void Send(String text) {
|
|
try {
|
|
Message x = await this.bot.SendTextMessageAsync(this.chat, text);
|
|
this.MessageSending?.Invoke(this, new TelegramEventArgs(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 class TelegramEventArgs : EventArgs {
|
|
public TelegramEventArgs() : base() { }
|
|
public TelegramEventArgs(String message, Int64 UserId, DateTime date) {
|
|
this.UserId = UserId;
|
|
this.Message = message;
|
|
this.Date = date;
|
|
}
|
|
|
|
public Int64 UserId { get; private set; }
|
|
public String Message { get; private set; }
|
|
public DateTime Date { get; private set; }
|
|
}
|
|
}
|