Skip to content

Commit b292b27

Browse files
Create basic_example.py
1 parent 403028b commit b292b27

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from telebot import TeleBot
2+
from telebot.handler_backends import BaseMiddleware
3+
4+
bot = TeleBot('TOKEN', use_class_middlewares=True) # set use_class_middlewares to True!
5+
# otherwise, class-based middlewares won't execute.
6+
7+
# You can use this classes for cancelling update or skipping handler:
8+
# from telebot.handler_backends import CancelUpdate, SkipHandler
9+
10+
class Middleware(BaseMiddleware):
11+
def __init__(self):
12+
self.update_types = ['message']
13+
def pre_process(self, message, data):
14+
data['foo'] = 'Hello' # just for example
15+
# we edited the data. now, this data is passed to handler.
16+
# return SkipHandler() -> this will skip handler
17+
# return CancelUpdate() -> this will cancel update
18+
def post_process(self, message, data, exception=None):
19+
print(data['foo'])
20+
if exception: # check for exception
21+
print(exception)
22+
23+
@bot.message_handler(commands=['start'])
24+
def start(message, data: dict): # you don't have to put data parameter in handler if you don't need it.
25+
bot.send_message(message.chat.id, data['foo'])
26+
data['foo'] = 'Processed' # we changed value of data.. this data is now passed to post_process.
27+
28+
29+
# Setup middleware
30+
bot.setup_middleware(Middleware())
31+
32+
bot.infinity_polling()

0 commit comments

Comments
 (0)