python-vk-bot 0.2.0__py3-none-any.whl → 0.4.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,29 +5,39 @@ 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 CommandHandler, Handler, MessageEventHandler, MessageHandler, TypeHandler
9
10
  from .long_poll import LongPoll
10
11
  from .models import (
11
12
  Attachment,
12
13
  AudioMessageAttachment,
14
+ ButtonColor,
15
+ ButtonType,
16
+ CallbackButton,
13
17
  DocumentAttachment,
14
18
  Keyboard,
15
19
  Message,
16
20
  MessageEvent,
17
21
  PhotoAttachment,
22
+ TextButton,
18
23
  Update,
19
24
  User,
20
25
  VideoAttachment,
21
26
  )
27
+ from .queues import UpdateQueue
22
28
  from .settings import BotSettings
23
29
 
24
30
  __all__ = [
25
31
  "Application",
32
+ "ApplicationHandlerStop",
26
33
  "Attachment",
27
34
  "AudioMessageAttachment",
28
35
  "Bot",
29
36
  "BotSettings",
37
+ "ButtonColor",
38
+ "ButtonType",
30
39
  "Callback",
40
+ "CallbackButton",
31
41
  "CommandHandler",
32
42
  "Context",
33
43
  "DocumentAttachment",
@@ -39,7 +49,10 @@ __all__ = [
39
49
  "MessageEventHandler",
40
50
  "MessageHandler",
41
51
  "PhotoAttachment",
52
+ "TextButton",
53
+ "TypeHandler",
42
54
  "Update",
55
+ "UpdateQueue",
43
56
  "User",
44
57
  "VideoAttachment",
45
58
  "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.Task[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,199 @@ 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._consumer_task: asyncio.Task[None] | None = None
80
+ self._processing_task: asyncio.Task[bool] | None = None
81
+ self._finishing_handler: asyncio.Task[bool] | None = None
82
+ self._hook_task: asyncio.Task[object] | None = None
83
+ self._stop_task: asyncio.Task[None] | None = None
84
+ self._shutdown_task: asyncio.Task[None] | None = None
54
85
 
55
86
  @property
56
87
  def running(self) -> bool:
57
88
  return self._running
58
89
 
59
- def add_handler(self, handler: Handler, *, group: int = 0) -> None:
60
- if self._running:
90
+ @property
91
+ def update_queue(self) -> UpdateQueue:
92
+ """The current run's producer interface; only Application consumes events."""
93
+ return self._update_queue
94
+
95
+ def _check_lifecycle(self, *, stopping: bool = False) -> None:
96
+ current = asyncio.current_task()
97
+ if current is self._hook_task:
98
+ raise LifecycleError("Lifecycle hooks cannot recursively invoke lifecycle methods")
99
+ if not stopping and (current is self._processing_task or current in self._tasks):
100
+ raise LifecycleError(
101
+ "Use stop() inside a handler or task; shutdown belongs to the owner"
102
+ )
103
+
104
+ def add_handler[T](self, handler: Handler | TypeHandler[T], *, group: int = 0) -> None:
105
+ if self._started:
61
106
  raise LifecycleError("Register handlers before starting the application")
62
107
  self._handlers.setdefault(group, []).append(handler)
63
108
 
64
109
  def add_error_handler(self, callback: ErrorCallback) -> None:
65
- if self._running:
110
+ if self._started:
66
111
  raise LifecycleError("Register error handlers before starting the application")
67
112
  self._error_handlers.append(callback)
68
113
 
114
+ async def _call_hook(self, hook: LifecycleHook | None) -> None:
115
+ if hook is None:
116
+ return
117
+ self._hook_task = asyncio.current_task()
118
+ try:
119
+ await hook(self)
120
+ finally:
121
+ self._hook_task = None
122
+
69
123
  async def initialize(self) -> None:
124
+ self._check_lifecycle()
125
+ if self._shutdown_task is not None and not self._shutdown_task.done():
126
+ raise LifecycleError("Application shutdown is in progress")
127
+ self._shutdown_task = None
70
128
  async with self._lifecycle_lock:
71
129
  if self._initialized:
72
130
  return
73
131
  try:
74
132
  await self.bot.initialize()
75
- if self._post_init is not None:
76
- await self._post_init(self)
133
+ await self._call_hook(self._post_init)
77
134
  except BaseException:
78
- await self.bot.shutdown()
135
+ cleanup = asyncio.create_task(self.bot.shutdown(), name="vk-startup-cleanup")
136
+ try:
137
+ await _await_owned(cleanup)
138
+ except BaseException as error:
139
+ logger.error("Startup cleanup failed (%s)", type(error).__name__)
79
140
  raise
80
141
  self._initialized = True
81
142
 
82
143
  async def start(self) -> None:
144
+ self._check_lifecycle()
83
145
  if not self._initialized:
84
146
  raise LifecycleError("Initialize the application before starting it")
147
+ if self._shutdown_task is not None:
148
+ raise LifecycleError("Application shutdown is in progress")
149
+ if self._running:
150
+ return
151
+ if self._started:
152
+ raise LifecycleError("Shut down and initialize before starting another run")
153
+ if self._update_queue._closed:
154
+ self._update_queue = UpdateQueue(self, self._update_queue.maxsize)
155
+ self._stop_task = None
156
+ self._finishing_handler = None
157
+ self._queue_open = True
85
158
  self._running = True
159
+ self._started = True
160
+ self._post_stop_pending = True
161
+ self._consumer_task = asyncio.create_task(self._consume(), name="vk-update-consumer")
86
162
 
87
163
  async def stop(self) -> None:
88
- """Stop intake, cancel owned polling, and wait for active dispatch to finish.
164
+ """Stop intake and drain accepted work. Does not invoke post_stop or close Bot.
89
165
 
90
- A handler may call stop: its current dispatch completes before polling exits.
166
+ Inside a handler or managed task this requests stopping without awaiting
167
+ that same task. An external owner can await stop/shutdown for completion.
91
168
  """
92
- self._running = False
93
- task = self._polling_task
169
+ self._check_lifecycle(stopping=True)
170
+ if not self._started:
171
+ return
172
+ if self._stop_task is None:
173
+ self._running = False
174
+ self._finishing_handler = self._processing_task
175
+ self._update_queue._space.set()
176
+ self._stop_task = asyncio.create_task(self._stop(), name="vk-application-stop")
94
177
  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
178
+ if current is self._processing_task or current in self._tasks:
179
+ return
180
+ await _await_owned(self._stop_task)
181
+
182
+ async def _stop(self) -> None:
183
+ # Polling awaiting a receipt must finish it; cancelling it would cancel
184
+ # the active handler. Only interrupt polling that is acquiring updates.
185
+ polling = self._polling_task
186
+ if polling is not None:
187
+ if not self._polling_waiting:
188
+ polling.cancel()
189
+ await asyncio.gather(polling, return_exceptions=True)
190
+ if self._finishing_handler is not None:
191
+ await asyncio.gather(self._finishing_handler, return_exceptions=True)
192
+ tasks = tuple(self._tasks)
193
+ for task in tasks:
194
+ if self._tasks.get(task):
195
+ task.cancel()
196
+ if tasks:
197
+ await asyncio.gather(*tasks, return_exceptions=True)
198
+ self._queue_open = False
199
+ self._update_queue._close()
200
+ if self._consumer_task is not None:
201
+ await self._consumer_task
202
+ self._finishing_handler = None
101
203
 
102
204
  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()
205
+ """Drain, invoke post_stop once, close Bot, then invoke post_shutdown."""
206
+ self._check_lifecycle()
207
+ if self._shutdown_task is None:
208
+ self._shutdown_task = asyncio.create_task(
209
+ self._shutdown(), name="vk-application-shutdown"
210
+ )
211
+ await _await_owned(self._shutdown_task)
212
+
213
+ async def _shutdown(self) -> None:
214
+ # Wait for initialization, but never retain this lock while waiting for
215
+ # handlers/tasks: their lifecycle requests are rejected or request stop.
106
216
  async with self._lifecycle_lock:
107
- if not self._initialized:
108
- return
217
+ initialized = self._initialized
218
+ if not initialized:
219
+ return
220
+ failure: BaseException | None = None
221
+ try:
222
+ await self.stop()
223
+ except BaseException as error:
224
+ failure = error
225
+ if self._post_stop_pending:
226
+ self._post_stop_pending = False
109
227
  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)
228
+ await self._call_hook(self._post_stop)
229
+ except BaseException as error:
230
+ if failure is None:
231
+ failure = error
232
+ else:
233
+ logger.error("Post-stop hook failed (%s)", type(error).__name__)
234
+ try:
235
+ await self.bot.shutdown()
236
+ except BaseException as error:
237
+ if failure is None:
238
+ failure = error
239
+ else:
240
+ logger.error("Bot shutdown failed (%s)", type(error).__name__)
241
+ finally:
242
+ self._initialized = False
243
+ try:
244
+ await self._call_hook(self._post_shutdown)
245
+ except BaseException as error:
246
+ if failure is None:
247
+ failure = error
248
+ else:
249
+ logger.error("Post-shutdown hook failed (%s)", type(error).__name__)
250
+ finally:
251
+ self._started = False
252
+ if failure is not None:
253
+ raise failure
115
254
 
116
255
  async def __aenter__(self) -> Self:
117
256
  if self._initialized or self._context_active:
@@ -121,7 +260,12 @@ class Application:
121
260
  await self.initialize()
122
261
  await self.start()
123
262
  except BaseException:
124
- self._context_active = False
263
+ try:
264
+ await self.shutdown()
265
+ except BaseException as error:
266
+ logger.error("Application startup cleanup failed (%s)", type(error).__name__)
267
+ finally:
268
+ self._context_active = False
125
269
  raise
126
270
  return self
127
271
 
@@ -133,12 +277,32 @@ class Application:
133
277
  ) -> None:
134
278
  try:
135
279
  await self.shutdown()
280
+ except BaseException as error:
281
+ if exc is None:
282
+ raise
283
+ logger.error("Application cleanup failed (%s)", type(error).__name__)
136
284
  finally:
137
285
  self._context_active = False
138
286
 
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
287
+ def _check_enqueue(self, queue: UpdateQueue, item: _QueueItem) -> None:
288
+ current = asyncio.current_task()
289
+ finishing = current is self._finishing_handler or current in self._tasks
290
+ if (
291
+ queue is not self._update_queue
292
+ or not self._queue_open
293
+ or not (self._running or finishing)
294
+ ):
295
+ raise LifecycleError("Application is not running or accepting events")
296
+ if isinstance(item.event, Update):
297
+ if item.event.group_id != self.group_id:
298
+ raise ValueError("Update belongs to another community")
299
+ if item.user_id is not None or item.peer_id is not None:
300
+ raise ValueError("VK update state scopes are supplied by the update")
301
+
302
+ def _context(self, item: _QueueItem, error: Exception | None = None) -> Context:
303
+ event = item.event
304
+ user_id = event.user_id if isinstance(event, Update) else item.user_id
305
+ peer_id = event.peer_id if isinstance(event, Update) else item.peer_id
142
306
  return Context(
143
307
  application=self,
144
308
  bot=self.bot,
@@ -146,62 +310,168 @@ class Application:
146
310
  peer_data=self.peer_data.setdefault(peer_id, {}) if peer_id is not None else {},
147
311
  bot_data=self.bot_data,
148
312
  error=error,
313
+ event=event,
149
314
  )
150
315
 
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__)
316
+ async def _report_error(self, item: _QueueItem, error: Exception) -> None:
317
+ context = self._context(item, error)
318
+ update = item.event if isinstance(item.event, Update) else None
319
+ logger.error("Event processing failed (%s)", type(error).__name__)
154
320
  for callback in self._error_handlers:
155
321
  try:
156
322
  await callback(update, context)
323
+ except ApplicationHandlerStop:
324
+ break
157
325
  except Exception as callback_error:
158
326
  logger.error("Error handler failed (%s)", type(callback_error).__name__)
159
327
 
160
- async def process_update(self, update: Update) -> bool:
161
- """Return False for a duplicate, True after dispatch; propagate handler errors."""
328
+ async def process_update(
329
+ self, update: object, *, user_id: int | None = None, peer_id: int | None = None
330
+ ) -> bool:
331
+ """Queue and await dispatch; False for a duplicate, otherwise True.
332
+
333
+ Cancellation skips queued work or cancels/awaits the active handler.
334
+ Internal objects can explicitly select user/peer state scopes.
335
+ """
162
336
  if self._processing_task is asyncio.current_task():
163
337
  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:
338
+ return await self._submit(_QueueItem(update, user_id, peer_id))
339
+
340
+ async def _submit(self, item: _QueueItem) -> bool:
341
+ receipt = asyncio.get_running_loop().create_future()
342
+ item.receipt = receipt
343
+ try:
344
+ await self._update_queue._put(item)
345
+ return await asyncio.shield(receipt)
346
+ except asyncio.CancelledError:
347
+ item.cancelled = True
348
+ if receipt.done() and not receipt.cancelled():
349
+ receipt.exception()
350
+ receipt.cancel()
351
+ if item.task is not None and not item.task.done():
352
+ item.task.cancel()
353
+ with suppress(BaseException):
354
+ await _await_owned(item.task)
355
+ raise
356
+
357
+ async def _consume(self) -> None:
358
+ while True:
359
+ try:
360
+ item = await self._update_queue._get()
361
+ except asyncio.QueueShutDown:
362
+ return
363
+ try:
364
+ if item.cancelled:
365
+ continue
366
+ task = asyncio.create_task(self._dispatch(item), name="vk-event-dispatch")
367
+ item.task = task
368
+ self._processing_task = task
369
+ try:
370
+ result = await task
371
+ except asyncio.CancelledError:
372
+ if item.receipt is not None and not item.receipt.done():
373
+ item.receipt.cancel()
374
+ current = asyncio.current_task()
375
+ if current is not None and current.cancelling():
376
+ raise
377
+ except Exception as error:
378
+ if item.receipt is not None and not item.receipt.done():
379
+ item.receipt.set_exception(error)
380
+ else:
381
+ if item.receipt is not None and not item.receipt.done():
382
+ item.receipt.set_result(result)
383
+ finally:
384
+ self._processing_task = None
385
+ finally:
386
+ self._update_queue._queue.task_done()
387
+
388
+ async def _dispatch(self, item: _QueueItem) -> bool:
389
+ if item.error is not None:
390
+ await self._report_error(item, item.error)
391
+ return True
392
+ event = item.event
393
+ if isinstance(event, Update):
394
+ if event.group_id != self.group_id:
168
395
  raise ValueError("Update belongs to another community")
169
- if update.event_id in self._seen:
396
+ if event.event_id in self._seen:
170
397
  return False
171
- self._processing_task = asyncio.current_task()
398
+ try:
399
+ context = self._context(item)
400
+ for group in sorted(self._handlers):
401
+ for handler in self._handlers[group]:
402
+ if await handler._dispatch(event, context):
403
+ break
404
+ except ApplicationHandlerStop:
405
+ pass
406
+ except Exception as error:
407
+ await self._report_error(item, error)
408
+ raise
409
+ if isinstance(event, Update) and self._deduplication_size:
410
+ self._seen[event.event_id] = None
411
+ if len(self._seen) > self._deduplication_size:
412
+ self._seen.popitem(last=False)
413
+ return True
414
+
415
+ def create_task[T](
416
+ self,
417
+ coroutine: Coroutine[object, object, T],
418
+ *,
419
+ update: object = None,
420
+ name: str | None = None,
421
+ cancel_on_stop: bool = False,
422
+ ) -> asyncio.Task[T]:
423
+ """Own a running coroutine, report failures serially, and await it on stop.
424
+
425
+ Use cancel_on_stop for long-lived workers. Tasks must not directly mutate
426
+ Context state or be awaited by a handler if they depend on the consumer.
427
+ """
428
+ if not self._running:
429
+ coroutine.close()
430
+ raise LifecycleError("Create tasks only while the application is running")
431
+ if isinstance(update, Update) and update.group_id != self.group_id:
432
+ coroutine.close()
433
+ raise ValueError("Update belongs to another community")
434
+
435
+ async def run() -> T:
172
436
  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
437
+ return await coroutine
179
438
  except Exception as error:
180
- await self._report_error(update, error)
439
+ try:
440
+ await self._submit(_QueueItem(update, error=error))
441
+ except Exception as reporting_error:
442
+ logger.error("Task error reporting failed (%s)", type(reporting_error).__name__)
181
443
  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
444
+
445
+ task = asyncio.create_task(run(), name=name)
446
+ self._tasks[task] = cancel_on_stop
447
+
448
+ def finished(done: asyncio.Task[T]) -> None:
449
+ self._tasks.pop(done, None)
450
+ # Also close a coroutine cancelled before the wrapper's first step.
451
+ coroutine.close()
452
+ if not done.cancelled():
453
+ done.exception()
454
+
455
+ task.add_done_callback(finished)
456
+ return task
189
457
 
190
458
  async def _poll(self, long_poll: LongPoll) -> None:
191
459
  async with aclosing(long_poll.listen()) as updates:
192
460
  async for update in updates:
193
461
  if not self._running:
194
462
  break
463
+ self._polling_waiting = True
195
464
  try:
196
465
  await self.process_update(update)
197
466
  except Exception:
198
- # Dispatch already reported the error; never replay partial side effects.
199
467
  logger.warning("Skipping failed update in polling mode")
468
+ finally:
469
+ self._polling_waiting = False
200
470
  if not self._running:
201
471
  break
202
472
 
203
473
  async def run_polling(self, *, wait: int = 25) -> None:
204
- """Run until stop or cancellation; own startup and shutdown, not the event loop."""
474
+ """Run until stop/cancellation; own lifecycle, not the caller's event loop."""
205
475
  if self._polling_task is not None:
206
476
  raise LifecycleError("Polling is already running")
207
477
  long_poll = LongPoll(self.bot, self.group_id, wait=wait)
@@ -215,7 +485,7 @@ class Application:
215
485
  if current is not None and current.cancelling():
216
486
  raise
217
487
  except Exception as error:
218
- await self._report_error(None, error)
488
+ await self._submit(_QueueItem(None, error=error))
219
489
  raise
220
490
  finally:
221
491
  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/handlers.py CHANGED
@@ -1,6 +1,7 @@
1
1
  """Typed handler registration without a conversation-state framework."""
2
2
 
3
3
  from collections.abc import Awaitable, Callable
4
+ from typing import Protocol, TypeGuard
4
5
 
5
6
  from . import filters
6
7
  from .context import Context
@@ -9,6 +10,10 @@ from .models import Update
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__(
@@ -6,11 +6,15 @@ from .attachments import (
6
6
  VideoAttachment,
7
7
  )
8
8
  from .events import Update
9
+ from .keyboards import ButtonColor, ButtonType, CallbackButton, TextButton
9
10
  from .messages import Coordinates, Geo, Keyboard, Message, MessageEvent, User
10
11
 
11
12
  __all__ = [
12
13
  "Attachment",
13
14
  "AudioMessageAttachment",
15
+ "ButtonColor",
16
+ "ButtonType",
17
+ "CallbackButton",
14
18
  "Coordinates",
15
19
  "DocumentAttachment",
16
20
  "Geo",
@@ -18,6 +22,7 @@ __all__ = [
18
22
  "Message",
19
23
  "MessageEvent",
20
24
  "PhotoAttachment",
25
+ "TextButton",
21
26
  "Update",
22
27
  "User",
23
28
  "VideoAttachment",
@@ -0,0 +1,78 @@
1
+ """Convenient outgoing button models with VK JSON serialization."""
2
+
3
+ import json
4
+ from enum import StrEnum
5
+ from typing import Annotated, Literal
6
+
7
+ from pydantic import (
8
+ BaseModel,
9
+ ConfigDict,
10
+ Field,
11
+ JsonValue,
12
+ SerializeAsAny,
13
+ SerializerFunctionWrapHandler,
14
+ field_serializer,
15
+ model_serializer,
16
+ )
17
+
18
+
19
+ class ButtonColor(StrEnum):
20
+ """Colors documented by the VK keyboard guide."""
21
+
22
+ PRIMARY = "primary"
23
+ SECONDARY = "secondary"
24
+ POSITIVE = "positive"
25
+ NEGATIVE = "negative"
26
+
27
+
28
+ class ButtonType(StrEnum):
29
+ """Action types supported by the typed button models."""
30
+
31
+ TEXT = "text"
32
+ CALLBACK = "callback"
33
+
34
+
35
+ class _LabeledButton(BaseModel):
36
+ model_config = ConfigDict(
37
+ extra="forbid", validate_assignment=True, hide_input_in_errors=True, allow_inf_nan=False
38
+ )
39
+
40
+ label: str = Field(repr=False)
41
+ payload: dict[str, JsonValue] | SerializeAsAny[BaseModel] | str | None = Field(
42
+ default=None, repr=False
43
+ )
44
+ color: ButtonColor = ButtonColor.SECONDARY
45
+
46
+ @field_serializer("payload", when_used="json")
47
+ def serialize_payload(self, value: dict[str, JsonValue] | BaseModel | str | None) -> str | None:
48
+ if isinstance(value, BaseModel):
49
+ return value.model_dump_json(by_alias=True)
50
+ if isinstance(value, dict):
51
+ return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
52
+ return value
53
+
54
+ @model_serializer(mode="wrap", when_used="json")
55
+ def serialize_button(self, handler: SerializerFunctionWrapHandler) -> dict[str, JsonValue]:
56
+ action: dict[str, JsonValue] = handler(self)
57
+ button: dict[str, JsonValue] = {"action": action}
58
+ if "color" in action:
59
+ button["color"] = action.pop("color")
60
+ # Absence of payload is represented by an omitted action field, never JSON null.
61
+ if action.get("payload") is None:
62
+ action.pop("payload", None)
63
+ return button
64
+
65
+
66
+ class TextButton(_LabeledButton):
67
+ """Send the label and optional payload as a message, handled by MessageHandler."""
68
+
69
+ type: Literal[ButtonType.TEXT] = ButtonType.TEXT
70
+
71
+
72
+ class CallbackButton(_LabeledButton):
73
+ """Emit a message_event, handled by MessageEventHandler."""
74
+
75
+ type: Literal[ButtonType.CALLBACK] = ButtonType.CALLBACK
76
+
77
+
78
+ type TypedButton = Annotated[TextButton | CallbackButton, Field(discriminator="type")]
@@ -4,6 +4,7 @@ from pydantic import Field, JsonValue
4
4
 
5
5
  from .attachments import Attachment, parse_attachment
6
6
  from .base import VKModel
7
+ from .keyboards import TypedButton
7
8
 
8
9
 
9
10
  class Coordinates(VKModel):
@@ -53,7 +54,7 @@ class User(VKModel):
53
54
 
54
55
 
55
56
  class Keyboard(VKModel):
56
- buttons: list[list[dict[str, JsonValue]]]
57
+ buttons: list[list[TypedButton | dict[str, JsonValue]]]
57
58
  one_time: bool = False
58
59
  inline: bool = False
59
60
 
@@ -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.2.0
3
+ Version: 0.4.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,7 @@ 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 |
77
78
 
78
79
  ## Long Poll bot
79
80
 
@@ -287,6 +288,18 @@ The media API has network-free regression tests. Actual replacement of a photo i
287
288
  existing VK message has not yet been verified with a live token; an explicitly enabled
288
289
  [integration test](docs/development/media-api.md#live-integration-test) is provided.
289
290
 
291
+ ## Background tasks and internal events
292
+
293
+ Use `Application.create_task()` for background operations and `update_queue.put()` to
294
+ return Python objects to the shared serial dispatcher. `TypeHandler` routes these results;
295
+ `ApplicationHandlerStop` skips later handler groups for the current event. See the
296
+ [background-result example](examples/background_result.py).
297
+
298
+ The application manages task completion and calls `post_stop` before closing Bot.
299
+ Queue capacity, state scopes, cancellation, workers and shutdown are described in the
300
+ [event processing guide](docs/development/event-processing.md). The queue is in memory
301
+ and does not preserve work across restarts.
302
+
290
303
  ## Agent Skills
291
304
 
292
305
  The bundled **telegram-to-vk** Agent Skill helps AI coding agents migrate
@@ -1,25 +1,27 @@
1
- python_vk_bot/__init__.py,sha256=VVjIFYtWN4iBjyWHD53swcdsi9iF3h2imIyLoAS2y2g,948
1
+ python_vk_bot/__init__.py,sha256=gPIWyuwSePq-smJP_qS00CRMR0M0TAUGrl3HE6Bav20,1250
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=mn1L8d85CRrmtfIrtz-i893z3GaK98Z4SR-0Fxilm3w,19865
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
6
+ python_vk_bot/context.py,sha256=yFPT1rXCUXSfbyPCu4y2kmWv2NI_XlZ2zIbzTpeWG90,504
7
+ python_vk_bot/errors.py,sha256=brqC5zxQgXOBRNPMOU230CPFL0rFZi_tZBr3mua0wBA,1393
8
8
  python_vk_bot/filters.py,sha256=5fpOdxTZvFmrgokWUvYj1nowCWvPlLt9EUhRmB-0HVg,1285
9
- python_vk_bot/handlers.py,sha256=iG91bzA40evZFY6Qp78nvoz_O4pjG0lE6p1IwLuCQSY,1974
9
+ python_vk_bot/handlers.py,sha256=UkGx773OdDM-F7myxQNjSMRUYyZQQpwvj4Lznc1csvM,3221
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=pY7XWrFu8HlVRMmBAM6899EDs61Y6mqO2qIH10eNpZY,486
17
+ python_vk_bot/models/__init__.py,sha256=znIpo8F8TrxEGxeEkAkA-M5qp6aqH-NPRNdblgOBBsk,638
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
21
  python_vk_bot/models/events.py,sha256=bS8XC0TJrj_AG0u6H9fs35kMkg47EeVoxtaUH7ya1gM,2222
21
- python_vk_bot/models/messages.py,sha256=r0YZXYA63eAVzhiB4hM1COg0xEbe1b9fcBGwl0aBUqw,1494
22
- python_vk_bot-0.2.0.dist-info/METADATA,sha256=cJsI4VjKjBWt31vE9Dj2mKKusloT1KdFn24RYYXOr0w,11789
23
- python_vk_bot-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
24
- python_vk_bot-0.2.0.dist-info/licenses/LICENSE,sha256=F-35ycqPcYW243OjxMHCggr_AHQgZLX2zvtZgobVEvo,1072
25
- python_vk_bot-0.2.0.dist-info/RECORD,,
22
+ python_vk_bot/models/keyboards.py,sha256=ZtwBLSbd-DROuohl9mM0Ui4i7FRUzXVePnfDnmkYzvc,2395
23
+ python_vk_bot/models/messages.py,sha256=WAUsa7VMDNl0xK2LXa91kg6RQsWBXoQATI1aAMDiHLU,1543
24
+ python_vk_bot-0.4.0.dist-info/METADATA,sha256=bKg5KuHSG0K-cNzPTC_KsdIhEVj73-Ps_Ub5XI5yrqE,12567
25
+ python_vk_bot-0.4.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
26
+ python_vk_bot-0.4.0.dist-info/licenses/LICENSE,sha256=F-35ycqPcYW243OjxMHCggr_AHQgZLX2zvtZgobVEvo,1072
27
+ python_vk_bot-0.4.0.dist-info/RECORD,,