@@ -17,58 +17,37 @@ _Package is in preview state and theses are all in preview and may change later.
17
17
See [ Wiki] ( https://github.com/python-telegrambots/custom-telegrambots/wiki/ ) for more working examples.
18
18
19
19
``` py
20
- import asyncio
21
-
22
- from telegrambots.custom import TelegramBot, Dispatcher
23
- from telegrambots.custom.contexts import MessageContext
24
-
25
20
from telegrambots.custom import (
21
+ TelegramBot,
22
+ MessageContext,
26
23
message_filters as mf,
27
24
) # -> filters for each update type are in separate modules.
28
25
29
- # you can easily add new filters by importing them and adding them to the list.
30
26
31
27
# Create main bot object, this object may contains all available api methods.
32
28
bot = TelegramBot(" BOT_TOKEN" )
33
29
34
-
35
- # A function to handle errors inside handlers.
36
- async def handle_error (_ : TelegramBot, e : Exception ):
37
- print (e)
38
-
39
-
40
30
# Dispatcher is to process updates and dispatches them to handlers.
41
- dp = Dispatcher(
42
- bot, handle_error
43
- ) # By default, the dispatcher will process updates sequentially .
31
+ dp = bot.dispatcher # By default, the dispatcher will process updates sequentially.
32
+
33
+ dp.add_default_exception_handler( ) # Simple err handler that prints error message .
44
34
45
35
46
36
# Use decorator to register handler for each update type.
47
37
# You can use filters and combine them.
48
- @dp.add.handlers.via_decorator.message (mf.regex (" ^/start" ) & mf.private)
38
+ @dp.add.handlers.via_decorator.message (mf.Regex (" ^/start" ) & mf.private)
49
39
async def handle_message (
50
40
context : MessageContext,
51
41
): # -> async callback function to handle update
52
42
await context.reply_text(
53
43
" Started"
54
44
) # -> bound method for messages, only available in `MessageContext`
55
- await asyncio.sleep(5 )
56
- await context.reply_text(" Done" )
57
-
58
-
59
- async def main ():
60
- me = await bot.get_me()
61
- print (me.pretty_str()) # let's know who we are.
62
-
63
- print (" Streaming updates ..." )
64
- # For now you should fetch updates manually and feed them to dispatcher.
65
- async for update in bot.stream_updates([" message" ]):
66
- await dp.feed_update(update)
67
45
68
46
69
47
if __name__ == " __main__" :
70
48
# Fire up the event loop.
71
- asyncio.run(main())
49
+ dp.unlimited()
50
+
72
51
```
73
52
74
53
### Process updates in parallel
@@ -85,7 +64,6 @@ from src.telegrambots.custom.processor import ParallelProcessor
85
64
# Dispatcher is to process updates and dispatches them to handlers.
86
65
dp = Dispatcher(
87
66
bot,
88
- handle_error = handle_error,
89
67
processor_type = ParallelProcessor, # Now the dispatcher will use ParallelProcessor.
90
68
# And it will process updates in parallel.
91
69
)
@@ -132,12 +110,15 @@ class AdvancedMessageFilter(Filter[Message]):
132
110
133
111
def __check__ (self , update : Optional[Message]) -> bool :
134
112
# ---- check if update is a valid for your case ----
113
+ self ._set_metadata(" balh" , " Ablah" )
135
114
return True
136
115
137
116
# ---- or anything you like ----
138
117
139
118
# @dp.add.handlers.via_decorator.message(AdvancedMessageFilter())
140
- # ...
119
+ # ---- sniff ----
120
+
121
+ context[" balh" ] # Ablah
141
122
```
142
123
143
124
#### Using factories ( Fast, Low options )
@@ -215,7 +196,7 @@ So you need a way to keep track of a user, right?
215
196
216
197
Here's where this package mages!!
217
198
218
- You can use ` @context.continue_with_this_message ` decorator inside your handler.
199
+ You can use ` @context.continue_with.this.message ` decorator inside your handler.
219
200
220
201
It's much likely similar to ` @dp.register_message_handler ` , except it takes one more parameter before filter. And it's a ` keys ` .
221
202
@@ -272,8 +253,8 @@ async def handle_message(
272
253
if context.update.from_user:
273
254
274
255
# Again
275
- @context.continue_with.this.message (
276
- keys = [MessageSenderId(context.update.from_user.id)],
256
+ @context.continue_with.this.message_from ( # same as keys=[MessageSenderId(context.update from_user.id)],
257
+
277
258
filter = mf.text_message & mf.private,
278
259
tag = " give_age" , # Another name, it's important!
279
260
name = context.update.text, # -> you can pass custom data to handler. they're available in callback's *args or **kwargs.
@@ -369,6 +350,8 @@ Let's modify unrelated method.
369
350
``` py
370
351
@dp.add.handlers.via_decorator.message (
371
352
filter = mf.any_message, continue_after = [" handle_message" , " unrelated" ] # notice we added this methods name to `continue_after`, so it can be continued with after itself ( user sends multiple unrelated updates in a row )
353
+
354
+ # You can use allow_continue_after_self = True, which dose the same.
372
355
)
373
356
async def unrelated (context : MessageContext):
374
357
await context.reply_text(" Please try again with a text message." )
@@ -397,28 +380,18 @@ now everything is ready! fast and clear.
397
380
Let see full example
398
381
399
382
``` py
400
- import asyncio
401
- from typing import Any
402
- import logging
403
- import sys
404
-
405
- from telegrambots.custom import TelegramBot, Dispatcher
406
- from telegrambots.custom.contexts import MessageContext
407
- from telegrambots.custom import message_filters as mf
408
- from telegrambots.custom.processor import ParallelProcessor
409
- from telegrambots.custom.key_resolvers import MessageSenderId
410
- from telegrambots.custom.contexts import ContinueWithInfo
383
+ from telegrambots.custom import (
384
+ TelegramBot,
385
+ message_filters as mf,
386
+ ContinueWithInfo,
387
+ MessageContext,
388
+ )
411
389
412
390
413
391
bot = TelegramBot(" BOT_TOKEN" )
392
+ dp = bot.dispatcher
414
393
415
-
416
- # A function to handle errors inside handlers.
417
- async def handle_error (_ : TelegramBot, e : Exception ):
418
- print (e)
419
-
420
-
421
- dp = Dispatcher(bot, handle_error = handle_error)
394
+ dp.add_default_exception_handler()
422
395
423
396
424
397
@dp.add.handlers.via_decorator.message (
@@ -430,43 +403,35 @@ async def give_name(context: MessageContext):
430
403
431
404
432
405
@dp.add.handlers.via_decorator.message (
433
- filter = mf.any_message & mf.private, continue_after = [" handle_message" , " unrelated" ]
406
+ filter = mf.any_message & mf.private,
407
+ continue_after = [" handle_message" ],
408
+ allow_continue_after_self = True ,
434
409
)
435
410
async def unrelated (context : MessageContext):
436
411
await context.reply_text(" Please try again with a text message." )
412
+
437
413
if context.update.from_user:
438
- keys = [MessageSenderId( context.update.from_user.id)]
414
+ user_id = context.update.from_user.id
439
415
context.continue_with.many(
440
- ContinueWithInfo.with_message (" give_name" , keys , priority = 1 ),
441
- ContinueWithInfo.with_message (" unrelated" , keys , priority = 0 ),
416
+ ContinueWithInfo.with_message_from (" give_name" , user_id , priority = 1 ),
417
+ ContinueWithInfo.with_message_from (" unrelated" , user_id , priority = 0 ),
442
418
)
443
419
444
420
445
- @dp.add.handlers.via_decorator.message (mf.regex (" ^/start" ) & mf.private)
421
+ @dp.add.handlers.via_decorator.message (mf.Regex (" ^/start" ) & mf.private)
446
422
async def handle_message (context : MessageContext):
447
423
await context.reply_text(" Please gimme you name ..." )
448
424
449
425
if context.update.from_user:
450
- keys = [MessageSenderId( context.update.from_user.id)]
426
+ user_id = context.update.from_user.id
451
427
context.continue_with.many(
452
- ContinueWithInfo.with_message (" give_name" , keys , priority = 1 ),
453
- ContinueWithInfo.with_message (" unrelated" , keys , priority = 0 ),
428
+ ContinueWithInfo.with_message_from (" give_name" , user_id , priority = 1 ),
429
+ ContinueWithInfo.with_message_from (" unrelated" , user_id , priority = 0 ),
454
430
)
455
431
456
432
457
- async def main ():
458
- me = await bot.get_me()
459
- print (me.pretty_str()) # let's know who we are.
460
-
461
- print (" Streaming updates ..." )
462
- # For now you should fetch updates manually and feed them to dispatcher.
463
- async for update in bot.stream_updates([" message" , " callback_query" ]):
464
- await dp.feed_update(update)
465
-
466
-
467
433
if __name__ == " __main__" :
468
- # Fire up the event loop.
469
- asyncio.run(main())
434
+ dp.unlimited()
470
435
471
436
```
472
437
0 commit comments