Skip to content

Commit 2e99472

Browse files
authored
Merge pull request eternnoir#1421 from coder2020official/master
RedisStorage, middleware fix, pass_bot parameter and more
2 parents cf2eb1f + c350ea0 commit 2e99472

20 files changed

Lines changed: 1273 additions & 561 deletions
Lines changed: 34 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,36 @@
11
import telebot
22
from telebot import asyncio_filters
33
from telebot.async_telebot import AsyncTeleBot
4-
bot = AsyncTeleBot('TOKEN')
54

5+
# list of storages, you can use any storage
6+
from telebot.asyncio_storage import StateRedisStorage,StateMemoryStorage,StatePickleStorage
67

8+
# new feature for states.
9+
from telebot.asyncio_handler_backends import State, StatesGroup
710

8-
class MyStates:
9-
name = 1
10-
surname = 2
11-
age = 3
11+
# default state storage is statememorystorage
12+
bot = AsyncTeleBot('TOKEN', state_storage=StateMemoryStorage())
1213

1314

15+
# Just create different statesgroup
16+
class MyStates(StatesGroup):
17+
name = State() # statesgroup should contain states
18+
surname = State()
19+
age = State()
20+
21+
22+
23+
# set_state -> sets a new state
24+
# delete_state -> delets state if exists
25+
# get_state -> returns state if exists
26+
1427

1528
@bot.message_handler(commands=['start'])
1629
async def start_ex(message):
1730
"""
1831
Start command. Here we are starting state
1932
"""
20-
await bot.set_state(message.from_user.id, MyStates.name)
33+
await bot.set_state(message.from_user.id, MyStates.name, message.chat.id)
2134
await bot.send_message(message.chat.id, 'Hi, write me a name')
2235

2336

