|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +# This example shows how to implement session creation and retrieval based on user id with middleware handler. |
| 4 | +# |
| 5 | +# Note: For the sake of simplicity of this example no extra library is used. However, it is recommended to use |
| 6 | +# in-memory or on-disk storage implementations (redis, mysql, postgres and etc) for storing and retrieving structures. |
| 7 | +# This is not a working, production-ready sample and it is highly recommended not to use it in production. |
| 8 | +# |
| 9 | +# In this example let's imagine we want to create a session for each user who communicates with the bot to store |
| 10 | +# different kind of temporary data while session is active. As an example we want to track the state of the user |
| 11 | +# with the help of this session. So, we need a way to store this session data somewhere globally to enable other |
| 12 | +# message handler functions to be able to use it. |
| 13 | +# The middleware session is explained: |
| 14 | + |
| 15 | +import telebot |
| 16 | +from telebot import apihelper |
| 17 | + |
| 18 | +apihelper.ENABLE_MIDDLEWARE = True |
| 19 | + |
| 20 | +INFO_STATE = 'ON_INFO_MENU' |
| 21 | +MAIN_STATE = 'ON_MAIN_MENU' |
| 22 | + |
| 23 | +SESSIONS = { |
| 24 | + -10000: { |
| 25 | + 'state': INFO_STATE |
| 26 | + }, |
| 27 | + -11111: { |
| 28 | + 'state': MAIN_STATE |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | + |
| 33 | +def get_or_create_session(user_id): |
| 34 | + try: |
| 35 | + return SESSIONS[user_id] |
| 36 | + except KeyError: |
| 37 | + SESSIONS[user_id] = {'state': MAIN_STATE} |
| 38 | + return SESSIONS[user_id] |
| 39 | + |
| 40 | + |
| 41 | +bot = telebot.TeleBot('TOKEN') |
| 42 | + |
| 43 | + |
| 44 | +@bot.middleware_handler(update_types=['message']) |
| 45 | +def set_session(bot_instance, message): |
| 46 | + bot_instance.session = get_or_create_session(message.from_user.id) |
| 47 | + |
| 48 | + |
| 49 | +@bot.message_handler(commands=['start']) |
| 50 | +def start(message): |
| 51 | + bot.session['state'] = MAIN_STATE |
| 52 | + bot.send_message(message.chat.id, bot.session['state']) |
| 53 | + |
| 54 | + |
| 55 | +@bot.message_handler(commands=['info']) |
| 56 | +def start(message): |
| 57 | + bot.session['state'] = INFO_STATE |
| 58 | + bot.send_message(message.chat.id, bot.session['state']) |
| 59 | + |
| 60 | + |
| 61 | +bot.polling() |
0 commit comments