#include "execbot.h" #include #include ExecBot::ExecBot(QObject *parent) : TelegramBotBase(parent) { } QString ExecBot::loginMessage(uint id) { if (sessions.contains(id)) { if (sessions[id] == Password) return tr("Enter password"); if (sessions[id] == NotLogged) return tr("Please send me /start"); } return tr("Error"); } QString ExecBot::help() { return tr("Input command for exec on server, after exec finished result will be sended to you"); } bool ExecBot::loginUser(uint id, const QString &msg) { if (sessions.contains(id)) { switch (sessions[id]) { case NotLogged: if (msg == "/start") sessions[id] = Password; break; case Password: if (msg == "shspasswd") { sessions[id] = Ready; return true; } break; case Ready: case CommandExec: return true; default: break; return false; } } else { if (msg == "/start") sessions[id] = Password; else sessions[id] = NotLogged; } return false; } void ExecBot::messageFromUser(uint id, const QString &msg) { if (sessions.contains(id)) { if (msg == "/exit") { sessions[id] = NotLogged; disconnectUser(id); getAPI()->sendMessage(id, tr("Logout")); return; } if (sessions[id] == CommandExec) { if (msg == "/kill") { int rm = -1; for (int i=0; ikill(); getAPI()->sendMessage(id, tr("Process killed")); sessions[id] = Ready; rm = i; } } if (rm >= 0) run_commands.remove(rm); } else getAPI()->sendMessage(id, tr("Command is running, please wait for finish")); return; } if (sessions[id] == Ready) { getAPI()->sendMessage(id, "exec: " + msg); UserCommand uc; uc.user = id; uc.cmd = new QProcess(); // uc.cmd->setProcessChannelMode(QProcess::MergedChannels); connect(uc.cmd, SIGNAL(readyRead()), this, SLOT(cmdRead())); // connect(uc.cmd, SIGNAL(started()), this, SLOT(cmdStart())); connect(uc.cmd, SIGNAL(finished(int)), this, SLOT(cmdFinish(int))); uc.cmd->start(msg); if (uc.cmd->waitForStarted(3000)) { sessions[id] = CommandExec; run_commands.append(uc); } else getAPI()->sendMessage(id, tr("Can't run command %1").arg(msg)); } } } void ExecBot::cmdRead() { // qDebug() << "cmdRead()"; QProcess * p = (QProcess *)sender(); for (int i=0; ireadAll());//codec->toUnicode(p->readAll()); getAPI()->sendMessage(id, s); } } } void ExecBot::cmdFinish(int code) { qDebug() << "cmdFinish()" << code; QProcess * p = (QProcess *)sender(); int rm = -1; for (int i=0; ireadAll()); //codec->toUnicode(p->readAll()); getAPI()->sendMessage(id, s); rm = i; sessions[id] = Ready; } } if (rm >= 0) run_commands.remove(rm); }