echobot.pyΒΆ

 1#!/usr/bin/env python
 2# pylint: disable=unused-argument, wrong-import-position
 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 __version__ as TG_VER
21
22try:
23    from telegram import __version_info__
24except ImportError:
25    __version_info__ = (0, 0, 0, 0, 0)  # type: ignore[assignment]
26
27if __version_info__ < (20, 0, 0, "alpha", 1):
28    raise RuntimeError(
29        f"This example is not compatible with your current PTB version {TG_VER}. To view the "
30        f"{TG_VER} version of this example, "
31        f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
32    )
33from telegram import ForceReply, Update
34from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
35
36# Enable logging
37logging.basicConfig(
38    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
39)
40# set higher logging level for httpx to avoid all GET and POST requests being logged
41logging.getLogger("httpx").setLevel(logging.WARNING)
42
43logger = logging.getLogger(__name__)
44
45
46# Define a few command handlers. These usually take the two arguments update and
47# context.
48async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
49    """Send a message when the command /start is issued."""
50    user = update.effective_user
51    await update.message.reply_html(
52        rf"Hi {user.mention_html()}!",
53        reply_markup=ForceReply(selective=True),
54    )
55
56
57async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
58    """Send a message when the command /help is issued."""
59    await update.message.reply_text("Help!")
60
61
62async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
63    """Echo the user message."""
64    await update.message.reply_text(update.message.text)
65
66
67def main() -> None:
68    """Start the bot."""
69    # Create the Application and pass it your bot's token.
70    application = Application.builder().token("TOKEN").build()
71
72    # on different commands - answer in Telegram
73    application.add_handler(CommandHandler("start", start))
74    application.add_handler(CommandHandler("help", help_command))
75
76    # on non command i.e message - echo the message on Telegram
77    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
78
79    # Run the bot until the user presses Ctrl-C
80    application.run_polling(allowed_updates=Update.ALL_TYPES)
81
82
83if __name__ == "__main__":
84    main()