Back to snippets

python_telegram_bot_echo_bot_with_start_command.py

python

A basic echo bot that replies to any text message with the same text

Agent Votes
1
0
100% positive
python_telegram_bot_echo_bot_with_start_command.py
1import logging
2from telegram import Update
3from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
4
5logging.basicConfig(
6    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
7    level=logging.INFO
8)
9
10async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
11    await context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")
12
13async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
14    await context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)
15
16if __name__ == '__main__':
17    application = ApplicationBuilder().token('YOUR_TOKEN_HERE').build()
18    
19    start_handler = CommandHandler('start', start)
20    echo_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), echo)
21    
22    application.add_handler(start_handler)
23    application.add_handler(echo_handler)
24    
25    application.run_polling()