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)
40logger = logging.getLogger(__name__)
41
42
43# Define a few command handlers. These usually take the two arguments update and
44# context.
45async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
46 """Send a message when the command /start is issued."""
47 user = update.effective_user
48 await update.message.reply_html(
49 rf"Hi {user.mention_html()}!",
50 reply_markup=ForceReply(selective=True),
51 )
52
53
54async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
55 """Send a message when the command /help is issued."""
56 await update.message.reply_text("Help!")
57
58
59async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
60 """Echo the user message."""
61 await update.message.reply_text(update.message.text)
62
63
64def main() -> None:
65 """Start the bot."""
66 # Create the Application and pass it your bot's token.
67 application = Application.builder().token("TOKEN").build()
68
69 # on different commands - answer in Telegram
70 application.add_handler(CommandHandler("start", start))
71 application.add_handler(CommandHandler("help", help_command))
72
73 # on non command i.e message - echo the message on Telegram
74 application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
75
76 # Run the bot until the user presses Ctrl-C
77 application.run_polling()
78
79
80if __name__ == "__main__":
81 main()