@@ -28,48 +41,52 @@ async def any_state(message):
2841
Cancel state
2942
"""
3043
await bot.send_message(message.chat.id, "Your state was cancelled.")
31-
await bot.delete_state(message.from_user.id)
44+
await bot.delete_state(message.from_user.id, message.chat.id)
3245

3346
@bot.message_handler(state=MyStates.name)
3447
async def name_get(message):
3548
"""
36-
State 1. Will process when user's state is 1.
49+
State 1. Will process when user's state is MyStates.name.
3750
"""
3851
await bot.send_message(message.chat.id, f'Now write me a surname')
39-
await bot.set_state(message.from_user.id, MyStates.surname)
40-
async with bot.retrieve_data(message.from_user.id) as data:
52+
await bot.set_state(message.from_user.id, MyStates.surname, message.chat.id)
53+
async with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
4154
data['name'] = message.text
4255

4356

4457
@bot.message_handler(state=MyStates.surname)
4558
async def ask_age(message):
4659
"""
47-
State 2. Will process when user's state is 2.
60+
State 2. Will process when user's state is MyStates.surname.
4861
"""
4962
await bot.send_message(message.chat.id, "What is your age?")
50-
await bot.set_state(message.from_user.id, MyStates.age)
51-
async with bot.retrieve_data(message.from_user.id) as data:
63+
await bot.set_state(message.from_user.id, MyStates.age, message.chat.id)
64+
async with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
5265
data['surname'] = message.text
5366

5467
# result
5568
@bot.message_handler(state=MyStates.age, is_digit=True)
5669
async def ready_for_answer(message):
57-
async with bot.retrieve_data(message.from_user.id) as data:
70+
"""
71+
State 3. Will process when user's state is MyStates.age.
72+
"""
73+
async with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
5874
await bot.send_message(message.chat.id, "Ready, take a look:\n<b>Name: {name}\nSurname: {surname}\nAge: {age}</b>".format(name=data['name'], surname=data['surname'], age=message.text), parse_mode="html")
59-
await bot.delete_state(message.from_user.id)
75+
await bot.delete_state(message.from_user.id, message.chat.id)
6076

6177
#incorrect number
6278
@bot.message_handler(state=MyStates.age, is_digit=False)
6379
async def age_incorrect(message):
80+
"""
81+
Will process for wrong input when state is MyState.age
82+
"""
6483
await bot.send_message(message.chat.id, 'Looks like you are submitting a string in the field age. Please enter a number')
6584

6685
# register filters
6786

6887
bot.add_custom_filter(asyncio_filters.StateFilter(bot))
6988
bot.add_custom_filter(asyncio_filters.IsDigitFilter())
7089

71-
# set saving states into file.
72-
bot.enable_saving_states() # you can delete this if you do not need to save states
7390

7491
import asyncio
7592
asyncio.run(bot.polling())

‎examples/custom_states.py‎

Lines changed: 48 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,39 @@
1-
import telebot
1+
import telebot # telebot
22

33
from telebot import custom_filters
4+
from telebot.handler_backends import State, StatesGroup #States
45

5-
bot = telebot.TeleBot("")
6+
# States storage
7+
from telebot.storage import StateRedisStorage, StatePickleStorage, StateMemoryStorage
68

79

8-
class MyStates:
9-
name = 1
10-
surname = 2
11-
age = 3
10+
# Beginning from version 4.4.0+, we support storages.
11+
# StateRedisStorage -> Redis-based storage.
12+
# StatePickleStorage -> Pickle-based storage.
13+
# For redis, you will need to install redis.
14+
# Pass host, db, password, or anything else,
15+
# if you need to change config for redis.
16+
# Pickle requires path. Default path is in folder .state-saves.
17+
# If you were using older version of pytba for pickle,
18+
# you need to migrate from old pickle to new by using
19+
# StatePickleStorage().convert_old_to_new()
20+
21+
22+
23+
# Now, you can pass storage to bot.
24+
state_storage = StateMemoryStorage() # you can init here another storage
25+
26+
bot = telebot.TeleBot("TOKEN",
27+
state_storage=state_storage)
28+
29+
30+
# States group.
31+
class MyStates(StatesGroup):
32+
# Just name variables differently
33+
name = State() # creating instances of State class is enough from now
34+
surname = State()
35+
age = State()
36+
1237

1338

1439

@@ -17,58 +42,61 @@ def start_ex(message):
1742
"""
1843
Start command. Here we are starting state
1944
"""
20-
bot.set_state(message.from_user.id, MyStates.name)
45+
bot.set_state(message.from_user.id, MyStates.name, message.chat.id)
2146
bot.send_message(message.chat.id, 'Hi, write me a name')
2247

2348

24-
49+
# Any state
2550
@bot.message_handler(state="*", commands='cancel')
2651
def any_state(message):
2752
"""
2853
Cancel state
2954
"""
3055
bot.send_message(message.chat.id, "Your state was cancelled.")
31-
bot.delete_state(message.from_user.id)
56+
bot.delete_state(message.from_user.id, message.chat.id)
3257

3358
@bot.message_handler(state=MyStates.name)
3459
def name_get(message):
3560
"""
36-
State 1. Will process when user's state is 1.
61+
State 1. Will process when user's state is MyStates.name.
3762
"""
3863
bot.send_message(message.chat.id, f'Now write me a surname')
39-
bot.set_state(message.from_user.id, MyStates.surname)
40-
with bot.retrieve_data(message.from_user.id) as data:
64+
bot.set_state(message.from_user.id, MyStates.surname, message.chat.id)
65+
with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
4166
data['name'] = message.text
4267

4368

4469
@bot.message_handler(state=MyStates.surname)
4570
def ask_age(message):
4671
"""
47-
State 2. Will process when user's state is 2.
72+
State 2. Will process when user's state is MyStates.surname.
4873
"""
4974
bot.send_message(message.chat.id, "What is your age?")
50-
bot.set_state(message.from_user.id, MyStates.age)
51-
with bot.retrieve_data(message.from_user.id) as data:
75+
bot.set_state(message.from_user.id, MyStates.age, message.chat.id)
76+
with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
5277
data['surname'] = message.text
5378

5479
# result
5580
@bot.message_handler(state=MyStates.age, is_digit=True)
5681
def ready_for_answer(message):
57-
with bot.retrieve_data(message.from_user.id) as data:
82+
"""
83+
State 3. Will process when user's state is MyStates.age.
84+
"""
85+
with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
5886
bot.send_message(message.chat.id, "Ready, take a look:\n<b>Name: {name}\nSurname: {surname}\nAge: {age}</b>".format(name=data['name'], surname=data['surname'], age=message.text), parse_mode="html")
59-
bot.delete_state(message.from_user.id)
87+
bot.delete_state(message.from_user.id, message.chat.id)
6088

6189
#incorrect number
6290
@bot.message_handler(state=MyStates.age, is_digit=False)
6391
def age_incorrect(message):
92+
"""
93+
Wrong response for MyStates.age
94+
"""
6495
bot.send_message(message.chat.id, 'Looks like you are submitting a string in the field age. Please enter a number')
6596

6697
# register filters
6798

6899
bot.add_custom_filter(custom_filters.StateFilter(bot))
69100
bot.add_custom_filter(custom_filters.IsDigitFilter())
70101

71-
# set saving states into file.
72-
bot.enable_saving_states() # you can delete this if you do not need to save states
73-
74102
bot.infinity_polling(skip_pending=True)

0 commit comments

Comments
 (0)