python-vk-bot 0.4.0__tar.gz → 0.6.0__tar.gz

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.
Files changed (33) hide show
  1. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/CHANGELOG.md +30 -0
  2. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/PKG-INFO +14 -2
  3. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/README.md +13 -1
  4. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/examples/README.md +24 -3
  5. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/pyproject.toml +1 -1
  6. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/__init__.py +19 -1
  7. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/application.py +18 -8
  8. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/bot.py +7 -2
  9. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/errors.py +4 -1
  10. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/filters.py +18 -1
  11. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/handlers.py +35 -2
  12. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/models/__init__.py +15 -1
  13. python_vk_bot-0.6.0/python_vk_bot/models/donut.py +34 -0
  14. python_vk_bot-0.6.0/python_vk_bot/models/event_answers.py +14 -0
  15. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/models/events.py +11 -0
  16. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/models/keyboards.py +25 -4
  17. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/transport.py +54 -1
  18. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/.gitignore +0 -0
  19. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/LICENSE +0 -0
  20. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/docs/decisions/README.md +0 -0
  21. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/.agents/skills/telegram-to-vk/SKILL.md +0 -0
  22. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/.agents/skills/telegram-to-vk/references/migration-mapping.md +0 -0
  23. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/_config.py +0 -0
  24. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/callback.py +0 -0
  25. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/context.py +0 -0
  26. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/long_poll.py +0 -0
  27. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/models/api.py +0 -0
  28. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/models/attachments.py +0 -0
  29. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/models/base.py +0 -0
  30. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/models/messages.py +0 -0
  31. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/py.typed +0 -0
  32. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/queues.py +0 -0
  33. {python_vk_bot-0.4.0 → python_vk_bot-0.6.0}/python_vk_bot/settings.py +0 -0
@@ -2,6 +2,36 @@
2
2
 
3
3
  All notable changes will be documented here, following Keep a Changelog.
4
4
 
5
+ ## Unreleased
6
+
7
+ -
8
+
9
+ ## 0.6.0 - 2026-11-06
10
+
11
+ ### Added
12
+
13
+ - `OpenLinkButton` and `LocationButton` with automatic payload serialization, mixed
14
+ typed/raw keyboards, and `ButtonType.OPEN_LINK` / `ButtonType.LOCATION` values.
15
+ - `ShowSnackbar` for typed callback answers through `Bot.send_message_event_answer`,
16
+ validating VK's 90-character text limit while retaining raw mapping support.
17
+ - Optional `HTTPError.retry_after` in seconds, read from HTTP `Retry-After` integer
18
+ seconds or HTTP-date. No automatic retries or waits are added; VK API error 6
19
+ retains its separate `RateLimitError` behavior.
20
+
21
+ ## 0.5.0 - 2026-11-05
22
+
23
+ ### Added
24
+
25
+ - Typed support for all five VK Donut subscription Callback events through
26
+ `Update.donut_subscription`, subscriber user context, `DonutSubscriptionHandler`
27
+ and composable filters. See the [Donut guide](docs/development/donut.md) and
28
+ Callback example. These events report changes without synchronizing paid access.
29
+
30
+ ### Fixed
31
+
32
+ - Concurrent graceful stop and polling-runner cancellation wait for Long Poll cleanup
33
+ without interrupting it with a second cancellation request.
34
+
5
35
  ## 0.4.0 - 2026-11-03
6
36
 
7
37
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-vk-bot
3
- Version: 0.4.0
3
+ Version: 0.6.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
@@ -71,10 +71,11 @@ See the [examples guide](examples/README.md) for setup, required events and run
71
71
  | Example | Description |
72
72
  | --- | --- |
73
73
  | [Echo bot](examples/echo.py) | Reply to text messages using Bots Long Poll |
74
- | [Keyboards](examples/keyboards.py) | Ordinary text buttons and inline callback buttons with message editing |
74
+ | [Keyboards](examples/keyboards.py) | Text, callback, link and location buttons; typed snackbar answers and 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
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 |
78
79
 
79
80
  ## Long Poll bot
80
81
 
@@ -300,6 +301,17 @@ Queue capacity, state scopes, cancellation, workers and shutdown are described i
300
301
  [event processing guide](docs/development/event-processing.md). The queue is in memory
