namespace tg_bot
{
public class TgBot
{
public TelegramBotClient client;
private string screenshotPath = @"D:\temp";
string apiKey = "";
string users = ""; // Comma separated authorized users
/// <summary>
/// Начинаем работу бота
/// </summary>
/// <param name="project"></param>
/// <returns></returns>
public async Task<bool> Start()
{
client = new TelegramBotClient(apiKey);
var me = await client.GetMeAsync();
Console.WriteLine($@"Бот ""{me.Username}"" запущен", true);
client.OnMessage += BotOnMessageReceived;
client.OnCallbackQuery += BotOnCallbackQueryReceived;
client.StartReceiving(Array.Empty<UpdateType>());
return true;
}
/// <summary>
/// Обработка входящих сообщений
/// </summary>
/// <param name="sender"></param>
/// <param name="messageEventArgs"></param>
async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
{
var message = messageEventArgs.Message;
if (message == null || message.Type != MessageType.Text)
return;
if (!CheckAutorized(message.Chat.Username))
{
try
{
await client.SendTextMessageAsync(
chatId: message.Chat.Id,
text: "Недостаточно прав."
);
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка BotOnCallbackQueryReceived: {ex.Message}", true);
return;
}
Console.WriteLine($"Неавторизованный пользователь: {message.Chat.Username} написал: {message.Text}", true);
return;
}
Console.WriteLine($"{message.Chat.Username} написал {message.Text}", true);
string command = message.Text.Split(' ').First();
switch (command)
{
// Любая команда
default:
await MainMenu(message.Chat.Id);
break;
}
}
/// <summary>
/// Основное меню
/// </summary>
/// <param name="message"></param>
/// <param name="onlyWork"></param>
/// <returns></returns>
async Task MainMenu(long userId)
{
// Создаем массив кнопок
List<IEnumerable<InlineKeyboardButton>> rowArr = new List<IEnumerable<InlineKeyboardButton>>();
rowArr.Add(new[]
{
InlineKeyboardButton.WithCallbackData("CPU", "/cpu"),
InlineKeyboardButton.WithCallbackData("Скриншот", "/screen"),
});
rowArr.Add(new[]
{
InlineKeyboardButton.WithCallbackData("Команда 1", "/test1"),
InlineKeyboardButton.WithCallbackData("Команда 2", "/test2"),
});
InlineKeyboardMarkup inlineKeyboard = new InlineKeyboardMarkup(rowArr);
try
{
await client.SendTextMessageAsync(
chatId: userId,
text: "Список команд:",
replyMarkup: inlineKeyboard
);
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка SendInlineKeyboard: {ex.Message}", true);
return;
}
}
/// <summary>
/// Обработка нажатий Inline кнопок
/// </summary>
/// <param name="sender"></param>
/// <param name="callbackQueryEventArgs"></param>
private async void BotOnCallbackQueryReceived(object sender, CallbackQueryEventArgs callbackQueryEventArgs)
{
var callbackQuery = callbackQueryEventArgs.CallbackQuery;
if (!CheckAutorized(callbackQuery.Message.Chat.Username))
{
try
{
await client.SendTextMessageAsync(
chatId: callbackQuery.Message.Chat.Id,
text: "Недостаточно прав."
);
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка BotOnCallbackQueryReceived: {ex.Message}", true);
return;
}
Console.WriteLine($"Неавторизованный пользователь: {callbackQuery.Message.Chat.Username} нажал: {callbackQuery.Data}", true);
return;
}
Console.WriteLine($"{callbackQuery.Message.Chat.Username} выбрал {callbackQuery.Data}", true);
string[] callbackArr = callbackQuery.Data.Split('|');
string task = callbackArr[0];
string message = "";
InlineKeyboardMarkup inlineKeyboard = null;
switch (task)
{
// Сделать скриншот
case "/screen":
await GetScreen(callbackQuery.Message.Chat.Id);
return;
case "/cpu": // Узнать загруженность системы
float cpu;
string freeMemery;
//Процессора
using (var pc = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total"))
{
cpu = pc.NextValue();
Thread.Sleep(1000);
cpu = pc.NextValue();
}
// Свободно оперативы
using (var mem = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes"))
{
freeMemery = (mem.NextValue() / 1024.0).ToString("N2"); ;
}
message = $"Нагрузка на CPU : {(int)cpu}%. \nСвободно памяти: {freeMemery} GB";
break;
default:
return;
}
// Создаем кнопки управления
try
{
await client.SendTextMessageAsync(
chatId: callbackQuery.Message.Chat.Id,
text: message,
parseMode: ParseMode.Html,
replyMarkup: inlineKeyboard
);
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка BotOnCallbackQueryReceived: {ex.Message}", true);
return;
}
}
async Task GetScreen(long userId)
{
string fileName = DateTime.Now.ToString("yy.MM.dd_HH.mm.ss") + ".jpeg";
string path = Path.Combine(screenshotPath);
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(printscreen as Image);
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
printscreen.Save(path + fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
using (var fileStream = new FileStream(path + fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
await client.SendPhotoAsync(
chatId: userId,
photo: new InputOnlineFile(fileStream, fileName),
caption: $"Снимок экрана {fileName}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка GetScreen: {ex.Message}", true);
return;
}
}
bool CheckAutorized(string userName)
{
string[] authorizedUsers = users.Split(',');
if (!authorizedUsers.Contains(userName))
{
return false;
}
return true;
}
}
}