echobot.pyΒΆ

 1#!/usr/bin/env python
 2# pylint: disable=unused-argument
 3# This program is dedicated to the public domain under the CC0 license.
 4
 5"""
 6Simple Bot to reply to Telegram messages.
 7
 8First, a few handler functions are defined. Then, those functions are passed to
 9the Application and registered at their respective places.
10Then, the bot is started and runs until we press Ctrl-C on the command line.
11
12Usage:
13Basic Echobot example, repeats messages.
14Press Ctrl-C on the command line or send a signal to the process to stop the
15bot.
16"""
17
18import logging
19
20from telegram import ForceReply, Update
21from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
22
23# Enable logging
24logging.basicConfig(
25    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
26)
27# set higher logging level for httpx to avoid all GET and POST requests being logged
28logging.getLogger("httpx").setLevel(logging.WARNING)
29
30logger = logging.getLogger(__name__)
31
32
33# Define a few command handlers. These usually take the two arguments update and
34# context.
35async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
36    """Send a message when the command /start is issued."""
37    user = update.effective_user
38    await update.message.reply_html(
39        rf"Hi {user.mention_html()}!",
40        reply_markup=ForceReply(selective=True),
41    )
42
43
44async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
45    """Send a message when the command /help is issued."""
46    await update.message.reply_text("Help!")
47
48
49async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
50    """Echo the user message."""
51    await update.message.reply_text(update.message.text)
52
53
54def main() -> None:
55    """Start the bot."""
56    # Create the Application and pass it your bot's token.
57    application = Application.builder().token("TOKEN").build()
58
59    # on different commands - answer in Telegram
60    application.add_handler(CommandHandler("start", start))
61    application.add_handler(CommandHandler("help", help_command))
62
63    # on non command i.e message - echo the message on Telegram
64    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
65
66    # Run the bot until the user presses Ctrl-C
67    application.run_polling(allowed_updates=Update.ALL_TYPES)
68
69
70if __name__ == "__main__":
71    main()