301
302
  and does not preserve work across restarts.
302
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
+
303
315
  ## Agent Skills
304
316
 
305
317
  The bundled **telegram-to-vk** Agent Skill helps AI coding agents migrate
@@ -45,10 +45,11 @@ See the [examples guide](examples/README.md) for setup, required events and run
45
45
  | Example | Description |
46
46
  | --- | --- |
47
47
  | [Echo bot](examples/echo.py) | Reply to text messages using Bots Long Poll |
48
- | [Keyboards](examples/keyboards.py) | Ordinary text buttons and inline callback buttons with message editing |
48
+ | [Keyboards](examples/keyboards.py) | Text, callback, link and location buttons; typed snackbar answers and message editing |
49
49
  | [Interactive map](examples/interactive_map.py) | Generate, upload and replace a PNG using navigation buttons |
50
50
  | [Callback receiver](examples/callback.py) | Receive events through an ASGI application |
51
51
  | [Background result](examples/background_result.py) | Return a local calculation through the unified event queue |
52
+ | [Donut subscriptions](examples/donut_subscriptions.py) | Receive five typed subscription events and inspect the latest notification |
52
53
 
53
54
  ## Long Poll bot
54
55
 
@@ -274,6 +275,17 @@ Queue capacity, state scopes, cancellation, workers and shutdown are described i
274
275
  [event processing guide](docs/development/event-processing.md). The queue is in memory
275
276
  and does not preserve work across restarts.
276
277
 
278
+ ## VK Donut events
279
+
280
+ Register `DonutSubscriptionHandler(on_donut)` through `Application.add_handler` to receive
281
+ all five subscription Callback events. Inside the async callback, `update.donut_subscription`
282
+ provides the typed object and `update.user_id` selects the subscriber's `context.user_data`.
283
+ Use `event_types` or composable `filters.DONUT_SUBSCRIPTION_*` predicates to select events.
284
+
285
+ These are subscription-change notifications, not a synchronized subscriber list or a paid
286
+ access check. See the [Donut guide](docs/development/donut.md) for setup, models, filtering,
287
+ delivery limitations and the runnable example.
288
+
277
289
  ## Agent Skills
278
290
 
279
291
  The bundled **telegram-to-vk** Agent Skill helps AI coding agents migrate
@@ -25,6 +25,7 @@ The Callback example uses its own HTTP delivery setup instead.
25
25
  | [keyboards.py](keyboards.py) | Ordinary and inline keyboards, payloads and message editing | `message_new`, `message_event` |
26
26
  | [interactive_map.py](interactive_map.py) | Photo upload and replacement with inline navigation | `message_new`, `message_event` |
27
27
  | [callback.py](callback.py) | A Callback API receiver using an ASGI factory | `message_new` |
28
+ | [donut_subscriptions.py](donut_subscriptions.py) | Typed Donut notifications and a private `/donut` command | Five `donut_subscription_*` events and `message_new` |
28
29
  | [background_result.py](background_result.py) | Managed computation, TypeHandler and event dispatch stopping | `message_new` |
29
30
 
30
31
  ## Echo bot
@@ -38,8 +39,9 @@ smallest example of `Application`, `BotSettings`, `MessageHandler` and `filters.
38
39
 
39
40
  ## Ordinary and inline keyboards
40
41
 
41
- The example constructs Pydantic `TextButton` and `CallbackButton` objects and uses
42
- `ButtonColor` enum members. Dictionary payloads are JSON encoded by the library.
42
+ The example constructs Pydantic `TextButton`, `CallbackButton`, `OpenLinkButton` and
43
+ `LocationButton` objects and uses `ButtonColor` enum members for text/callback colors.
44
+ Dictionary payloads are JSON encoded by the library; callback answers use `ShowSnackbar`.
43
45
  See the [keyboard API](../docs/development/keyboards.md) for model payloads and serialization.
44
46
 
45
47
  ```bash
@@ -49,10 +51,12 @@ uv run python examples/keyboards.py
49
51
  - `/keyboard` opens a persistent ordinary keyboard with **Помощь**, **О боте** and
50
52
  **Скрыть клавиатуру**. Text buttons are handled through `MessageHandler`; actions are
51
53
  selected by their JSON `payload`, independently of the displayed label. Hiding sends
