python-vk-bot 0.3.0__py3-none-any.whl → 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
python_vk_bot/__init__.py CHANGED
@@ -5,7 +5,15 @@ from .application import Application
5
5
  from .bot import Bot
6
6
  from .callback import Callback
7
7
  from .context import Context
8
- from .handlers import CommandHandler, Handler, MessageEventHandler, MessageHandler
8
+ from .errors import ApplicationHandlerStop
9
+ from .handlers import (
10
+ CommandHandler,
11
+ DonutSubscriptionHandler,
12
+ Handler,
13
+ MessageEventHandler,
14
+ MessageHandler,
15
+ TypeHandler,
16
+ )
9
17
  from .long_poll import LongPoll
10
18
  from .models import (
11
19
  Attachment,
@@ -14,6 +22,8 @@ from .models import (
14
22
  ButtonType,
15
23
  CallbackButton,
16
24
  DocumentAttachment,
25
+ DonutSubscriptionEvent,
26
+ DonutSubscriptionEventType,
17
27
  Keyboard,
18
28
  Message,
19
29
  MessageEvent,
@@ -23,10 +33,12 @@ from .models import (
23
33
  User,
24
34
  VideoAttachment,
25
35
  )
36
+ from .queues import UpdateQueue
26
37
  from .settings import BotSettings
27
38
 
28
39
  __all__ = [
29
40
  "Application",
41
+ "ApplicationHandlerStop",
30
42
  "Attachment",
31
43
  "AudioMessageAttachment",
32
44
  "Bot",
@@ -38,6 +50,9 @@ __all__ = [
38
50
  "CommandHandler",
39
51
  "Context",
40
52
  "DocumentAttachment",
53
+ "DonutSubscriptionEvent",
54
+ "DonutSubscriptionEventType",
55
+ "DonutSubscriptionHandler",
41
56
  "Handler",
42
57
  "Keyboard",
43
58
  "LongPoll",
@@ -47,7 +62,9 @@ __all__ = [
47
62
  "MessageHandler",
48
63
  "PhotoAttachment",
49
64
  "TextButton",
65
+ "TypeHandler",
50
66
  "Update",
67
+ "UpdateQueue",
51
68
  "User",
52
69
  "VideoAttachment",
53
70
  "filters",
@@ -1,19 +1,20 @@
1
- """Serial dispatch with explicit lifecycle and bounded duplicate suppression."""
1
+ """Serial queued dispatch, managed tasks, and explicit resource ownership."""
2
2
 
3
3
  import asyncio
4
4
  import logging
5
5
  from collections import OrderedDict
6
- from collections.abc import Awaitable, Callable
7
- from contextlib import aclosing
6
+ from collections.abc import Awaitable, Callable, Coroutine
7
+ from contextlib import aclosing, suppress
8
8
  from types import TracebackType
9
9
  from typing import Self
10
10
 
11
11
  from .bot import Bot
12
12
  from .context import Context
13
- from .errors import LifecycleError
14
- from .handlers import Handler
13
+ from .errors import ApplicationHandlerStop, LifecycleError
14
+ from .handlers import Handler, TypeHandler, _DispatchHandler
15
15
  from .long_poll import LongPoll
16
16
  from .models import Update
17
+ from .queues import UpdateQueue, _QueueItem
17
18
 
18
19
  type ErrorCallback = Callable[[Update | None, Context], Awaitable[None]]
19
20
  type LifecycleHook = Callable[[Application], Awaitable[None]]
@@ -21,6 +22,23 @@ type LifecycleHook = Callable[[Application], Awaitable[None]]
21
22
  logger = logging.getLogger(__name__)
22
23
 
23
24
 
25
+ async def _await_owned[T](task: asyncio.Future[T]) -> T:
26
+ """Finish owned cleanup even on repeated caller cancellation, then propagate it."""
27
+ interrupted = False
28
+ while not task.done():
29
+ try:
30
+ await asyncio.shield(task)
31
+ except asyncio.CancelledError:
32
+ interrupted = True
33
+ except BaseException:
34
+ break
35
+ if interrupted:
36
+ if not task.cancelled():
37
+ task.exception()
38
+ raise asyncio.CancelledError
39
+ return task.result()
40
+
41
+
24
42
  class Application:
25
43
  def __init__(
26
44
  self,
@@ -28,7 +46,9 @@ class Application:
28
46
  group_id: int,
29
47
  *,
30
48
  deduplication_size: int = 4096,
49
+ update_queue_size: int = 256,
31
50
  post_init: LifecycleHook | None = None,
51
+ post_stop: LifecycleHook | None = None,
32
52
  post_shutdown: LifecycleHook | None = None,
33
53
  ) -> None:
34
54
  if group_id <= 0 or deduplication_size < 0:
@@ -38,80 +58,200 @@ class Application:
38
58
  self.bot_data: dict[str, object] = {}
39
59
  self.user_data: dict[int, dict[str, object]] = {}
40
60
  self.peer_data: dict[int, dict[str, object]] = {}
41
- self._handlers: dict[int, list[Handler]] = {}
61
+ self._handlers: dict[int, list[_DispatchHandler]] = {}
42
62
  self._error_handlers: list[ErrorCallback] = []
43
63
  self._seen: OrderedDict[str, None] = OrderedDict()
44
64
  self._deduplication_size = deduplication_size
45
65
  self._post_init = post_init
66
+ self._post_stop = post_stop
46
67
  self._post_shutdown = post_shutdown
47
- self._dispatch_lock = asyncio.Lock()
48
68
  self._lifecycle_lock = asyncio.Lock()
49
69
  self._initialized = False
50
70
  self._context_active = False
51
71
  self._running = False
72
+ self._started = False
73
+ self._queue_open = False
74
+ self._post_stop_pending = False
75
+ self._update_queue = UpdateQueue(self, update_queue_size)
76
+ self._tasks: dict[asyncio.Task[object], bool] = {}
52
77
  self._polling_task: asyncio.Task[None] | None = None
53
- self._processing_task: asyncio.Task[object] | None = None
78
+ self._polling_waiting = False
79
+ self._polling_cancel_requested = False
80
+ self._consumer_task: asyncio.Task[None] | None = None
81
+ self._processing_task: asyncio.Task[bool] | None = None
82
+ self._finishing_handler: asyncio.Task[bool] | None = None
83
+ self._hook_task: asyncio.Task[object] | None = None
84
+ self._stop_task: asyncio.Task[None] | None = None
85
+ self._shutdown_task: asyncio.Task[None] | None = None
54
86
 
55
87
  @property
56
88
  def running(self) -> bool:
57
89
  return self._running
58
90
 
59
- def add_handler(self, handler: Handler, *, group: int = 0) -> None:
60
- if self._running:
91
+ @property
92
+ def update_queue(self) -> UpdateQueue:
93
+ """The current run's producer interface; only Application consumes events."""
94
+ return self._update_queue
95
+
96
+ def _check_lifecycle(self, *, stopping: bool = False) -> None:
97
+ current = asyncio.current_task()
98
+ if current is self._hook_task:
99
+ raise LifecycleError("Lifecycle hooks cannot recursively invoke lifecycle methods")
100
+ if not stopping and (current is self._processing_task or current in self._tasks):
101
+ raise LifecycleError(
102
+ "Use stop() inside a handler or task; shutdown belongs to the owner"
103
+ )
104
+
105
+ def add_handler[T](self, handler: Handler | TypeHandler[T], *, group: int = 0) -> None:
106
+ if self._started:
61
107
  raise LifecycleError("Register handlers before starting the application")
62
108
  self._handlers.setdefault(group, []).append(handler)
63
109
 
64
110
  def add_error_handler(self, callback: ErrorCallback) -> None:
65
- if self._running:
111
+ if self._started:
66
112
  raise LifecycleError("Register error handlers before starting the application")
67
113
  self._error_handlers.append(callback)
68
114
 
115
+ async def _call_hook(self, hook: LifecycleHook | None) -> None:
116
+ if hook is None:
117
+ return
118
+ self._hook_task = asyncio.current_task()
119
+ try:
120
+ await hook(self)
121
+ finally:
122
+ self._hook_task = None
123
+
69
124
  async def initialize(self) -> None:
125
+ self._check_lifecycle()
126
+ if self._shutdown_task is not None and not self._shutdown_task.done():
127
+ raise LifecycleError("Application shutdown is in progress")
128
+ self._shutdown_task = None
70
129
  async with self._lifecycle_lock:
71
130
  if self._initialized:
72
131
  return
73
132
  try:
74
133
  await self.bot.initialize()
75
- if self._post_init is not None:
76
- await self._post_init(self)
134
+ await self._call_hook(self._post_init)
77
135
  except BaseException:
78
- await self.bot.shutdown()
136
+ cleanup = asyncio.create_task(self.bot.shutdown(), name="vk-startup-cleanup")
137
+ try:
138
+ await _await_owned(cleanup)
139
+ except BaseException as error:
140
+ logger.error("Startup cleanup failed (%s)", type(error).__name__)
79
141
  raise
80
142
  self._initialized = True
81
143
 
82
144
  async def start(self) -> None:
145
+ self._check_lifecycle()
83
146
  if not self._initialized:
84
147
  raise LifecycleError("Initialize the application before starting it")
148
+ if self._shutdown_task is not None:
149
+ raise LifecycleError("Application shutdown is in progress")
150
+ if self._running:
151
+ return
152
+ if self._started:
153
+ raise LifecycleError("Shut down and initialize before starting another run")
154
+ if self._update_queue._closed:
155
+ self._update_queue = UpdateQueue(self, self._update_queue.maxsize)
156
+ self._stop_task = None
157
+ self._finishing_handler = None
158
+ self._queue_open = True
85
159
  self._running = True
160
+ self._started = True
161
+ self._post_stop_pending = True
162
+ self._consumer_task = asyncio.create_task(self._consume(), name="vk-update-consumer")
86
163
 
87
164
  async def stop(self) -> None:
88
- """Stop intake, cancel owned polling, and wait for active dispatch to finish.
165
+ """Stop intake and drain accepted work. Does not invoke post_stop or close Bot.
89
166
 
90
- A handler may call stop: its current dispatch completes before polling exits.
167
+ Inside a handler or managed task this requests stopping without awaiting
168
+ that same task. An external owner can await stop/shutdown for completion.
91
169
  """
92
- self._running = False
93
- task = self._polling_task
170
+ self._check_lifecycle(stopping=True)
171
+ if not self._started:
172
+ return
173
+ if self._stop_task is None:
174
+ self._running = False
175
+ self._finishing_handler = self._processing_task
176
+ self._update_queue._space.set()
177
+ self._stop_task = asyncio.create_task(self._stop(), name="vk-application-stop")
94
178
  current = asyncio.current_task()
95
- if task is not None and task is not current:
96
- task.cancel()
97
- await asyncio.gather(task, return_exceptions=True)
98
- if self._processing_task is not current:
99
- async with self._dispatch_lock:
100
- pass
179
+ if current is self._processing_task or current in self._tasks:
180
+ return
181
+ await _await_owned(self._stop_task)
182
+
183
+ async def _stop(self) -> None:
184
+ # Polling awaiting a receipt must finish it; cancelling it would cancel
185
+ # the active handler. Only interrupt polling that is acquiring updates.
186
+ polling = self._polling_task
187
+ if polling is not None:
188
+ if not self._polling_waiting:
189
+ self._cancel_polling(polling)
190
+ await asyncio.gather(polling, return_exceptions=True)
191
+ if self._finishing_handler is not None:
192
+ await asyncio.gather(self._finishing_handler, return_exceptions=True)
193
+ tasks = tuple(self._tasks)
194
+ for task in tasks:
195
+ if self._tasks.get(task):
196
+ task.cancel()
197
+ if tasks:
198
+ await asyncio.gather(*tasks, return_exceptions=True)
199
+ self._queue_open = False
200
+ self._update_queue._close()
201
+ if self._consumer_task is not None:
202
+ await self._consumer_task
203
+ self._finishing_handler = None
101
204
 
102
205
  async def shutdown(self) -> None:
103
- if self._processing_task is asyncio.current_task():
104
- raise LifecycleError("Use stop() inside a handler; shutdown belongs to the owner")
105
- await self.stop()
206
+ """Drain, invoke post_stop once, close Bot, then invoke post_shutdown."""
207
+ self._check_lifecycle()
208
+ if self._shutdown_task is None:
209
+ self._shutdown_task = asyncio.create_task(
210
+ self._shutdown(), name="vk-application-shutdown"
211
+ )
212
+ await _await_owned(self._shutdown_task)
213
+
214
+ async def _shutdown(self) -> None:
215
+ # Wait for initialization, but never retain this lock while waiting for
216
+ # handlers/tasks: their lifecycle requests are rejected or request stop.
106
217
  async with self._lifecycle_lock:
107
- if not self._initialized:
108
- return
218
+ initialized = self._initialized
219
+ if not initialized:
220
+ return
221
+ failure: BaseException | None = None
222
+ try:
223
+ await self.stop()
224
+ except BaseException as error:
225
+ failure = error
226
+ if self._post_stop_pending:
227
+ self._post_stop_pending = False
109
228
  try:
110
- await self.bot.shutdown()
111
- finally:
112
- self._initialized = False
113
- if self._post_shutdown is not None:
114
- await self._post_shutdown(self)
229
+ await self._call_hook(self._post_stop)
230
+ except BaseException as error:
231
+ if failure is None:
232
+ failure = error
233
+ else:
234
+ logger.error("Post-stop hook failed (%s)", type(error).__name__)
235
+ try:
236
+ await self.bot.shutdown()
237
+ except BaseException as error:
238
+ if failure is None:
239
+ failure = error
240
+ else:
241
+ logger.error("Bot shutdown failed (%s)", type(error).__name__)
242
+ finally:
243
+ self._initialized = False
244
+ try:
245
+ await self._call_hook(self._post_shutdown)
246
+ except BaseException as error:
247
+ if failure is None:
248
+ failure = error
249
+ else:
250
+ logger.error("Post-shutdown hook failed (%s)", type(error).__name__)
251
+ finally:
252
+ self._started = False
253
+ if failure is not None:
254
+ raise failure
115
255
 
116
256
  async def __aenter__(self) -> Self:
117
257
  if self._initialized or self._context_active:
@@ -121,7 +261,12 @@ class Application:
121
261
  await self.initialize()
122
262
  await self.start()
123
263
  except BaseException:
124
- self._context_active = False
264
+ try:
265
+ await self.shutdown()
266
+ except BaseException as error:
267
+ logger.error("Application startup cleanup failed (%s)", type(error).__name__)
268
+ finally:
269
+ self._context_active = False
125
270
  raise
126
271
  return self
127
272
 
@@ -133,12 +278,32 @@ class Application:
133
278
  ) -> None:
134
279
  try:
135
280
  await self.shutdown()
281
+ except BaseException as error:
282
+ if exc is None:
283
+ raise
284
+ logger.error("Application cleanup failed (%s)", type(error).__name__)
136
285
  finally:
137
286
  self._context_active = False
138
287
 
139
- def _context(self, update: Update | None, error: Exception | None = None) -> Context:
140
- user_id = update.user_id if update is not None else None
141
- peer_id = update.peer_id if update is not None else None
288
+ def _check_enqueue(self, queue: UpdateQueue, item: _QueueItem) -> None:
289
+ current = asyncio.current_task()
290
+ finishing = current is self._finishing_handler or current in self._tasks
291
+ if (
292
+ queue is not self._update_queue
293
+ or not self._queue_open
294
+ or not (self._running or finishing)
295
+ ):
296
+ raise LifecycleError("Application is not running or accepting events")
297
+ if isinstance(item.event, Update):
298
+ if item.event.group_id != self.group_id:
299
+ raise ValueError("Update belongs to another community")
300
+ if item.user_id is not None or item.peer_id is not None:
301
+ raise ValueError("VK update state scopes are supplied by the update")
302
+
303
+ def _context(self, item: _QueueItem, error: Exception | None = None) -> Context:
304
+ event = item.event
305
+ user_id = event.user_id if isinstance(event, Update) else item.user_id
306
+ peer_id = event.peer_id if isinstance(event, Update) else item.peer_id
142
307
  return Context(
143
308
  application=self,
144
309
  bot=self.bot,
@@ -146,76 +311,191 @@ class Application:
146
311
  peer_data=self.peer_data.setdefault(peer_id, {}) if peer_id is not None else {},
147
312
  bot_data=self.bot_data,
148
313
  error=error,
314
+ event=event,
149
315
  )
150
316
 
151
- async def _report_error(self, update: Update | None, error: Exception) -> None:
152
- context = self._context(update, error)
153
- logger.error("Update processing failed (%s)", type(error).__name__)
317
+ async def _report_error(self, item: _QueueItem, error: Exception) -> None:
318
+ context = self._context(item, error)
319
+ update = item.event if isinstance(item.event, Update) else None
320
+ logger.error("Event processing failed (%s)", type(error).__name__)
154
321
  for callback in self._error_handlers:
155
322
  try:
156
323
  await callback(update, context)
324
+ except ApplicationHandlerStop:
325
+ break
157
326
  except Exception as callback_error:
158
327
  logger.error("Error handler failed (%s)", type(callback_error).__name__)
159
328
 
160
- async def process_update(self, update: Update) -> bool:
161
- """Return False for a duplicate, True after dispatch; propagate handler errors."""
329
+ async def process_update(
330
+ self, update: object, *, user_id: int | None = None, peer_id: int | None = None
331
+ ) -> bool:
332
+ """Queue and await dispatch; False for a duplicate, otherwise True.
333
+
334
+ Cancellation skips queued work or cancels/awaits the active handler.
335
+ Internal objects can explicitly select user/peer state scopes.
336
+ """
162
337
  if self._processing_task is asyncio.current_task():
163
338
  raise LifecycleError("Recursive update dispatch is not supported")
164
- async with self._dispatch_lock:
165
- if not self._running:
166
- raise LifecycleError("Application is not running")
167
- if update.group_id != self.group_id:
339
+ return await self._submit(_QueueItem(update, user_id, peer_id))
340
+
341
+ async def _submit(self, item: _QueueItem) -> bool:
342
+ receipt = asyncio.get_running_loop().create_future()
343
+ item.receipt = receipt
344
+ try:
345
+ await self._update_queue._put(item)
346
+ return await asyncio.shield(receipt)
347
+ except asyncio.CancelledError:
348
+ item.cancelled = True
349
+ if receipt.done() and not receipt.cancelled():
350
+ receipt.exception()
351
+ receipt.cancel()
352
+ if item.task is not None and not item.task.done():
353
+ item.task.cancel()
354
+ with suppress(BaseException):
355
+ await _await_owned(item.task)
356
+ raise
357
+
358
+ async def _consume(self) -> None:
359
+ while True:
360
+ try:
361
+ item = await self._update_queue._get()
362
+ except asyncio.QueueShutDown:
363
+ return
364
+ try:
365
+ if item.cancelled:
366
+ continue
367
+ task = asyncio.create_task(self._dispatch(item), name="vk-event-dispatch")
368
+ item.task = task
369
+ self._processing_task = task
370
+ try:
371
+ result = await task
372
+ except asyncio.CancelledError:
373
+ if item.receipt is not None and not item.receipt.done():
374
+ item.receipt.cancel()
375
+ current = asyncio.current_task()
376
+ if current is not None and current.cancelling():
377
+ raise
378
+ except Exception as error:
379
+ if item.receipt is not None and not item.receipt.done():
380
+ item.receipt.set_exception(error)
381
+ else:
382
+ if item.receipt is not None and not item.receipt.done():
383
+ item.receipt.set_result(result)
384
+ finally:
385
+ self._processing_task = None
386
+ finally:
387
+ self._update_queue._queue.task_done()
388
+
389
+ async def _dispatch(self, item: _QueueItem) -> bool:
390
+ if item.error is not None:
391
+ await self._report_error(item, item.error)
392
+ return True
393
+ event = item.event
394
+ if isinstance(event, Update):
395
+ if event.group_id != self.group_id:
168
396
  raise ValueError("Update belongs to another community")
169
- if update.event_id in self._seen:
397
+ if event.event_id in self._seen:
170
398
  return False
171
- self._processing_task = asyncio.current_task()
399
+ try:
400
+ context = self._context(item)
401
+ for group in sorted(self._handlers):
402
+ for handler in self._handlers[group]:
403
+ if await handler._dispatch(event, context):
404
+ break
405
+ except ApplicationHandlerStop:
406
+ pass
407
+ except Exception as error:
408
+ await self._report_error(item, error)
409
+ raise
410
+ if isinstance(event, Update) and self._deduplication_size:
411
+ self._seen[event.event_id] = None
412
+ if len(self._seen) > self._deduplication_size:
413
+ self._seen.popitem(last=False)
414
+ return True
415
+
416
+ def create_task[T](
417
+ self,
418
+ coroutine: Coroutine[object, object, T],
419
+ *,
420
+ update: object = None,
421
+ name: str | None = None,
422
+ cancel_on_stop: bool = False,
423
+ ) -> asyncio.Task[T]:
424
+ """Own a running coroutine, report failures serially, and await it on stop.
425
+
426
+ Use cancel_on_stop for long-lived workers. Tasks must not directly mutate
427
+ Context state or be awaited by a handler if they depend on the consumer.
428
+ """
429
+ if not self._running:
430
+ coroutine.close()
431
+ raise LifecycleError("Create tasks only while the application is running")
432
+ if isinstance(update, Update) and update.group_id != self.group_id:
433
+ coroutine.close()
434
+ raise ValueError("Update belongs to another community")
435
+
436
+ async def run() -> T:
172
437
  try:
173
- context = self._context(update)
174
- for group in sorted(self._handlers):
175
- for handler in self._handlers[group]:
176
- if handler.check_update(update):
177
- await handler.handle_update(update, context)
178
- break
438
+ return await coroutine
179
439
  except Exception as error:
180
- await self._report_error(update, error)
440
+ try:
441
+ await self._submit(_QueueItem(update, error=error))
442
+ except Exception as reporting_error:
443
+ logger.error("Task error reporting failed (%s)", type(reporting_error).__name__)
181
444
  raise
182
- finally:
183
- self._processing_task = None
184
- if self._deduplication_size:
185
- self._seen[update.event_id] = None
186
- if len(self._seen) > self._deduplication_size:
187
- self._seen.popitem(last=False)
188
- return True
445
+
446
+ task = asyncio.create_task(run(), name=name)
447
+ self._tasks[task] = cancel_on_stop
448
+
449
+ def finished(done: asyncio.Task[T]) -> None:
450
+ self._tasks.pop(done, None)
451
+ # Also close a coroutine cancelled before the wrapper's first step.
452
+ coroutine.close()
453
+ if not done.cancelled():
454
+ done.exception()
455
+
456
+ task.add_done_callback(finished)
457
+ return task
189
458
 
190
459
  async def _poll(self, long_poll: LongPoll) -> None:
191
460
  async with aclosing(long_poll.listen()) as updates:
192
461
  async for update in updates:
193
462
  if not self._running:
194
463
  break
464
+ self._polling_waiting = True
195
465
  try:
196
466
  await self.process_update(update)
197
467
  except Exception:
198
- # Dispatch already reported the error; never replay partial side effects.
199
468
  logger.warning("Skipping failed update in polling mode")
469
+ finally:
470
+ self._polling_waiting = False
200
471
  if not self._running:
201
472
  break
202
473
 
474
+ def _cancel_polling(self, task: asyncio.Task[None]) -> None:
475
+ """Request cancellation once; another owner must await the same cleanup."""
476
+ if not self._polling_cancel_requested and not task.done():
477
+ self._polling_cancel_requested = True
478
+ task.cancel()
479
+
203
480
  async def run_polling(self, *, wait: int = 25) -> None:
204
- """Run until stop or cancellation; own startup and shutdown, not the event loop."""
481
+ """Run until stop/cancellation; own lifecycle, not the caller's event loop."""
205
482
  if self._polling_task is not None:
206
483
  raise LifecycleError("Polling is already running")
207
484
  long_poll = LongPoll(self.bot, self.group_id, wait=wait)
208
485
  async with self:
209
486
  task = asyncio.create_task(self._poll(long_poll), name="vk-long-poll")
210
487
  self._polling_task = task
488
+ self._polling_cancel_requested = False
211
489
  try:
212
- await task
213
- except asyncio.CancelledError:
214
- current = asyncio.current_task()
215
- if current is not None and current.cancelling():
216
- raise
490
+ await asyncio.wait({task})
491
+ if not task.cancelled():
492
+ task.result()
217
493
  except Exception as error:
218
- await self._report_error(None, error)
494
+ await self._submit(_QueueItem(None, error=error))
219
495
  raise
220
496
  finally:
221
- self._polling_task = None
497
+ try:
498
+ self._cancel_polling(task)
499
+ await _await_owned(asyncio.gather(task, return_exceptions=True))
500
+ finally:
501
+ self._polling_task = None
python_vk_bot/context.py CHANGED
@@ -17,3 +17,4 @@ class Context:
17
17
  peer_data: dict[str, object]
18
18
  bot_data: dict[str, object]
19
19
  error: Exception | None = field(default=None, repr=False)
20
+ event: object | None = field(default=None, repr=False)
python_vk_bot/errors.py CHANGED
@@ -1,6 +1,10 @@
1
1
  """Safe exceptions: messages never include credentials or server payloads."""
2
2
 
3
3
 
4
+ class ApplicationHandlerStop(Exception):
5
+ """Finish the current event successfully without invoking further handlers."""
6
+
7
+
4
8
  class VKError(Exception):
5
9
  """Base class for library errors."""
6
10
 
python_vk_bot/filters.py CHANGED
@@ -3,7 +3,7 @@
3
3
  import re
4
4
  from collections.abc import Callable
5
5
 
6
- from .models import Update
6
+ from .models import DonutSubscriptionEventType, Update
7
7
 
8
8
 
9
9
  class Filter:
@@ -38,3 +38,20 @@ class Regex(Filter):
38
38
  ALL = Filter(lambda update: True)
39
39
  TEXT = Filter(lambda update: update.message is not None and bool(update.message.text))
40
40
  LOCATION = Filter(lambda update: update.message is not None and update.message.geo is not None)
41
+
42
+ DONUT_SUBSCRIPTION = Filter(lambda update: update.donut_subscription is not None)
43
+ DONUT_SUBSCRIPTION_CREATE = DONUT_SUBSCRIPTION & Filter(
44
+ lambda update: update.type == DonutSubscriptionEventType.CREATE
45
+ )
46
+ DONUT_SUBSCRIPTION_PROLONGED = DONUT_SUBSCRIPTION & Filter(
47
+ lambda update: update.type == DonutSubscriptionEventType.PROLONGED
48
+ )
49
+ DONUT_SUBSCRIPTION_CANCELLED = DONUT_SUBSCRIPTION & Filter(
50
+ lambda update: update.type == DonutSubscriptionEventType.CANCELLED
51
+ )
52
+ DONUT_SUBSCRIPTION_EXPIRED = DONUT_SUBSCRIPTION & Filter(
53
+ lambda update: update.type == DonutSubscriptionEventType.EXPIRED
54
+ )
55
+ DONUT_SUBSCRIPTION_PRICE_CHANGED = DONUT_SUBSCRIPTION & Filter(
56
+ lambda update: update.type == DonutSubscriptionEventType.PRICE_CHANGED
57
+ )
python_vk_bot/handlers.py CHANGED
@@ -1,14 +1,19 @@
1
1
  """Typed handler registration without a conversation-state framework."""
2
2
 
3
- from collections.abc import Awaitable, Callable
3
+ from collections.abc import Awaitable, Callable, Iterable
4
+ from typing import Protocol, TypeGuard
4
5
 
5
6
  from . import filters
6
7
  from .context import Context
7
- from .models import Update
8
+ from .models import DonutSubscriptionEventType, Update
8
9
 
9
10
  type HandlerCallback = Callable[[Update, Context], Awaitable[None]]
10
11
 
11
12
 
13
+ class _DispatchHandler(Protocol):
14
+ async def _dispatch(self, update: object, context: Context) -> bool: ...
15
+
16
+
12
17
  class Handler:
13
18
  def __init__(
14
19
  self, callback: HandlerCallback, *, predicate: filters.Filter = filters.ALL
@@ -22,6 +27,39 @@ class Handler:
22
27
  async def handle_update(self, update: Update, context: Context) -> None:
23
28
  await self.callback(update, context)
24
29
 
30
+ async def _dispatch(self, update: object, context: Context) -> bool:
31
+ if not isinstance(update, Update) or not self.check_update(update):
32
+ return False
33
+ await self.handle_update(update, context)
34
+ return True
35
+
36
+
37
+ class TypeHandler[T]:
38
+ """Route a Python object by type, including validated VK Updates."""
39
+
40
+ def __init__(
41
+ self,
42
+ update_type: type[T],
43
+ callback: Callable[[T, Context], Awaitable[None]],
44
+ *,
45
+ strict: bool = False,
46
+ ) -> None:
47
+ self.type = update_type
48
+ self.callback = callback
49
+ self.strict = strict
50
+
51
+ def check_update(self, update: object) -> TypeGuard[T]:
52
+ return type(update) is self.type if self.strict else isinstance(update, self.type)
53
+
54
+ async def handle_update(self, update: T, context: Context) -> None:
55
+ await self.callback(update, context)
56
+
57
+ async def _dispatch(self, update: object, context: Context) -> bool:
58
+ if not self.check_update(update):
59
+ return False
60
+ await self.handle_update(update, context)
61
+ return True
62
+
25
63
 
26
64
  class MessageHandler(Handler):
27
65
  def __init__(
@@ -43,6 +81,39 @@ class MessageEventHandler(Handler):
43
81
  )
44
82
 
45
83
 
84
+ class DonutSubscriptionHandler(Handler):
85
+ """Handle subscription changes through the ordinary awaited callback pipeline.
86
+
87
+ event_types accepts enum members or their exact VK strings. None selects all
88
+ five events; an empty iterable selects none. Unknown names raise ValueError.
89
+ predicate further restricts the selection. This handler does not synchronize
90
+ subscriptions or decide whether a user has paid access.
91
+ """
92
+
93
+ def __init__(
94
+ self,
95
+ callback: HandlerCallback,
96
+ *,
97
+ event_types: Iterable[DonutSubscriptionEventType | str] | None = None,
98
+ predicate: filters.Filter = filters.ALL,
99
+ ) -> None:
100
+ if isinstance(event_types, str):
101
+ raise TypeError("event_types must be an iterable of event names, not a single string")
102
+ selected = (
103
+ frozenset(DonutSubscriptionEventType)
104
+ if event_types is None
105
+ else frozenset(DonutSubscriptionEventType(value) for value in event_types)
106
+ )
107
+ super().__init__(
108
+ callback,
109
+ predicate=(
110
+ filters.DONUT_SUBSCRIPTION
111
+ & filters.Filter(lambda update: update.type in selected)
112
+ & predicate
113
+ ),
114
+ )
115
+
116
+
46
117
  class CommandHandler(MessageHandler):
47
118
  """Match an explicit /command token; no Telegram mention syntax is inferred."""
48
119
 
@@ -5,6 +5,7 @@ from .attachments import (
5
5
  PhotoAttachment,
6
6
  VideoAttachment,
7
7
  )
8
+ from .donut import DonutSubscriptionEvent, DonutSubscriptionEventType
8
9
  from .events import Update
9
10
  from .keyboards import ButtonColor, ButtonType, CallbackButton, TextButton
10
11
  from .messages import Coordinates, Geo, Keyboard, Message, MessageEvent, User
@@ -17,6 +18,8 @@ __all__ = [
17
18
  "CallbackButton",
18
19
  "Coordinates",
19
20
  "DocumentAttachment",
21
+ "DonutSubscriptionEvent",
22
+ "DonutSubscriptionEventType",
20
23
  "Geo",
21
24
  "Keyboard",
22
25
  "Message",
@@ -0,0 +1,34 @@
1
+ """Typed facts from VK Donut subscription events, not subscription or access state."""
2
+
3
+ from enum import StrEnum
4
+
5
+ from pydantic import Field
6
+
7
+ from .base import VKModel
8
+
9
+
10
+ class DonutSubscriptionEventType(StrEnum):
11
+ """The five supported VK Callback subscription event names."""
12
+
13
+ CREATE = "donut_subscription_create"
14
+ PROLONGED = "donut_subscription_prolonged"
15
+ CANCELLED = "donut_subscription_cancelled"
16
+ EXPIRED = "donut_subscription_expired"
17
+ PRICE_CHANGED = "donut_subscription_price_changed"
18
+
19
+
20
+ class DonutSubscriptionEvent(VKModel):
21
+ """Shared view of a Donut event object; amounts are in rubles.
22
+
23
+ Monetary fields depend on the event type and default to None when absent.
24
+ Unknown fields are retained. This object carries no inferred payment dates
25
+ or entitlement status; cancellation does not itself mean access has expired.
26
+ """
27
+
28
+ user_id: int = Field(strict=True, gt=0)
29
+ amount: int | None = Field(default=None, strict=True)
30
+ amount_without_fee: float | None = Field(default=None, strict=True, allow_inf_nan=False)
31
+ amount_old: int | None = Field(default=None, strict=True)
32
+ amount_new: int | None = Field(default=None, strict=True)
33
+ amount_diff: float | None = Field(default=None, strict=True, allow_inf_nan=False)
34
+ amount_diff_without_fee: float | None = Field(default=None, strict=True, allow_inf_nan=False)
@@ -7,6 +7,7 @@ from pydantic import JsonValue, PrivateAttr, ValidationError, field_validator, m
7
7
  from python_vk_bot.errors import InvalidUpdateError
8
8
 
9
9
  from .base import VKModel
10
+ from .donut import DonutSubscriptionEvent, DonutSubscriptionEventType
10
11
  from .messages import Message, MessageEvent, MessageObject
11
12
 
12
13
 
@@ -18,6 +19,7 @@ class Update(VKModel):
18
19
  object: JsonValue
19
20
  _message: Message | None = PrivateAttr(default=None)
20
21
  _message_event: MessageEvent | None = PrivateAttr(default=None)
22
+ _donut_subscription: DonutSubscriptionEvent | None = PrivateAttr(default=None)
21
23
 
22
24
  @field_validator("event_id", mode="before")
23
25
  @classmethod
@@ -31,6 +33,8 @@ class Update(VKModel):
31
33
  self._message = MessageObject.model_validate(self.object).message
32
34
  elif self.type == "message_event":
33
35
  self._message_event = MessageEvent.model_validate(self.object)
36
+ elif self.type in DonutSubscriptionEventType:
37
+ self._donut_subscription = DonutSubscriptionEvent.model_validate(self.object)
34
38
  return self
35
39
 
36
40
  @classmethod
@@ -50,12 +54,19 @@ class Update(VKModel):
50
54
  def message_event(self) -> MessageEvent | None:
51
55
  return self._message_event
52
56
 
57
+ @property
58
+ def donut_subscription(self) -> DonutSubscriptionEvent | None:
59
+ """Return the parsed subscription event, not a synchronized access status."""
60
+ return self._donut_subscription
61
+
53
62
  @property
54
63
  def user_id(self) -> int | None:
55
64
  if self.message is not None:
56
65
  return self.message.from_id
57
66
  if self.message_event is not None:
58
67
  return self.message_event.user_id
68
+ if self.donut_subscription is not None:
69
+ return self.donut_subscription.user_id
59
70
  return None
60
71
 
61
72
  @property
@@ -0,0 +1,86 @@
1
+ """Bounded, application-owned event admission; only Application consumes events."""
2
+
3
+ import asyncio
4
+ from dataclasses import dataclass, field
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from .application import Application
9
+
10
+
11
+ @dataclass(slots=True)
12
+ class _QueueItem:
13
+ event: object
14
+ user_id: int | None = None
15
+ peer_id: int | None = None
16
+ error: Exception | None = field(default=None, repr=False)
17
+ receipt: asyncio.Future[bool] | None = field(default=None, repr=False)
18
+ task: asyncio.Task[bool] | None = field(default=None, repr=False)
19
+ cancelled: bool = False
20
+
21
+
22
+ class UpdateQueue:
23
+ """Producer interface to Application's FIFO, not a standalone asyncio.Queue.
24
+
25
+ put waits for capacity outside handlers. In a handler, a full queue raises
26
+ QueueFull instead of waiting for the consumer that is awaiting that handler.
27
+ Items and their state scopes are process-local; no durable acceptance is implied.
28
+ """
29
+
30
+ def __init__(self, application: Application, maxsize: int) -> None:
31
+ if maxsize <= 0:
32
+ raise ValueError("update_queue_size must be positive")
33
+ self._application = application
34
+ self._queue: asyncio.Queue[_QueueItem] = asyncio.Queue(maxsize)
35
+ self._space = asyncio.Event()
36
+ self._closed = False
37
+
38
+ @property
39
+ def maxsize(self) -> int:
40
+ return self._queue.maxsize
41
+
42
+ def qsize(self) -> int:
43
+ return self._queue.qsize()
44
+
45
+ def empty(self) -> bool:
46
+ return self._queue.empty()
47
+
48
+ def full(self) -> bool:
49
+ return self._queue.full()
50
+
51
+ async def put(
52
+ self, update: object, *, user_id: int | None = None, peer_id: int | None = None
53
+ ) -> None:
54
+ """Enqueue an event, waiting for capacity; does not wait for dispatch."""
55
+ await self._put(_QueueItem(update, user_id, peer_id))
56
+
57
+ def put_nowait(
58
+ self, update: object, *, user_id: int | None = None, peer_id: int | None = None
59
+ ) -> None:
60
+ """Enqueue an event or raise QueueFull/LifecycleError without waiting."""
61
+ self._put_nowait(_QueueItem(update, user_id, peer_id))
62
+
63
+ def _put_nowait(self, item: _QueueItem) -> None:
64
+ self._application._check_enqueue(self, item)
65
+ self._queue.put_nowait(item)
66
+
67
+ async def _put(self, item: _QueueItem) -> None:
68
+ while True:
69
+ try:
70
+ self._put_nowait(item)
71
+ return
72
+ except asyncio.QueueFull:
73
+ if self._application._processing_task is asyncio.current_task():
74
+ raise
75
+ self._space.clear()
76
+ await self._space.wait()
77
+
78
+ async def _get(self) -> _QueueItem:
79
+ item = await self._queue.get()
80
+ self._space.set()
81
+ return item
82
+
83
+ def _close(self) -> None:
84
+ self._closed = True
85
+ self._queue.shutdown()
86
+ self._space.set()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-vk-bot
3
- Version: 0.3.0
3
+ Version: 0.5.0
4
4
  Summary: An asynchronous framework for VK community bots.
5
5
  Project-URL: Homepage, https://github.com/fomenko-ai/python-vk-bot
6
6
  Project-URL: Repository, https://github.com/fomenko-ai/python-vk-bot
@@ -74,6 +74,8 @@ See the [examples guide](examples/README.md) for setup, required events and run
74
74
  | [Keyboards](examples/keyboards.py) | Ordinary text buttons and inline callback buttons with message editing |
75
75
  | [Interactive map](examples/interactive_map.py) | Generate, upload and replace a PNG using navigation buttons |
76
76
  | [Callback receiver](examples/callback.py) | Receive events through an ASGI application |
77
+ | [Background result](examples/background_result.py) | Return a local calculation through the unified event queue |
78
+ | [Donut subscriptions](examples/donut_subscriptions.py) | Receive five typed subscription events and inspect the latest notification |
77
79
 
78
80
  ## Long Poll bot
79
81
 
@@ -287,6 +289,29 @@ The media API has network-free regression tests. Actual replacement of a photo i
287
289
  existing VK message has not yet been verified with a live token; an explicitly enabled
288
290
  [integration test](docs/development/media-api.md#live-integration-test) is provided.
289
291
 
292
+ ## Background tasks and internal events
293
+
294
+ Use `Application.create_task()` for background operations and `update_queue.put()` to
295
+ return Python objects to the shared serial dispatcher. `TypeHandler` routes these results;
296
+ `ApplicationHandlerStop` skips later handler groups for the current event. See the
297
+ [background-result example](examples/background_result.py).
298
+
299
+ The application manages task completion and calls `post_stop` before closing Bot.
300
+ Queue capacity, state scopes, cancellation, workers and shutdown are described in the
301
+ [event processing guide](docs/development/event-processing.md). The queue is in memory
302
+ and does not preserve work across restarts.
303
+
304
+ ## VK Donut events
305
+
306
+ Register `DonutSubscriptionHandler(on_donut)` through `Application.add_handler` to receive
307
+ all five subscription Callback events. Inside the async callback, `update.donut_subscription`
308
+ provides the typed object and `update.user_id` selects the subscriber's `context.user_data`.
309
+ Use `event_types` or composable `filters.DONUT_SUBSCRIPTION_*` predicates to select events.
310
+
311
+ These are subscription-change notifications, not a synchronized subscriber list or a paid
312
+ access check. See the [Donut guide](docs/development/donut.md) for setup, models, filtering,
313
+ delivery limitations and the runnable example.
314
+
290
315
  ## Agent Skills
291
316
 
292
317
  The bundled **telegram-to-vk** Agent Skill helps AI coding agents migrate
@@ -1,26 +1,28 @@
1
- python_vk_bot/__init__.py,sha256=K13sH66cbtWhwr-yB2TcrW5f7L2W0pe4rhCueBDCA50,1094
1
+ python_vk_bot/__init__.py,sha256=z13dYqi5v02yff21dmb0fIfDn6lpjOumFA1zEASux90,1461
2
2
  python_vk_bot/_config.py,sha256=Rju-sjCKAfk70ajQbpPMzOuefBIjtgF8tKjOuSYo0AE,744
3
- python_vk_bot/application.py,sha256=rHjKVJRUTGwqgpp7DRJrZOV1eP-_LZ9_ei90EYsTQcs,8741
3
+ python_vk_bot/application.py,sha256=dkHR3F6geN8VhpnnfCb7aSEL1k8GCo-iA9nSZRoZCC4,20361
4
4
  python_vk_bot/bot.py,sha256=zZ_lKe6Ac5eREm0gDV02XuUkIgcdU3pki4lsJLrs4NA,13379
5
5
  python_vk_bot/callback.py,sha256=9j11jtl4rpTnfUThvOf2g6kb7wYQXAQerHbuk3IYw3o,4726
6
- python_vk_bot/context.py,sha256=pzsnUSdJsVLCAsCeItf0L804HclyDtzG2laZrLlHDpk,445
7
- python_vk_bot/errors.py,sha256=qWA1OwH0HOIzZiL3LUBHKE5dMNkphNRIUKQ9OcLmqC0,1267
8
- python_vk_bot/filters.py,sha256=5fpOdxTZvFmrgokWUvYj1nowCWvPlLt9EUhRmB-0HVg,1285
9
- python_vk_bot/handlers.py,sha256=iG91bzA40evZFY6Qp78nvoz_O4pjG0lE6p1IwLuCQSY,1974
6
+ python_vk_bot/context.py,sha256=yFPT1rXCUXSfbyPCu4y2kmWv2NI_XlZ2zIbzTpeWG90,504
7
+ python_vk_bot/errors.py,sha256=brqC5zxQgXOBRNPMOU230CPFL0rFZi_tZBr3mua0wBA,1393
8
+ python_vk_bot/filters.py,sha256=YuZQwSpcMI2N56SnEggx_lvImiISSF_QJ52QIfGe8Uo,2059
9
+ python_vk_bot/handlers.py,sha256=MXGGD7FFMugrKLazkvUvSPPIxQXfJUgoj3-xFGFbKsw,4503
10
10
  python_vk_bot/long_poll.py,sha256=rmAxflq0E3H-tMDybQ7fBf1cKsJQFnaU4VbyQS3BSw4,3777
11
11
  python_vk_bot/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ python_vk_bot/queues.py,sha256=9OCfYBpOpcJBbW-7TwsIb18raJN2pueZbXoJUgu7MOc,2861
12
13
  python_vk_bot/settings.py,sha256=JcbDihGRJGRGvBBSeB3j_LPaoX7dkPHfh-WviKQCrwk,915
13
14
  python_vk_bot/transport.py,sha256=eVsq0_brPXQ0Yk1ngMhiWHD9Z6S5Y1NhH193jbMTkmE,9812
14
15
  python_vk_bot/.agents/skills/telegram-to-vk/SKILL.md,sha256=WMrNoxLkhhlu8wnS9rFpZi3OlwBlVNHCYFSNtKmkJzM,2828
15
16
  python_vk_bot/.agents/skills/telegram-to-vk/references/migration-mapping.md,sha256=KFxmCQyKbUK7Z0JuS39FocyoFdtnslLLp9j2pNeJAds,9019
16
- python_vk_bot/models/__init__.py,sha256=znIpo8F8TrxEGxeEkAkA-M5qp6aqH-NPRNdblgOBBsk,638
17
+ python_vk_bot/models/__init__.py,sha256=eAdbM08JcoYv6JPrdorVC6DvEfxhgp-5h9pXFa3B7iQ,772
17
18
  python_vk_bot/models/api.py,sha256=jY9pedj7TZQkt9bRROUo8rMrO2PyAO7DPJz7E1YphYs,1626
18
19
  python_vk_bot/models/attachments.py,sha256=5JWHv37BtSzRI9j_z_yAHToJ61EyBxqRjYp7Y7rP-1o,3887
19
20
  python_vk_bot/models/base.py,sha256=LYcbevtU8jq5QVLo8b1mOv70RzgEYjPtTmhMMe-JN3A,249
20
- python_vk_bot/models/events.py,sha256=bS8XC0TJrj_AG0u6H9fs35kMkg47EeVoxtaUH7ya1gM,2222
21
+ python_vk_bot/models/donut.py,sha256=qV9OyjDbmTi2UJqvzfXOL6LqYMxZvFwJo2yI1dcLSi0,1373
22
+ python_vk_bot/models/events.py,sha256=7JPZykMTRy8hiMKsX45ZZbwGiK8-sZFtzXZqprYxK18,2826
21
23
  python_vk_bot/models/keyboards.py,sha256=ZtwBLSbd-DROuohl9mM0Ui4i7FRUzXVePnfDnmkYzvc,2395
22
24
  python_vk_bot/models/messages.py,sha256=WAUsa7VMDNl0xK2LXa91kg6RQsWBXoQATI1aAMDiHLU,1543
23
- python_vk_bot-0.3.0.dist-info/METADATA,sha256=E40KM33dn9qnJv51LV8dAkGJ8rdQIlEGDURo2nsUXkY,11789
24
- python_vk_bot-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
25
- python_vk_bot-0.3.0.dist-info/licenses/LICENSE,sha256=F-35ycqPcYW243OjxMHCggr_AHQgZLX2zvtZgobVEvo,1072
26
- python_vk_bot-0.3.0.dist-info/RECORD,,
25
+ python_vk_bot-0.5.0.dist-info/METADATA,sha256=dtwSy8aIOmhAKgRNP3XlrjXeOVUzk800a-HGE-WP4aU,13325
26
+ python_vk_bot-0.5.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
27
+ python_vk_bot-0.5.0.dist-info/licenses/LICENSE,sha256=F-35ycqPcYW243OjxMHCggr_AHQgZLX2zvtZgobVEvo,1072
28
+ python_vk_bot-0.5.0.dist-info/RECORD,,