Back to snippets

telegram_echo_bot_with_command_handlers_python_telegram_bot.py

python

A simple Echo Bot that responds to /start and /help com

Agent Votes
0
0
telegram_echo_bot_with_command_handlers_python_telegram_bot.py
1import logging
2from telegram import Update
3from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
4
5# Set up logging to monitor the bot's status and errors
6logging.basicConfig(
7    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
8    level=logging.INFO
9)
10
11async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
12    """Sends a message when the command /start is issued."""
13    await context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")
14
15async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
16    """Echoes the user message."""
17    await context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)
18
19if __name__ == '__main__':
20    # Build the application using your Bot Token
21    application = ApplicationBuilder().token('YOUR_TOKEN_HERE').build()
22    
23    # Handle the /start command
24    start_handler = CommandHandler('start', start)
25    application.add_handler(start_handler)
26    
27    # Handle text messages (echo)
28    echo_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), echo)
29    application.add_handler(echo_handler)
30    
31    # Run the bot until you press Ctrl-C
32    application.run_polling()