python-vk-bot 0.5.0__py3-none-any.whl → 0.7.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
@@ -25,9 +25,12 @@ from .models import (
25
25
  DonutSubscriptionEvent,
26
26
  DonutSubscriptionEventType,
27
27
  Keyboard,
28
+ LocationButton,
28
29
  Message,
29
30
  MessageEvent,
31
+ OpenLinkButton,
30
32
  PhotoAttachment,
33
+ ShowSnackbar,
31
34
  TextButton,
32
35
  Update,
33
36
  User,
@@ -55,12 +58,15 @@ __all__ = [
55
58
  "DonutSubscriptionHandler",
56
59
  "Handler",
57
60
  "Keyboard",
61
+ "LocationButton",
58
62
  "LongPoll",
59
63
  "Message",
60
64
  "MessageEvent",
61
65
  "MessageEventHandler",
62
66
  "MessageHandler",
67
+ "OpenLinkButton",
63
68
  "PhotoAttachment",
69
+ "ShowSnackbar",
64
70
  "TextButton",
65
71
  "TypeHandler",
66
72
  "Update",
python_vk_bot/bot.py CHANGED
@@ -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
python_vk_bot/errors.py CHANGED
@@ -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
 
@@ -0,0 +1,12 @@
1
+ """Keyboard limits for VK API 5.199; see docs/development/api-compatibility.md."""
2
+
3
+ from typing import Final
4
+
5
+ MAX_INLINE_BUTTONS: Final[int] = 10
6
+ MAX_REPLY_BUTTONS: Final[int] = 40
7
+ MAX_BUTTONS_PER_ROW: Final[int] = 5
8
+ MAX_INLINE_ROWS: Final[int] = 6
9
+ MAX_REPLY_ROWS: Final[int] = 10
10
+ MAX_BUTTON_LABEL_LENGTH: Final[int] = 40
11
+ MAX_LOCATION_ROW_BUTTONS: Final[int] = 2
12
+ MAX_VKPAY_ROW_BUTTONS: Final[int] = 1
@@ -6,8 +6,16 @@ from .attachments import (
6
6
  VideoAttachment,
7
7
  )
8
8
  from .donut import DonutSubscriptionEvent, DonutSubscriptionEventType
9
+ from .event_answers import ShowSnackbar
9
10
  from .events import Update
10
- from .keyboards import ButtonColor, ButtonType, CallbackButton, TextButton
11
+ from .keyboards import (
12
+ ButtonColor,
13
+ ButtonType,
14
+ CallbackButton,
15
+ LocationButton,
16
+ OpenLinkButton,
17
+ TextButton,
18
+ )
11
19
  from .messages import Coordinates, Geo, Keyboard, Message, MessageEvent, User
12
20
 
13
21
  __all__ = [
@@ -22,9 +30,12 @@ __all__ = [
22
30
  "DonutSubscriptionEventType",
23
31
  "Geo",
24
32
  "Keyboard",
33
+ "LocationButton",
25
34
  "Message",
26
35
  "MessageEvent",
36
+ "OpenLinkButton",
27
37
  "PhotoAttachment",
38
+ "ShowSnackbar",
28
39
  "TextButton",
29
40
  "Update",
30
41
  "User",
@@ -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)
@@ -15,6 +15,8 @@ from pydantic import (
15
15
  model_serializer,
16
16
  )
17
17
 
18
+ from python_vk_bot.limits import MAX_BUTTON_LABEL_LENGTH
19
+
18
20
 
19
21
  class ButtonColor(StrEnum):
20
22
  """Colors documented by the VK keyboard guide."""
@@ -30,18 +32,18 @@ class ButtonType(StrEnum):
30
32
 
31
33
  TEXT = "text"
32
34
  CALLBACK = "callback"
35
+ OPEN_LINK = "open_link"
36
+ LOCATION = "location"
33
37
 
34
38
 
35
- class _LabeledButton(BaseModel):
39
+ class _Button(BaseModel):
36
40
  model_config = ConfigDict(
37
41
  extra="forbid", validate_assignment=True, hide_input_in_errors=True, allow_inf_nan=False
38
42
  )
39
43
 
40
- label: str = Field(repr=False)
41
44
  payload: dict[str, JsonValue] | SerializeAsAny[BaseModel] | str | None = Field(
42
45
  default=None, repr=False
43
46
  )
44
- color: ButtonColor = ButtonColor.SECONDARY
45
47
 
46
48
  @field_serializer("payload", when_used="json")
47
49
  def serialize_payload(self, value: dict[str, JsonValue] | BaseModel | str | None) -> str | None:
@@ -63,6 +65,11 @@ class _LabeledButton(BaseModel):
63
65
  return button
64
66
 
65
67
 
68
+ class _LabeledButton(_Button):
69
+ label: str = Field(repr=False, max_length=MAX_BUTTON_LABEL_LENGTH)
70
+ color: ButtonColor = ButtonColor.SECONDARY
71
+
72
+
66
73
  class TextButton(_LabeledButton):
67
74
  """Send the label and optional payload as a message, handled by MessageHandler."""
68
75
 
@@ -75,4 +82,20 @@ class CallbackButton(_LabeledButton):
75
82
  type: Literal[ButtonType.CALLBACK] = ButtonType.CALLBACK
76
83
 
77
84
 
78
- type TypedButton = Annotated[TextButton | CallbackButton, Field(discriminator="type")]
85
+ class OpenLinkButton(_Button):
86
+ """Open a URL using VK's link action, without a configurable color."""
87
+
88
+ type: Literal[ButtonType.OPEN_LINK] = ButtonType.OPEN_LINK
89
+ label: str = Field(repr=False, max_length=MAX_BUTTON_LABEL_LENGTH)
90
+ link: str = Field(repr=False)
91
+
92
+
93
+ class LocationButton(_Button):
94
+ """Let the user choose a location and send it as a message with geo data."""
95
+
96
+ type: Literal[ButtonType.LOCATION] = ButtonType.LOCATION
97
+
98
+
99
+ type TypedButton = Annotated[
100
+ TextButton | CallbackButton | OpenLinkButton | LocationButton, Field(discriminator="type")
101
+ ]
@@ -1,6 +1,26 @@
1
1
  """The message fields used by this framework, not the entire VK schema."""
2
2
 
3
- from pydantic import Field, JsonValue
3
+ from typing import Self
4
+
5
+ from pydantic import (
6
+ ConfigDict,
7
+ Field,
8
+ JsonValue,
9
+ SerializerFunctionWrapHandler,
10
+ model_serializer,
11
+ model_validator,
12
+ )
13
+
14
+ from python_vk_bot.limits import (
15
+ MAX_BUTTON_LABEL_LENGTH,
16
+ MAX_BUTTONS_PER_ROW,
17
+ MAX_INLINE_BUTTONS,
18
+ MAX_INLINE_ROWS,
19
+ MAX_LOCATION_ROW_BUTTONS,
20
+ MAX_REPLY_BUTTONS,
21
+ MAX_REPLY_ROWS,
22
+ MAX_VKPAY_ROW_BUTTONS,
23
+ )
4
24
 
5
25
  from .attachments import Attachment, parse_attachment
6
26
  from .base import VKModel
@@ -54,10 +74,58 @@ class User(VKModel):
54
74
 
55
75
 
56
76
  class Keyboard(VKModel):
77
+ model_config = ConfigDict(validate_assignment=True)
78
+
57
79
  buttons: list[list[TypedButton | dict[str, JsonValue]]]
58
80
  one_time: bool = False
59
81
  inline: bool = False
60
82
 
83
+ @model_validator(mode="after")
84
+ def validate_limits(self) -> Self:
85
+ self._validate_limits()
86
+ return self
87
+
88
+ def _validate_limits(self) -> None:
89
+ """Validate dimensions and known labels without exposing button contents."""
90
+ max_rows = MAX_INLINE_ROWS if self.inline else MAX_REPLY_ROWS
91
+ max_buttons = MAX_INLINE_BUTTONS if self.inline else MAX_REPLY_BUTTONS
92
+ self._check_limit("Keyboard rows", len(self.buttons), max_rows)
93
+ self._check_limit("Keyboard buttons", sum(map(len, self.buttons)), max_buttons)
94
+ for row_number, row in enumerate(self.buttons, start=1):
95
+ row_limit = MAX_BUTTONS_PER_ROW
96
+ for button_number, button in enumerate(row, start=1):
97
+ if isinstance(button, dict):
98
+ action = button.get("action")
99
+ if not isinstance(action, dict):
100
+ continue
101
+ kind = action.get("type")
102
+ label = action.get("label")
103
+ else:
104
+ kind = button.type
105
+ label = getattr(button, "label", None)
106
+ if kind == "location":
107
+ row_limit = min(row_limit, MAX_LOCATION_ROW_BUTTONS)
108
+ elif kind == "vkpay":
109
+ row_limit = min(row_limit, MAX_VKPAY_ROW_BUTTONS)
110
+ if kind in ("text", "callback", "open_link") and isinstance(label, str):
111
+ self._check_limit(
112
+ f"Row {row_number} button {button_number} label characters",
113
+ len(label),
114
+ MAX_BUTTON_LABEL_LENGTH,
115
+ )
116
+ self._check_limit(f"Row {row_number} buttons", len(row), row_limit)
117
+
118
+ @staticmethod
119
+ def _check_limit(subject: str, actual: int, maximum: int) -> None:
120
+ if actual > maximum:
121
+ raise ValueError(f"{subject}: maximum {maximum}, got {actual}")
122
+
123
+ @model_serializer(mode="wrap", when_used="json")
124
+ def serialize_keyboard(self, handler: SerializerFunctionWrapHandler) -> dict[str, JsonValue]:
125
+ # Nested lists and raw dictionaries can change without assignment validation.
126
+ self._validate_limits()
127
+ return handler(self)
128
+
61
129
 
62
130
  class MessagePage(VKModel):
63
131
  count: int
@@ -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:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-vk-bot
3
- Version: 0.5.0
3
+ Version: 0.7.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,7 +71,7 @@ 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 |
@@ -1,28 +1,30 @@
1
- python_vk_bot/__init__.py,sha256=z13dYqi5v02yff21dmb0fIfDn6lpjOumFA1zEASux90,1461
1
+ python_vk_bot/__init__.py,sha256=H-6FJF2oBDG-AjBZN8SpSXOfy9dVA7ReDekjrnq53Rs,1583
2
2
  python_vk_bot/_config.py,sha256=Rju-sjCKAfk70ajQbpPMzOuefBIjtgF8tKjOuSYo0AE,744
3
3
  python_vk_bot/application.py,sha256=dkHR3F6geN8VhpnnfCb7aSEL1k8GCo-iA9nSZRoZCC4,20361
4
- python_vk_bot/bot.py,sha256=zZ_lKe6Ac5eREm0gDV02XuUkIgcdU3pki4lsJLrs4NA,13379
4
+ python_vk_bot/bot.py,sha256=Ewt7ebW00rklpAXyZkiBcnZnKdzHwABD5mPAz7scqw8,13640
5
5
  python_vk_bot/callback.py,sha256=9j11jtl4rpTnfUThvOf2g6kb7wYQXAQerHbuk3IYw3o,4726
6
6
  python_vk_bot/context.py,sha256=yFPT1rXCUXSfbyPCu4y2kmWv2NI_XlZ2zIbzTpeWG90,504
7
- python_vk_bot/errors.py,sha256=brqC5zxQgXOBRNPMOU230CPFL0rFZi_tZBr3mua0wBA,1393
7
+ python_vk_bot/errors.py,sha256=N0bBnNqc_yHUIGxQ3fTwGLk7V03nn5FLQwcpBSsA7dQ,1544
8
8
  python_vk_bot/filters.py,sha256=YuZQwSpcMI2N56SnEggx_lvImiISSF_QJ52QIfGe8Uo,2059
9
9
  python_vk_bot/handlers.py,sha256=MXGGD7FFMugrKLazkvUvSPPIxQXfJUgoj3-xFGFbKsw,4503
10
+ python_vk_bot/limits.py,sha256=wE5x8R5ZO0eQqlJhBvoNN99bJOi6hF-f5T3-q3ljsE4,401
10
11
  python_vk_bot/long_poll.py,sha256=rmAxflq0E3H-tMDybQ7fBf1cKsJQFnaU4VbyQS3BSw4,3777
11
12
  python_vk_bot/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
13
  python_vk_bot/queues.py,sha256=9OCfYBpOpcJBbW-7TwsIb18raJN2pueZbXoJUgu7MOc,2861
13
14
  python_vk_bot/settings.py,sha256=JcbDihGRJGRGvBBSeB3j_LPaoX7dkPHfh-WviKQCrwk,915
14
- python_vk_bot/transport.py,sha256=eVsq0_brPXQ0Yk1ngMhiWHD9Z6S5Y1NhH193jbMTkmE,9812
15
+ python_vk_bot/transport.py,sha256=kdf9NRpZ2KM2yP2IGNAASfJagGvJOcgoEPpj-V9nudM,11936
15
16
  python_vk_bot/.agents/skills/telegram-to-vk/SKILL.md,sha256=WMrNoxLkhhlu8wnS9rFpZi3OlwBlVNHCYFSNtKmkJzM,2828
16
17
  python_vk_bot/.agents/skills/telegram-to-vk/references/migration-mapping.md,sha256=KFxmCQyKbUK7Z0JuS39FocyoFdtnslLLp9j2pNeJAds,9019
17
- python_vk_bot/models/__init__.py,sha256=eAdbM08JcoYv6JPrdorVC6DvEfxhgp-5h9pXFa3B7iQ,772
18
+ python_vk_bot/models/__init__.py,sha256=exCkuHNIqRGVDjinpi0afpdgEvoPbz4JWeQzimw7c0w,937
18
19
  python_vk_bot/models/api.py,sha256=jY9pedj7TZQkt9bRROUo8rMrO2PyAO7DPJz7E1YphYs,1626
19
20
  python_vk_bot/models/attachments.py,sha256=5JWHv37BtSzRI9j_z_yAHToJ61EyBxqRjYp7Y7rP-1o,3887
20
21
  python_vk_bot/models/base.py,sha256=LYcbevtU8jq5QVLo8b1mOv70RzgEYjPtTmhMMe-JN3A,249
21
22
  python_vk_bot/models/donut.py,sha256=qV9OyjDbmTi2UJqvzfXOL6LqYMxZvFwJo2yI1dcLSi0,1373
23
+ python_vk_bot/models/event_answers.py,sha256=BApsLwOySfcr3aLUazQo8rryEsitT3jaEGTQpuVIk14,445
22
24
  python_vk_bot/models/events.py,sha256=7JPZykMTRy8hiMKsX45ZZbwGiK8-sZFtzXZqprYxK18,2826
23
- python_vk_bot/models/keyboards.py,sha256=ZtwBLSbd-DROuohl9mM0Ui4i7FRUzXVePnfDnmkYzvc,2395
24
- python_vk_bot/models/messages.py,sha256=WAUsa7VMDNl0xK2LXa91kg6RQsWBXoQATI1aAMDiHLU,1543
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,,
25
+ python_vk_bot/models/keyboards.py,sha256=p-Z7EGL5e-rOPoYVEg_uctgwSMmCVk-Z1Pgl1nZ32RY,3062
26
+ python_vk_bot/models/messages.py,sha256=kuQEc4iLZJvhzpKJAGvRcERJdASWYQpj0OUwNdjnn10,4215
27
+ python_vk_bot-0.7.0.dist-info/METADATA,sha256=ejTVOHazyzFMgg7_mRW9vFx7bG52Jeu9gcksJsYU6_E,13340
28
+ python_vk_bot-0.7.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
29
+ python_vk_bot-0.7.0.dist-info/licenses/LICENSE,sha256=F-35ycqPcYW243OjxMHCggr_AHQgZLX2zvtZgobVEvo,1072
30
+ python_vk_bot-0.7.0.dist-info/RECORD,,