52
- an empty ordinary keyboard. Send `/keyboard` to show it again.
54
+ an empty ordinary keyboard. Send `/keyboard` to show it again. A separate location
55
+ button opens VK's location chooser; the selected location is sent to the chat.
53
56
  - `/inline` sends a message with **Подтвердить** and **Отмена** callback buttons.
54
57
  `MessageEventHandler` acknowledges the click with a snackbar, then edits that message
55
58
  using `conversation_message_id`. Both buttons remain available for repeated use.
59
+ A separate link button opens the VK bot documentation.
56
60
 
57
61
  The example validates the payload namespace, structure and supported actions. Ordinary
58
62
  message payloads are JSON strings; event payloads can also be objects. In a conversation,
@@ -97,6 +101,23 @@ The receiver echoes text messages. `CallbackSettings` extends `BotSettings` with
97
101
  required secret and confirmation fields, and the ASGI lifespan manages the application's
98
102
  resources. See [Callback API](../README.md#callback-api) for delivery semantics.
99
103
 
104
+ ## Donut subscription events
105
+
106
+ Use the same environment configuration as the Callback receiver above. Enable VK Donut
107
+ in the community and select `donut_subscription_create`, `donut_subscription_prolonged`,
108
+ `donut_subscription_cancelled`, `donut_subscription_expired`,
109
+ `donut_subscription_price_changed` and `message_new` in Callback API settings.
110
+
111
+ ```bash
112
+ uv run --extra callback uvicorn examples.donut_subscriptions:create_app --factory
113
+ ```
114
+
115
+ Configure the HTTPS `/callback` URL, matching secret and confirmation code. Send `/donut`
116
+ privately to the community to see the latest received event for your user. Event handling
117
+ does not send unsolicited messages. The remembered event is process-local and is not
118
+ evidence of current paid access; no history is recovered after a restart. See the
119
+ [Donut guide](../docs/development/donut.md) for complete setup and the public API.
120
+
100
121
  ## Background calculation
101
122
 
102
123
  ```bash
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "python-vk-bot"
7
- version = "0.4.0"
7
+ version = "0.6.0"
8
8
  description = "An asynchronous framework for VK community bots."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.14"
@@ -6,7 +6,14 @@ from .bot import Bot
6
6
  from .callback import Callback
7
7
  from .context import Context
8
8
  from .errors import ApplicationHandlerStop
9
- from .handlers import CommandHandler, Handler, MessageEventHandler, MessageHandler, TypeHandler
9
+ from .handlers import (
10
+ CommandHandler,
11
+ DonutSubscriptionHandler,
12
+ Handler,
13
+ MessageEventHandler,
14
+ MessageHandler,
15
+ TypeHandler,
16
+ )
10
17
  from .long_poll import LongPoll
11
18
  from .models import (
12
19
  Attachment,
@@ -15,10 +22,15 @@ from .models import (
15
22
  ButtonType,
16
23
  CallbackButton,
17
24
  DocumentAttachment,
25
+ DonutSubscriptionEvent,
26
+ DonutSubscriptionEventType,
18
27
  Keyboard,
28
+ LocationButton,
19
29
  Message,
20
30
  MessageEvent,
31
+ OpenLinkButton,
21
32
  PhotoAttachment,
33
+ ShowSnackbar,
22
34
  TextButton,
23
35
  Update,
24
36
  User,
@@ -41,14 +53,20 @@ __all__ = [
41
53
  "CommandHandler",
42
54
  "Context",
43
55
  "DocumentAttachment",
56
+ "DonutSubscriptionEvent",
57
+ "DonutSubscriptionEventType",
58
+ "DonutSubscriptionHandler",
44
59
  "Handler",
45
60
  "Keyboard",
61
+ "LocationButton",
46
62
  "LongPoll",
47
63
  "Message",
48
64
  "MessageEvent",
49
65
  "MessageEventHandler",
50
66
  "MessageHandler",
67
+ "OpenLinkButton",
51
68
  "PhotoAttachment",
69
+ "ShowSnackbar",
52
70
  "TextButton",
53
71
  "TypeHandler",
54
72
  "Update",
@@ -22,7 +22,7 @@ type LifecycleHook = Callable[[Application], Awaitable[None]]
22
22
  logger = logging.getLogger(__name__)
23
23
 
24
24
 
25
- async def _await_owned[T](task: asyncio.Task[T]) -> T:
25
+ async def _await_owned[T](task: asyncio.Future[T]) -> T:
26
26
  """Finish owned cleanup even on repeated caller cancellation, then propagate it."""
27
27
  interrupted = False
28
28
  while not task.done():
@@ -76,6 +76,7 @@ class Application:
76
76
  self._tasks: dict[asyncio.Task[object], bool] = {}
77
77
  self._polling_task: asyncio.Task[None] | None = None
78
78
  self._polling_waiting = False
79
+ self._polling_cancel_requested = False
79
80
  self._consumer_task: asyncio.Task[None] | None = None
80
81
  self._processing_task: asyncio.Task[bool] | None = None
81
82
  self._finishing_handler: asyncio.Task[bool] | None = None
@@ -185,7 +186,7 @@ class Application:
185
186
  polling = self._polling_task
186
187
  if polling is not None:
187
188
  if not self._polling_waiting:
188
- polling.cancel()
189
+ self._cancel_polling(polling)
189
190
  await asyncio.gather(polling, return_exceptions=True)
190
191
  if self._finishing_handler is not None:
191
192
  await asyncio.gather(self._finishing_handler, return_exceptions=True)
@@ -470,6 +471,12 @@ class Application:
470
471
  if not self._running:
471
472
  break
472
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
+
473
480
  async def run_polling(self, *, wait: int = 25) -> None:
474
481
  """Run until stop/cancellation; own lifecycle, not the caller's event loop."""
475
482
  if self._polling_task is not None:
@@ -478,14 +485,17 @@ class Application:
478
485
  async with self:
479
486
  task = asyncio.create_task(self._poll(long_poll), name="vk-long-poll")
480
487
  self._polling_task = task
488
+ self._polling_cancel_requested = False
481
489
  try:
482
- await task
483
- except asyncio.CancelledError:
484
- current = asyncio.current_task()
485
- if current is not None and current.cancelling():
486
- raise
490
+ await asyncio.wait({task})
491
+ if not task.cancelled():
492
+ task.result()
487
493
  except Exception as error:
488
494
  await self._submit(_QueueItem(None, error=error))
489
495
  raise
490
496
  finally:
491
- 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
@@ -27,6 +27,7 @@ from .models.attachments import (
27
27
  PhotoAttachment,
28
28
  serialize_attachment,
29
29
  )
30
+ from .models.event_answers import ShowSnackbar
30
31
  from .models.messages import Keyboard, Message, MessagePage, User
31
32
  from .transport import FileInput, HTTPTransport, Parameter
32
33
 
@@ -336,15 +337,19 @@ class Bot:
336
337
  event_id: str,
337
338
  user_id: int,
338
339
  peer_id: int,
339
- event_data: Mapping[str, JsonValue] | None = None,
340
+ event_data: ShowSnackbar | Mapping[str, JsonValue] | None = None,
340
341
  ) -> bool:
342
+ if isinstance(event_data, ShowSnackbar):
343
+ serialized_event_data = event_data.model_dump_json(by_alias=True)
344
+ else:
345
+ serialized_event_data = json.dumps(dict(event_data)) if event_data is not None else None
341
346
  result = await self.request(
342
347
  "messages.sendMessageEventAnswer",
343
348
  {
344
349
  "event_id": event_id,
345
350
  "user_id": user_id,
346
351
  "peer_id": peer_id,
347
- "event_data": json.dumps(dict(event_data)) if event_data is not None else None,
352
+ "event_data": serialized_event_data,
348
353
  },
349
354
  )
350
355
  return _integer(result) == 1
@@ -14,8 +14,11 @@ class NetworkError(VKError):
14
14
 
15
15
 
16
16
  class HTTPError(VKError):
17
- def __init__(self, status_code: int) -> None:
17
+ """HTTP failure with an optional server-supplied delay in seconds."""
18
+
19
+ def __init__(self, status_code: int, *, retry_after: float | None = None) -> None:
18
20
  self.status_code = status_code
21
+ self.retry_after = retry_after
19
22
  super().__init__(f"VK HTTP request failed with status {status_code}")
20
23
 
21
24
 
@@ -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
+ )
@@ -1,11 +1,11 @@
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
4
  from typing import Protocol, TypeGuard
5
5
 
6
6
  from . import filters
7
7
  from .context import Context
8
- from .models import Update
8
+ from .models import DonutSubscriptionEventType, Update
9
9
 
10
10
  type HandlerCallback = Callable[[Update, Context], Awaitable[None]]
11
11
 
@@ -81,6 +81,39 @@ class MessageEventHandler(Handler):
81
81
  )
82
82
 
83
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
+
84
117
  class CommandHandler(MessageHandler):
85
118
  """Match an explicit /command token; no Telegram mention syntax is inferred."""
86
119
 
@@ -5,8 +5,17 @@ from .attachments import (
5
5
  PhotoAttachment,
6
6
  VideoAttachment,
7
7
  )
8
+ from .donut import DonutSubscriptionEvent, DonutSubscriptionEventType
9
+ from .event_answers import ShowSnackbar
8
10
  from .events import Update
9
- from .keyboards import ButtonColor, ButtonType, CallbackButton, TextButton
11
+ from .keyboards import (
12
+ ButtonColor,
13
+ ButtonType,
14
+ CallbackButton,
15
+ LocationButton,
16
+ OpenLinkButton,
17
+ TextButton,
18
+ )
10
19
  from .messages import Coordinates, Geo, Keyboard, Message, MessageEvent, User
11
20
 
12
21
  __all__ = [
@@ -17,11 +26,16 @@ __all__ = [
17
26
  "CallbackButton",
18
27
  "Coordinates",
19
28
  "DocumentAttachment",
29
+ "DonutSubscriptionEvent",
30
+ "DonutSubscriptionEventType",
20
31
  "Geo",
21
32
  "Keyboard",
33
+ "LocationButton",
22
34
  "Message",
23
35
  "MessageEvent",
36
+ "OpenLinkButton",
24
37
  "PhotoAttachment",
38
+ "ShowSnackbar",
25
39
  "TextButton",
26
40
  "Update",
27
41
  "User",
@@ -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)
@@ -0,0 +1,14 @@
1
+ """Outgoing actions for replies to VK message_event callbacks."""
2
+
3
+ from typing import Literal
4
+
5
+ from pydantic import BaseModel, ConfigDict, Field
6
+
7
+
8
+ class ShowSnackbar(BaseModel):
9
+ """Show a notification containing at most 90 characters."""
10
+
11
+ model_config = ConfigDict(extra="forbid", validate_assignment=True, hide_input_in_errors=True)
12
+
13
+ type: Literal["show_snackbar"] = "show_snackbar"
14
+ text: str = Field(max_length=90, repr=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
@@ -30,18 +30,18 @@ class ButtonType(StrEnum):
30
30
 
31
31
  TEXT = "text"
32
32
  CALLBACK = "callback"
33
+ OPEN_LINK = "open_link"
34
+ LOCATION = "location"
33
35
 
34
36
 
35
- class _LabeledButton(BaseModel):
37
+ class _Button(BaseModel):
36
38
  model_config = ConfigDict(
37
39
  extra="forbid", validate_assignment=True, hide_input_in_errors=True, allow_inf_nan=False
38
40
  )
39
41
 
40
- label: str = Field(repr=False)
41
42
  payload: dict[str, JsonValue] | SerializeAsAny[BaseModel] | str | None = Field(
42
43
  default=None, repr=False
43
44
  )
44
- color: ButtonColor = ButtonColor.SECONDARY
45
45
 
46
46
  @field_serializer("payload", when_used="json")
47
47
  def serialize_payload(self, value: dict[str, JsonValue] | BaseModel | str | None) -> str | None:
@@ -63,6 +63,11 @@ class _LabeledButton(BaseModel):
63
63
  return button
64
64
 
65
65
 
66
+ class _LabeledButton(_Button):
67
+ label: str = Field(repr=False)
68
+ color: ButtonColor = ButtonColor.SECONDARY
69
+
70
+
66
71
  class TextButton(_LabeledButton):
67
72
  """Send the label and optional payload as a message, handled by MessageHandler."""
68
73
 
@@ -75,4 +80,20 @@ class CallbackButton(_LabeledButton):
75
80
  type: Literal[ButtonType.CALLBACK] = ButtonType.CALLBACK
76
81
 
77
82
 
78
- type TypedButton = Annotated[TextButton | CallbackButton, Field(discriminator="type")]
83
+ class OpenLinkButton(_Button):
84
+ """Open a URL using VK's link action, without a configurable color."""
85
+
86
+ type: Literal[ButtonType.OPEN_LINK] = ButtonType.OPEN_LINK
87
+ label: str = Field(repr=False)
88
+ link: str = Field(repr=False)
89
+
90
+
91
+ class LocationButton(_Button):
92
+ """Let the user choose a location and send it as a message with geo data."""
93
+
94
+ type: Literal[ButtonType.LOCATION] = ButtonType.LOCATION
95
+
96
+
97
+ type TypedButton = Annotated[
98
+ TextButton | CallbackButton | OpenLinkButton | LocationButton, Field(discriminator="type")
99
+ ]
@@ -2,9 +2,12 @@
2
2
 
3
3
  import asyncio
4
4
  import logging
5
+ import math
5
6
  import re
6
7
  from collections.abc import Mapping
7
8
  from contextlib import suppress
9
+ from datetime import UTC, datetime
10
+ from email.utils import parsedate_to_datetime
8
11
  from pathlib import Path
9
12
  from types import TracebackType
10
13
  from typing import BinaryIO, Literal, Self, cast
@@ -29,6 +32,53 @@ type Parameter = str | int | float | bool | None
29
32
  type FileInput = bytes | Path | BinaryIO
30
33
 
31
34
 
35
+ _HTTP_DATE = re.compile(
36
+ r"(?:"
37
+ r"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), [0-9]{2} "
38
+ r"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]{4} "
39
+ r"[0-9]{2}:[0-9]{2}:[0-9]{2} GMT"
40
+ r"|(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), "
41
+ r"[0-9]{2}-(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-[0-9]{2} "
42
+ r"[0-9]{2}:[0-9]{2}:[0-9]{2} GMT"
43
+ r"|(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) "
44
+ r"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (?:[0-9]{2}| [0-9]) "
45
+ r"[0-9]{2}:[0-9]{2}:[0-9]{2} [0-9]{4}"
46
+ r")"
47
+ )
48
+
49
+
50
+ def _parse_retry_after(value: str | None) -> float | None:
51
+ """Parse RFC 9110 seconds or HTTP-date without retaining server data."""
52
+ if value is None:
53
+ return None
54
+ value = value.strip(" \t")
55
+ try:
56
+ if re.fullmatch(r"[0-9]+", value):
57
+ seconds = float(value)
58
+ elif _HTTP_DATE.fullmatch(value):
59
+ now = datetime.now(UTC)
60
+ deadline = parsedate_to_datetime(value)
61
+ if deadline.tzinfo is None:
62
+ # The obsolete asctime format has no zone; HTTP defines it as UTC.
63
+ deadline = deadline.replace(tzinfo=UTC)
64
+ if "-" in value:
65
+ # RFC 850's two-digit year is interpreted relative to the current century.
66
+ year = now.year // 100 * 100 + deadline.year % 100
67
+ if year > now.year + 50:
68
+ year -= 100
69
+ else:
70
+ # The email parser applies a century heuristic even to four-digit years.
71
+ parts = value.split()
72
+ year = int(parts[3] if "," in value else parts[-1])
73
+ deadline = deadline.replace(year=year)
74
+ seconds = max(0.0, (deadline - now).total_seconds())
75
+ else:
76
+ return None
77
+ except ValueError, TypeError, OverflowError:
78
+ return None
79
+ return seconds if math.isfinite(seconds) else None
80
+
81
+
32
82
  def _read_upload(source: Path | BinaryIO) -> bytes:
33
83
  """Read in a worker; Path.read_bytes closes its own file even on failure."""
34
84
  try:
@@ -125,7 +175,10 @@ class HTTPTransport:
125
175
  except httpx.RequestError:
126
176
  raise NetworkError("VK HTTP request could not complete") from None
127
177
  if not response.is_success:
128
- raise HTTPError(response.status_code)
178
+ raise HTTPError(
179
+ response.status_code,
180
+ retry_after=_parse_retry_after(response.headers.get("Retry-After")),
181
+ )
129
182
  try:
130
183
  return cast(JsonValue, response.json())
131
184
  except ValueError:
File without changes
File without changes