Created
February 7, 2025 09:25
-
-
Save kiemrong08/611dc137ef31ab0118e8c3fc94caf0ab to your computer and use it in GitHub Desktop.
command prompt telegram bot
This file contains hidden or 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
from telegram.ext import Application, CommandHandler | |
from telegram import Update | |
import subprocess | |
import logging | |
from typing import List | |
# Enable logging | |
logging.basicConfig( | |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
level=logging.INFO | |
) | |
# Fill with your token after creating a bot using @BotFather | |
TOKEN = "" | |
async def exec_cmd(command: str) -> str: | |
"""Execute a system command and return its output.""" | |
try: | |
process = subprocess.Popen( | |
command, | |
shell=True, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE | |
) | |
output, error = process.communicate() | |
if error: | |
return error.decode("utf-8") | |
return output.decode("utf-8") | |
except Exception as e: | |
return f"There was an error executing the command: {str(e)}" | |
async def cmd(update, context): | |
"""Handle the /cmd command.""" | |
if not context.args: | |
await update.message.reply_text("Please provide a command to execute.") | |
return | |
command = " ".join(context.args) | |
result = await exec_cmd(command) | |
# Split long messages if they exceed Telegram's message length limit | |
if len(result) > 4096: | |
for i in range(0, len(result), 4096): | |
await update.message.reply_text(result[i:i+4096]) | |
else: | |
await update.message.reply_text(result) | |
def main(): | |
"""Start the bot.""" | |
# Create application with your bot token | |
application = Application.builder().token(TOKEN).build() | |
# Add command handler | |
application.add_handler(CommandHandler("cmd", cmd)) | |
# Start the bot | |
print("Starting bot...") | |
application.run_polling(allowed_updates=Update.ALL_TYPES) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment