1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
'''
Proof of concept to send messages to bot, and get reply using keyboard buttons.
Based on:
https://docs.python-telegram-bot.org/en/stable/examples.inlinekeyboard.html
and a bit of:
https://docs.python-telegram-bot.org/en/stable/examples.echobot.html
'''
import logging
import yaml
from telegram import InlineKeyboardButton, ReplyKeyboardMarkup, Update
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
MessageHandler,
filters,
)
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)
logger = logging.getLogger(__name__)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send message on `/start`."""
# Get user that sent /start and log their name
user = update.message.from_user
logger.info("User %s started the conversation.", user.first_name)
# Build InlineKeyboard where each button has a displayed text
# and a string as callback_data
# The keyboard is a list of button rows, where each row is in turn
# a list (hence `[[...]]`).
keyboard = [
[
InlineKeyboardButton("/1", callback_data='/2'),
InlineKeyboardButton("/2", callback_data='/2'),
]
]
reply_markup = ReplyKeyboardMarkup(keyboard)
# Send message with text and appended InlineKeyboard
await update.message.reply_text("Start handler, Choose a route", reply_markup=reply_markup)
# Tell ConversationHandler that we're in state `FIRST` now
return None
async def one(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /1 is issued."""
await update.message.reply_text("First")
async def two(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /2 is issued."""
await update.message.reply_text("Second")
def main() -> None:
"""Run the bot."""
# Create the Application and pass it your bot's token.
with open("src/config.yml", "r") as file:
config = yaml.safe_load(file)
application = Application.builder().token(config["telegram"]["token"]).build()
# Add command handlers
application.add_handler(CommandHandler("1", one))
application.add_handler(CommandHandler("2", two))
# Everything except the commands match start
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, start))
# Run the bot until the user presses Ctrl-C
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()
|