Files
zaobot/NotificationReceiver.cs

88 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading;
using Telegram.Bot;
using ZaoBot.Config;
namespace ZaoBot
{
class NotificationReceiver
{
private JsonDocument config;
public NotificationReceiver(IConfig config)
{
this.config = config.Data;
}
public void Run()
{
while (true)
{
try
{
var port = config.RootElement.GetProperty("notify_listen_port").GetInt32();
var listener = new HttpListener();
listener.Prefixes.Add("http://+:" + port + "/");
listener.Start();
Console.WriteLine("NotificationReceiver listening on port " + port);
ProcessRequests(listener);
listener.Stop();
}
catch (Exception e)
{
Console.WriteLine("NotificationReceiver exception: " + e.Message + "\n" + e.StackTrace);
Thread.Sleep(1000);
}
}
}
private void ProcessRequests(HttpListener listener)
{
while (true)
{
var context = listener.GetContext();
HttpListenerRequest request = context.Request;
var message = request.QueryString.Get("message");
if (string.IsNullOrEmpty(message))
{
RespondWith(context, "FAIL");
}
else
{
SendNotification(message);
RespondWith(context, "OK");
}
}
}
private async void SendNotification(string message)
{
var token = config.RootElement.GetProperty("token").GetString();
var botClient = new TelegramBotClient(token);
foreach(var element in config.RootElement.GetProperty("notify_user_ids").EnumerateArray())
{
await botClient.SendTextMessageAsync(
chatId: element.GetString(),
text: message
);
}
}
private void RespondWith(HttpListenerContext context, string v)
{
HttpListenerResponse response = context.Response;
string responseString = v;
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
}
}