69 lines
2.2 KiB
C++
69 lines
2.2 KiB
C++
#include "bot.h"
|
|
|
|
|
|
namespace fs = std::filesystem;
|
|
|
|
Bot::Bot(const std::string& token) : botToken(token), bot(token) {
|
|
// Инициализация бота
|
|
bot.getEvents().onCommand("list", [this](TgBot::Message::Ptr message) {
|
|
handleCommand(message);
|
|
});
|
|
bot.getEvents().onCommand("get", [this](TgBot::Message::Ptr message) {
|
|
if (!message->text.empty()) {
|
|
sendFile(message, message->text);
|
|
}
|
|
});
|
|
}
|
|
|
|
void Bot::run() {
|
|
bot.getApi().deleteWebhook();
|
|
TgBot::TgLongPoll longPoll(bot);
|
|
|
|
while (true) {
|
|
try {
|
|
longPoll.start();
|
|
} catch (const std::exception& e) {
|
|
std::cerr << "Exception: " << e.what() << std::endl;
|
|
}
|
|
}
|
|
}
|
|
|
|
void Bot::handleCommand(const TgBot::Message::Ptr& message) {
|
|
if (message->text == "/list") {
|
|
std::async(std::launch::async, &Bot::updateCacheAsync, this);
|
|
sendFileList(message);
|
|
}
|
|
}
|
|
|
|
void Bot::updateCacheAsync() {
|
|
std::lock_guard<std::mutex> lock(cacheMutex);
|
|
fileCache.clear();
|
|
|
|
for (const auto& entry : fs::directory_iterator("/home/pi/study")) {
|
|
fileCache.push_back(entry.path().filename().string());
|
|
}
|
|
}
|
|
|
|
void Bot::sendFileList(const TgBot::Message::Ptr& message) {
|
|
std::lock_guard<std::mutex> lock(cacheMutex);
|
|
std::string fileList = "Current files:\n";
|
|
for (const auto& file : fileCache) {
|
|
fileList += file + "\n";
|
|
}
|
|
bot.getApi().sendMessage(message->chat->id, fileList);
|
|
}
|
|
|
|
|
|
void Bot::sendFile(const TgBot::Message::Ptr& message, const std::string& fileName) {
|
|
std::ifstream file(fileName, std::ios::binary);
|
|
if (file) {
|
|
// Читаем содержимое файла в строковый поток (stringstream)
|
|
std::stringstream fileContents;
|
|
fileContents << file.rdbuf();
|
|
|
|
// Отправляем документ, передавая строковый поток в конструктор InputFile::fromFile
|
|
bot.getApi().sendDocument(message->chat->id, TgBot::InputFile::fromFile(fileName, fileContents.str()));
|
|
} else {
|
|
bot.getApi().sendMessage(message->chat->id, "File not found: " + fileName);
|
|
}
|
|
} |