Created
March 24, 2021 20:31
-
-
Save ricardojoserf/c5ab2d043067ccbf00bd39604769034d to your computer and use it in GitHub Desktop.
Telegram bot to execute commands with "/cmd" and get the output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Installation: pip3 install python-telegram-bot | |
# Usage: /cmd COMMAND | |
# Examples: /cmd whoami, /cmd ls -la, /cmd echo "a" > a.txt | |
from telegram.ext import Updater, CommandHandler | |
from telegram.ext.dispatcher import run_async | |
import subprocess | |
# Fill with your token after creating a bot using @BotFather | |
token = "" | |
def exec_cmd(command): | |
try: | |
sub_ = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) | |
subprocess_return = sub_.stdout.read() | |
return subprocess_return.decode("utf-8") | |
except: | |
return "There was an error executing the command" | |
#@run_async | |
def cmd(update, context): | |
chat_id = update.message.chat_id | |
command = " ".join(context.args) | |
subprocess_return = exec_cmd(command) | |
context.bot.sendMessage(chat_id, subprocess_return) | |
def main(): | |
updater = Updater(token, use_context=True) | |
dp = updater.dispatcher | |
dp.add_handler(CommandHandler('cmd',cmd)) | |
updater.start_polling() | |
updater.idle() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I did pip3 install python-telegram-bot
but running on windows it writes:
ModuleNotFoundError: No module named 'telegram.ext.dispatcher'
Python 3.9.7