Spaces:
Runtime error
Runtime error
| import logging | |
| from telegram import Update | |
| from telegram.ext import Application, MessageHandler, filters, ContextTypes | |
| # --- Configuration --- | |
| # 1. Replace with your actual bot token | |
| BOT_TOKEN = "8103639461:AAF_F1lLwqKWUWUIuR-erBVzsODz1W37DYM" | |
| # 2. Specify the base URL for the API server. | |
| # - For the official Telegram API: "https://api.telegram.org/" | |
| # - For a locally hosted API server: e.g., "http://localhost:8081/" | |
| BASE_API_URL = "https://hu-c3kd.onrender.com/see/bot" # We use the official URL here as an explicit example | |
| # Set up logging for better error visibility | |
| logging.basicConfig( | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
| level=logging.INFO | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # --- Handler Functions --- | |
| async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: | |
| """ | |
| Echoes the user's message back to them. | |
| This function is an asynchronous coroutine (`async def`). | |
| """ | |
| user_text = update.message.text | |
| logger.info(f"Received message from {update.message.from_user.username}: {user_text}") | |
| # Send the received text back to the same chat | |
| await update.message.reply_text(user_text) | |
| async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: | |
| """Sends a greeting when the command /start is issued.""" | |
| await update.message.reply_text("Hello! I am an echo bot. Send me any message and I will repeat it back to you.") | |
| # --- Main Application Setup --- | |
| def main() -> None: | |
| """Start the bot.""" | |
| # 1. Build the Application using the builder pattern | |
| application = ( | |
| Application.builder() | |
| .token(BOT_TOKEN) | |
| # 2. Explicitly set the base_url for the API server | |
| # Note: PTB adds 'bot<token>/' automatically, so only the root is needed. | |
| .base_url(BASE_API_URL) | |
| .build() | |
| ) | |
| # 3. Add Handlers to the Application | |
| # A MessageHandler filters for regular messages (not commands) and passes them to the echo function. | |
| # filters.TEXT & ~filters.COMMAND ensures only text messages that are NOT commands are processed. | |
| application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo)) | |
| # A CommandHandler filters for /start command | |
| from telegram.ext import CommandHandler | |
| application.add_handler(CommandHandler("start", start)) | |
| # 4. Start the Bot: The bot runs indefinitely until interrupted (e.g., Ctrl+C) | |
| logger.info("Bot started successfully. Polling for updates...") | |
| application.run_polling(allowed_updates=Update.ALL_TYPES) | |
| if __name__ == '__main__': | |
| main() | |