Skip to content

Instantly share code, notes, and snippets.

@ricardojoserf
Created March 24, 2021 20:31
Show Gist options
  • Save ricardojoserf/c5ab2d043067ccbf00bd39604769034d to your computer and use it in GitHub Desktop.
Save ricardojoserf/c5ab2d043067ccbf00bd39604769034d to your computer and use it in GitHub Desktop.
Telegram bot to execute commands with "/cmd" and get the output
# 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()
@freerider7777
Copy link

I did pip3 install python-telegram-bot
but running on windows it writes:

ModuleNotFoundError: No module named 'telegram.ext.dispatcher'

Python 3.9.7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment