pythonsandbox-pyramids / telegram_bot.py
Khalel81765's picture
اصنع لي كود بلغة بايثون لبوت تليكرام استضافة بايثون ،
41ab270 verified
```python
import os
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext, CallbackQueryHandler
import subprocess
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
# Bot token from environment variable
TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
def start(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /start is issued."""
user = update.effective_user
keyboard = [
[InlineKeyboardButton("Run Python Code", callback_data='run_code')],
[InlineKeyboardButton("Help", callback_data='help')]
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(
f'Hi {user.first_name}! I am PythonSandbox Bot.\n'
'I can execute Python code in a secure sandbox environment.',
reply_markup=reply_markup
)
def help_command(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /help is issued."""
update.message.reply_text(
'Send me Python code and I will execute it for you!\n\n'
'Commands:\n'
'/start - Start the bot\n'
'/help - Show this help message\n\n'
'How to use:\n'
'1. Send your Python code directly\n'
'2. Or use the inline buttons to interact'
)
def handle_code(update: Update, context: CallbackContext) -> None:
"""Handle incoming Python code messages."""
code = update.message.text
# Save code to temporary file
with open('temp.py', 'w') as f:
f.write(code)
try:
# Execute the code in a secure environment
result = subprocess.run(
['python', 'temp.py'],
capture_output=True,
text=True,
timeout=10
)
if result.returncode == 0:
output = result.stdout if result.stdout else "Code executed successfully (no output)"
else:
output = f"Error:\n{result.stderr}"
update.message.reply_text(f"Output:\n```\n{output}\n```", parse_mode='Markdown')
except subprocess.TimeoutExpired:
update.message.reply_text("Execution timed out (10s limit)")
except Exception as e:
update.message.reply_text(f"An error occurred: {str(e)}")
finally:
# Clean up
if os.path.exists('temp.py'):
os.remove('temp.py')
def button(update: Update, context: CallbackContext) -> None:
"""Handle button presses."""
query = update.callback_query
query.answer()
if query.data == 'run_code':
query.edit_message_text("Please send me your Python code to execute.")
elif query.data == 'help':
help_command(update, context)
def main() -> None:
"""Start the bot."""
updater = Updater(TOKEN)
dispatcher = updater.dispatcher
# Command handlers
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("help", help_command))
# Message handler for Python code
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_code))
# Button handler
dispatcher.add_handler(CallbackQueryHandler(button))
# Start the Bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
```