python-telegram-bot/examples/echobot.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

72 lines
2.3 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python
# pylint: disable=unused-argument
2020-07-16 19:17:57 +02:00
# This program is dedicated to the public domain under the CC0 license.
"""
2020-07-16 19:17:57 +02:00
Simple Bot to reply to Telegram messages.
First, a few handler functions are defined. Then, those functions are passed to
the Application and registered at their respective places.
2020-07-16 19:17:57 +02:00
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Basic Echobot example, repeats messages.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
import logging
from telegram import ForceReply, Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
2020-07-16 19:17:57 +02:00
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
# set higher logging level for httpx to avoid all GET and POST requests being logged
logging.getLogger("httpx").setLevel(logging.WARNING)
2020-07-16 19:17:57 +02:00
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and
# context.
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
2020-07-16 19:17:57 +02:00
"""Send a message when the command /start is issued."""
user = update.effective_user
await update.message.reply_html(
rf"Hi {user.mention_html()}!",
reply_markup=ForceReply(selective=True),
)
2020-07-16 19:17:57 +02:00
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
2020-07-16 19:17:57 +02:00
"""Send a message when the command /help is issued."""
await update.message.reply_text("Help!")
2020-07-16 19:17:57 +02:00
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
2020-07-16 19:17:57 +02:00
"""Echo the user message."""
await update.message.reply_text(update.message.text)
2016-06-12 15:30:56 +02:00
def main() -> None:
2020-07-16 19:17:57 +02:00
"""Start the bot."""
# Create the Application and pass it your bot's token.
application = Application.builder().token("TOKEN").build()
2020-07-16 19:17:57 +02:00
# on different commands - answer in Telegram
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
2020-07-16 19:17:57 +02:00
# on non command i.e message - echo the message on Telegram
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
2020-07-16 19:17:57 +02:00
# Run the bot until the user presses Ctrl-C
application.run_polling(allowed_updates=Update.ALL_TYPES)
2015-08-20 19:58:57 +02:00
if __name__ == "__main__":
main()