python-vk-bot 0.4.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
@@ -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,6 +22,8 @@ from .models import (
15
22
  ButtonType,
16
23
  CallbackButton,
17
24
  DocumentAttachment,
25
+ DonutSubscriptionEvent,
26
+ DonutSubscriptionEventType,
18
27
  Keyboard,
19
28
  Message,
20
29
  MessageEvent,
@@ -41,6 +50,9 @@ __all__ = [
41
50
  "CommandHandler",
42
51
  "Context",
43
52
  "DocumentAttachment",
53
+ "DonutSubscriptionEvent",
54
+ "DonutSubscriptionEventType",
55
+ "DonutSubscriptionHandler",
44
56
  "Handler",
45
57
  "Keyboard",
46
58
  "LongPoll",
@@ -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
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,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,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
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-vk-bot
3
- Version: 0.4.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
@@ -75,6 +75,7 @@ See the [examples guide](examples/README.md) for setup, required events and run
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
@@ -1,12 +1,12 @@
1
- python_vk_bot/__init__.py,sha256=gPIWyuwSePq-smJP_qS00CRMR0M0TAUGrl3HE6Bav20,1250
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=mn1L8d85CRrmtfIrtz-i893z3GaK98Z4SR-0Fxilm3w,19865
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
6
  python_vk_bot/context.py,sha256=yFPT1rXCUXSfbyPCu4y2kmWv2NI_XlZ2zIbzTpeWG90,504
7
7
  python_vk_bot/errors.py,sha256=brqC5zxQgXOBRNPMOU230CPFL0rFZi_tZBr3mua0wBA,1393
8
- python_vk_bot/filters.py,sha256=5fpOdxTZvFmrgokWUvYj1nowCWvPlLt9EUhRmB-0HVg,1285
9
- python_vk_bot/handlers.py,sha256=UkGx773OdDM-F7myxQNjSMRUYyZQQpwvj4Lznc1csvM,3221
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
12
  python_vk_bot/queues.py,sha256=9OCfYBpOpcJBbW-7TwsIb18raJN2pueZbXoJUgu7MOc,2861
@@ -14,14 +14,15 @@ python_vk_bot/settings.py,sha256=JcbDihGRJGRGvBBSeB3j_LPaoX7dkPHfh-WviKQCrwk,915
14
14
  python_vk_bot/transport.py,sha256=eVsq0_brPXQ0Yk1ngMhiWHD9Z6S5Y1NhH193jbMTkmE,9812
15
15
  python_vk_bot/.agents/skills/telegram-to-vk/SKILL.md,sha256=WMrNoxLkhhlu8wnS9rFpZi3OlwBlVNHCYFSNtKmkJzM,2828
16
16
  python_vk_bot/.agents/skills/telegram-to-vk/references/migration-mapping.md,sha256=KFxmCQyKbUK7Z0JuS39FocyoFdtnslLLp9j2pNeJAds,9019
17
- python_vk_bot/models/__init__.py,sha256=znIpo8F8TrxEGxeEkAkA-M5qp6aqH-NPRNdblgOBBsk,638
17
+ python_vk_bot/models/__init__.py,sha256=eAdbM08JcoYv6JPrdorVC6DvEfxhgp-5h9pXFa3B7iQ,772
18
18
  python_vk_bot/models/api.py,sha256=jY9pedj7TZQkt9bRROUo8rMrO2PyAO7DPJz7E1YphYs,1626
19
19
  python_vk_bot/models/attachments.py,sha256=5JWHv37BtSzRI9j_z_yAHToJ61EyBxqRjYp7Y7rP-1o,3887
20
20
  python_vk_bot/models/base.py,sha256=LYcbevtU8jq5QVLo8b1mOv70RzgEYjPtTmhMMe-JN3A,249
21
- 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
22
23
  python_vk_bot/models/keyboards.py,sha256=ZtwBLSbd-DROuohl9mM0Ui4i7FRUzXVePnfDnmkYzvc,2395
23
24
  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,,
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,,