Files
zaobot/CamerasMenuUserState.cs
2024-01-20 18:37:52 +03:00

113 lines
2.7 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types.ReplyMarkups;
using ZaoBot.Config;
using ZaoBot.OpenHab;
namespace ZaoBot
{
class CameraConfigData
{
public string name;
public string url;
}
class CamerasMenuUserState : IUserState
{
public const string CMD_BACK = "Назад";
ITelegramBotClient botClient;
private JsonDocument config;
List<CameraConfigData> cameras;
OpenHabClient openhab;
IServiceProvider services;
public CamerasMenuUserState(IServiceProvider services, ITelegramBotClient botClient, IConfig config, OpenHabClient openhab)
{
this.botClient = botClient;
this.config = config.Data;
this.openhab = openhab;
this.services = services;
cameras = new List<CameraConfigData>();
foreach (var element in this.config.RootElement.GetProperty("cameras").EnumerateObject())
{
var cam = new CameraConfigData()
{
name = element.Name,
url = element.Value.GetString(),
};
cameras.Add(cam);
}
}
public async Task<IUserState> ProcessMessage(IUserState previous, Telegram.Bot.Types.Update e)
{
if (e.Message.Text == CMD_BACK)
{
var newState = services.GetRequiredService<MainMenuUserState>();
await newState.ProcessMessage(this, e);
return newState;
}
var response = "Выберите камеру";
foreach (var cam in cameras)
{
if (e.Message.Text == cam.name)
{
try
{
await SendCameraImage(e.Message.Chat, cam);
}
catch (Exception ex)
{
await botClient.SendTextMessageAsync(chatId: e.Message.Chat,
text: "Error: " + ex.Message);
}
}
}
var buttons = new KeyboardButton[cameras.Count + 1][];
for (int i = 0; i < cameras.Count; i++)
{
buttons[i] = new KeyboardButton[] { cameras[i].name };
}
buttons[cameras.Count] = new KeyboardButton[] { CMD_BACK };
var replyKeyboardMarkup = new ReplyKeyboardMarkup(
buttons
);
await botClient.SendTextMessageAsync(
chatId: e.Message.Chat,
text: response,
replyMarkup: replyKeyboardMarkup
);
return this;
}
private async Task SendCameraImage(Telegram.Bot.Types.Chat chat, CameraConfigData cam)
{
using (WebClient client = new WebClient())
{
await client.DownloadFileTaskAsync(
new System.Uri(cam.url),
"temp.jpg"
);
using (Stream stream = File.OpenRead("temp.jpg"))
{
await botClient.SendDocumentAsync(
chatId: chat,
document: Telegram.Bot.Types.InputFile.FromStream(stream: stream, fileName: cam.name + ".jpg")
);
}
}
}
}
}