112 lines
2.6 KiB
C#
112 lines
2.6 KiB
C#
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.Args;
|
|
using Telegram.Bot.Types.InputFiles;
|
|
using Telegram.Bot.Types.ReplyMarkups;
|
|
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;
|
|
|
|
public CamerasMenuUserState(ITelegramBotClient botClient, JsonDocument config, OpenHabClient openhab)
|
|
{
|
|
this.botClient = botClient;
|
|
this.config = config;
|
|
this.openhab = openhab;
|
|
cameras = new List<CameraConfigData>();
|
|
foreach (var element in 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, MessageEventArgs e)
|
|
{
|
|
if (e.Message.Text == CMD_BACK)
|
|
{
|
|
var newState = new MainMenuUserState(botClient, config, openhab);
|
|
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,
|
|
resizeKeyboard: true
|
|
);
|
|
|
|
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: new InputOnlineFile(content: stream, fileName: cam.name + ".jpg")
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|