python-vk-bot 0.6.0__tar.gz → 0.8.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 (35) hide show
  1. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/CHANGELOG.md +22 -1
  2. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/PKG-INFO +42 -3
  3. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/README.md +41 -2
  4. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/pyproject.toml +1 -1
  5. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/__init__.py +2 -0
  6. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/bot.py +101 -11
  7. python_vk_bot-0.8.0/python_vk_bot/limits.py +12 -0
  8. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/models/__init__.py +2 -0
  9. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/models/api.py +28 -0
  10. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/models/keyboards.py +4 -2
  11. python_vk_bot-0.8.0/python_vk_bot/models/messages.py +132 -0
  12. python_vk_bot-0.6.0/python_vk_bot/models/messages.py +0 -64
  13. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/.gitignore +0 -0
  14. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/LICENSE +0 -0
  15. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/docs/decisions/README.md +0 -0
  16. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/examples/README.md +0 -0
  17. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/.agents/skills/telegram-to-vk/SKILL.md +0 -0
  18. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/.agents/skills/telegram-to-vk/references/migration-mapping.md +0 -0
  19. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/_config.py +0 -0
  20. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/application.py +0 -0
  21. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/callback.py +0 -0
  22. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/context.py +0 -0
  23. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/errors.py +0 -0
  24. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/filters.py +0 -0
  25. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/handlers.py +0 -0
  26. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/long_poll.py +0 -0
  27. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/models/attachments.py +0 -0
  28. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/models/base.py +0 -0
  29. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/models/donut.py +0 -0
  30. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/models/event_answers.py +0 -0
  31. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/models/events.py +0 -0
  32. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/py.typed +0 -0
  33. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/queues.py +0 -0
  34. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/settings.py +0 -0
  35. {python_vk_bot-0.6.0 → python_vk_bot-0.8.0}/python_vk_bot/transport.py +0 -0
@@ -4,7 +4,28 @@ All notable changes will be documented here, following Keep a Changelog.
4
4
 
5
5
  ## Unreleased
6
6
 
7
- -
7
+ ## 0.8.0 - 2026-11-26
8
+
9
+ ### Added
10
+
11
+ - `Bot.send_message_and_get_ids` and `Bot.forward_message_and_get_ids` return a
12
+ typed `MessageSendResult` with recipient and conversation-scoped message IDs.
13
+ An unavailable global message ID is represented by `None`. See the
14
+ [send, edit and forwarding examples](README.md#send-edit-and-forward-using-conversation-ids).
15
+
16
+ ## 0.7.0 - 2026-11-16
17
+
18
+ ### Added
19
+
20
+ - Keyboard limit constants in `python_vk_bot.limits`.
21
+
22
+ ### Changed
23
+
24
+ - **Breaking:** keyboards reject excessive button/row counts, location/vkpay row
25
+ sizes and known labels over 40 characters at validation and JSON serialization.
26
+ Typed text/callback/open-link labels also validate assignments. Open-link label
27
+ length is a library policy; URL length is unchanged. See the
28
+ [validation and migration guidance](docs/development/keyboards.md#references-and-limits).
8
29
 
9
30
  ## 0.6.0 - 2026-11-06
10
31
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-vk-bot
3
- Version: 0.6.0
3
+ Version: 0.8.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
@@ -194,10 +194,49 @@ connection data. `Bot.request(method, parameters)` exposes raw JSON results for
194
194
  VK methods; nested request parameters must be JSON encoded explicitly.
195
195
 
196
196
  Messages use `peer_id`; `Message` exposes both `id` and `conversation_message_id`.
197
- `send_message` returns an integer message ID and accepts an optional nonzero int32
198
- `random_id`. Sends are never retried automatically. `edit_message` accepts exactly one
197
+ `send_message` returns an integer, which may be `0` for a community send to a chat,
198
+ and accepts an optional nonzero int32 `random_id`. Sends are never retried automatically.
199
+ `edit_message` accepts exactly one
199
200
  message identifier and maps `conversation_message_id` to VK's `cmid` parameter.
200
201
 
202
+ ### Send, edit and forward using conversation IDs
203
+
204
+ `send_message_and_get_ids` returns a `MessageSendResult`, also exported from
205
+ `python_vk_bot.models`. Its `peer_id` identifies the recipient;
206
+ `conversation_message_id` is positive and belongs to that peer. The separate global
207
+ `message_id` is positive when available, or `None` when VK returns `0`.
208
+
209
+ ```python
210
+ async with Bot(token) as bot:
211
+ sent = await bot.send_message_and_get_ids(peer_id, "Original text", random_id=12345)
212
+ await bot.edit_message(
213
+ sent.peer_id,
214
+ "Updated text",
215
+ conversation_message_id=sent.conversation_message_id,
216
+ )
217
+ forwarded = await bot.forward_message_and_get_ids(
218
+ destination_peer_id,
219
+ from_peer_id=sent.peer_id,
220
+ conversation_message_id=sent.conversation_message_id,
221
+ random_id=12346,
222
+ )
223
+ # forwarded IDs identify the new message in destination_peer_id.
224
+ ```
225
+
226
+ The send method supports `text`, `keyboard`, `attachment`, `dont_parse_links` and
227
+ `random_id`. The forwarding method forwards one message by its source peer and
228
+ conversation ID, with optional `random_id`; it does not add accompanying content.
229
+ Both use `peer_ids` with one recipient and require one matching result with usable
230
+ conversation identifiers. Recipient errors raise `APIError` (`RateLimitError` for
231
+ code 6); malformed results raise `InvalidResponseError`. A response-validation or
232
+ network failure can occur after delivery: neither method sends a fallback or retries.
233
+ To control deduplication when retrying, retain and reuse an explicit `random_id`.
234
+
235
+ These public methods and the three result fields follow the project's alpha API
236
+ stability policy: changes are documented in the changelog; unknown VK response
237
+ fields are retained as extras but are not stable library-defined fields.
238
+ `forward_message(peer_id, message, random_id=...)` returns an integer result.
239
+
201
240
  ## Callback API
202
241
 
203
242
  The [Callback example](examples/callback.py) extends the same base settings with its
@@ -168,10 +168,49 @@ connection data. `Bot.request(method, parameters)` exposes raw JSON results for
168
168
  VK methods; nested request parameters must be JSON encoded explicitly.
169
169
 
170
170
  Messages use `peer_id`; `Message` exposes both `id` and `conversation_message_id`.
171
- `send_message` returns an integer message ID and accepts an optional nonzero int32
172
- `random_id`. Sends are never retried automatically. `edit_message` accepts exactly one
171
+ `send_message` returns an integer, which may be `0` for a community send to a chat,
172
+ and accepts an optional nonzero int32 `random_id`. Sends are never retried automatically.
173
+ `edit_message` accepts exactly one
173
174
  message identifier and maps `conversation_message_id` to VK's `cmid` parameter.
174
175
 
176
+ ### Send, edit and forward using conversation IDs
177
+
178
+ `send_message_and_get_ids` returns a `MessageSendResult`, also exported from
179
+ `python_vk_bot.models`. Its `peer_id` identifies the recipient;
180
+ `conversation_message_id` is positive and belongs to that peer. The separate global
181
+ `message_id` is positive when available, or `None` when VK returns `0`.
182
+
183
+ ```python
184
+ async with Bot(token) as bot:
185
+ sent = await bot.send_message_and_get_ids(peer_id, "Original text", random_id=12345)
186
+ await bot.edit_message(
187
+ sent.peer_id,
188
+ "Updated text",
189
+ conversation_message_id=sent.conversation_message_id,
190
+ )
191
+ forwarded = await bot.forward_message_and_get_ids(
192
+ destination_peer_id,
193
+ from_peer_id=sent.peer_id,
194
+ conversation_message_id=sent.conversation_message_id,
195
+ random_id=12346,
196
+ )
197
+ # forwarded IDs identify the new message in destination_peer_id.
198
+ ```
199
+
200
+ The send method supports `text`, `keyboard`, `attachment`, `dont_parse_links` and
201
+ `random_id`. The forwarding method forwards one message by its source peer and
202
+ conversation ID, with optional `random_id`; it does not add accompanying content.
203
+ Both use `peer_ids` with one recipient and require one matching result with usable
204
+ conversation identifiers. Recipient errors raise `APIError` (`RateLimitError` for
205
+ code 6); malformed results raise `InvalidResponseError`. A response-validation or
206
+ network failure can occur after delivery: neither method sends a fallback or retries.
207
+ To control deduplication when retrying, retain and reuse an explicit `random_id`.
208
+
209
+ These public methods and the three result fields follow the project's alpha API
210
+ stability policy: changes are documented in the changelog; unknown VK response
211
+ fields are retained as extras but are not stable library-defined fields.
212
+ `forward_message(peer_id, message, random_id=...)` returns an integer result.
213
+
175
214
  ## Callback API
176
215
 
177
216
  The [Callback example](examples/callback.py) extends the same base settings with its
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "python-vk-bot"
7
- version = "0.6.0"
7
+ version = "0.8.0"
8
8
  description = "An asynchronous framework for VK community bots."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.14"
@@ -28,6 +28,7 @@ from .models import (
28
28
  LocationButton,
29
29
  Message,
30
30
  MessageEvent,
31
+ MessageSendResult,
31
32
  OpenLinkButton,
32
33
  PhotoAttachment,
33
34
  ShowSnackbar,
@@ -64,6 +65,7 @@ __all__ = [
64
65
  "MessageEvent",
65
66
  "MessageEventHandler",
66
67
  "MessageHandler",
68
+ "MessageSendResult",
67
69
  "OpenLinkButton",
68
70
  "PhotoAttachment",
69
71
  "ShowSnackbar",
@@ -16,8 +16,10 @@ from .models.api import (
16
16
  DocumentUpload,
17
17
  LongPollServer,
18
18
  MessageDeleteResult,
19
+ MessageSendResult,
19
20
  PhotoUpload,
20
21
  UploadServer,
22
+ _MessageSendResponse,
21
23
  )
22
24
  from .models.attachments import (
23
25
  Attachment,
@@ -62,6 +64,52 @@ def _message_identifier(message_id: int | None, conversation_message_id: int | N
62
64
  return identifier
63
65
 
64
66
 
67
+ def _send_parameters(
68
+ text: str,
69
+ random_id: int | None,
70
+ keyboard: Keyboard | None,
71
+ attachment: str | Attachment | None,
72
+ dont_parse_links: bool,
73
+ ) -> dict[str, Parameter]:
74
+ attachment_id = serialize_attachment(attachment)
75
+ if not text and not attachment_id:
76
+ raise ValueError("Provide text or an attachment")
77
+ return {
78
+ "message": text,
79
+ "random_id": _random_id(random_id),
80
+ "keyboard": keyboard.model_dump_json(exclude_none=True) if keyboard else None,
81
+ "attachment": attachment_id,
82
+ "dont_parse_links": dont_parse_links,
83
+ }
84
+
85
+
86
+ def _peer_identifier(peer_id: int) -> int:
87
+ if type(peer_id) is not int or peer_id == 0:
88
+ raise ValueError("peer_id must be a nonzero integer")
89
+ return peer_id
90
+
91
+
92
+ def _message_send_result(payload: JsonValue, peer_id: int) -> MessageSendResult:
93
+ if not isinstance(payload, list) or len(payload) != 1:
94
+ raise InvalidResponseError("Expected one message send result")
95
+ sent = _parse(_MessageSendResponse, payload[0])
96
+ if sent.peer_id != peer_id:
97
+ raise InvalidResponseError("Message send result has an unexpected recipient")
98
+ if sent.error is not None:
99
+ error_type = RateLimitError if sent.error.code == 6 else APIError
100
+ raise error_type(sent.error.code, "messages.send")
101
+ if sent.message_id is None or sent.conversation_message_id is None:
102
+ raise InvalidResponseError("Message send result has no message identifiers")
103
+ if sent.conversation_message_id == 0:
104
+ raise InvalidResponseError("Message send result has no usable conversation identifier")
105
+ return MessageSendResult(
106
+ peer_id=sent.peer_id,
107
+ message_id=sent.message_id or None,
108
+ conversation_message_id=sent.conversation_message_id,
109
+ **(sent.model_extra or {}),
110
+ )
111
+
112
+
65
113
  class Bot:
66
114
  def __init__(
67
115
  self,
@@ -132,22 +180,34 @@ class Bot:
132
180
  attachment: str | Attachment | None = None,
133
181
  dont_parse_links: bool = False,
134
182
  ) -> int:
135
- attachment_id = serialize_attachment(attachment)
136
- if not text and not attachment_id:
137
- raise ValueError("Provide text or an attachment")
183
+ parameters = _send_parameters(text, random_id, keyboard, attachment, dont_parse_links)
138
184
  result = await self.request(
139
185
  "messages.send",
140
- {
141
- "peer_id": peer_id,
142
- "message": text,
143
- "random_id": _random_id(random_id),
144
- "keyboard": keyboard.model_dump_json(exclude_none=True) if keyboard else None,
145
- "attachment": attachment_id,
146
- "dont_parse_links": dont_parse_links,
147
- },
186
+ {"peer_id": peer_id, **parameters},
148
187
  )
149
188
  return _integer(result)
150
189
 
190
+ async def send_message_and_get_ids(
191
+ self,
192
+ peer_id: int,
193
+ text: str = "",
194
+ *,
195
+ random_id: int | None = None,
196
+ keyboard: Keyboard | None = None,
197
+ attachment: str | Attachment | None = None,
198
+ dont_parse_links: bool = False,
199
+ ) -> MessageSendResult:
200
+ """Send to one peer and return IDs; an unavailable global ID becomes None.
201
+
202
+ Uses peer_ids to obtain a conversation-scoped ID. Recipient errors raise
203
+ APIError (RateLimitError for code 6); malformed results raise InvalidResponseError.
204
+ No automatic retry or fallback send is performed.
205
+ """
206
+ _peer_identifier(peer_id)
207
+ parameters = _send_parameters(text, random_id, keyboard, attachment, dont_parse_links)
208
+ result = await self.request("messages.send", {"peer_ids": str(peer_id), **parameters})
209
+ return _message_send_result(result, peer_id)
210
+
151
211
  async def edit_message(
152
212
  self,
153
213
  peer_id: int,
@@ -332,6 +392,36 @@ class Bot:
332
392
  )
333
393
  return _integer(result)
334
394
 
395
+ async def forward_message_and_get_ids(
396
+ self,
397
+ peer_id: int,
398
+ *,
399
+ from_peer_id: int,
400
+ conversation_message_id: int,
401
+ random_id: int | None = None,
402
+ ) -> MessageSendResult:
403
+ """Forward one source peer's message and return the new message's IDs.
404
+
405
+ conversation_message_id belongs to from_peer_id, not the destination.
406
+ Recipient errors and response validation follow send_message_and_get_ids.
407
+ """
408
+ _peer_identifier(peer_id)
409
+ _peer_identifier(from_peer_id)
410
+ _message_identifier(None, conversation_message_id)
411
+ forward = {
412
+ "peer_id": from_peer_id,
413
+ "conversation_message_ids": [conversation_message_id],
414
+ }
415
+ result = await self.request(
416
+ "messages.send",
417
+ {
418
+ "peer_ids": str(peer_id),
419
+ "random_id": _random_id(random_id),
420
+ "forward": json.dumps(forward),
421
+ },
422
+ )
423
+ return _message_send_result(result, peer_id)
424
+
335
425
  async def send_message_event_answer(
336
426
  self,
337
427
  event_id: str,
@@ -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
@@ -1,3 +1,4 @@
1
+ from .api import MessageSendResult
1
2
  from .attachments import (
2
3
  Attachment,
3
4
  AudioMessageAttachment,
@@ -33,6 +34,7 @@ __all__ = [
33
34
  "LocationButton",
34
35
  "Message",
35
36
  "MessageEvent",
37
+ "MessageSendResult",
36
38
  "OpenLinkButton",
37
39
  "PhotoAttachment",
38
40
  "ShowSnackbar",
@@ -51,6 +51,34 @@ class DocumentUpload(VKModel):
51
51
  file: str = Field(min_length=1, repr=False)
52
52
 
53
53
 
54
+ class MessageSendResult(VKModel):
55
+ """Identifiers of one sent message; a global ID is not always available."""
56
+
57
+ peer_id: int = Field(strict=True)
58
+ message_id: int | None = Field(strict=True, gt=0)
59
+ conversation_message_id: int = Field(strict=True, gt=0)
60
+
61
+ @field_validator("peer_id")
62
+ @classmethod
63
+ def validate_peer_id(cls, value: int) -> int:
64
+ if value == 0:
65
+ raise ValueError("peer_id must be nonzero")
66
+ return value
67
+
68
+
69
+ class _MessageSendError(VKModel):
70
+ code: int = Field(strict=True, gt=0)
71
+
72
+
73
+ class _MessageSendResponse(VKModel):
74
+ """Recipient errors may carry zero or omitted message identifiers."""
75
+
76
+ peer_id: int = Field(strict=True)
77
+ message_id: int | None = Field(default=None, strict=True, ge=0)
78
+ conversation_message_id: int | None = Field(default=None, strict=True, ge=0)
79
+ error: _MessageSendError | None = Field(default=None, repr=False)
80
+
81
+
54
82
  class MessageDeleteError(VKModel):
55
83
  code: int = Field(strict=True)
56
84
 
@@ -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."""
@@ -64,7 +66,7 @@ class _Button(BaseModel):
64
66
 
65
67
 
66
68
  class _LabeledButton(_Button):
67
- label: str = Field(repr=False)
69
+ label: str = Field(repr=False, max_length=MAX_BUTTON_LABEL_LENGTH)
68
70
  color: ButtonColor = ButtonColor.SECONDARY
69
71
 
70
72
 
@@ -84,7 +86,7 @@ class OpenLinkButton(_Button):
84
86
  """Open a URL using VK's link action, without a configurable color."""
85
87
 
86
88
  type: Literal[ButtonType.OPEN_LINK] = ButtonType.OPEN_LINK
87
- label: str = Field(repr=False)
89
+ label: str = Field(repr=False, max_length=MAX_BUTTON_LABEL_LENGTH)
88
90
  link: str = Field(repr=False)
89
91
 
90
92
 
@@ -0,0 +1,132 @@
1
+ """The message fields used by this framework, not the entire VK schema."""
2
+
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
+ )
24
+
25
+ from .attachments import Attachment, parse_attachment
26
+ from .base import VKModel
27
+ from .keyboards import TypedButton
28
+
29
+
30
+ class Coordinates(VKModel):
31
+ latitude: float
32
+ longitude: float
33
+
34
+
35
+ class Geo(VKModel):
36
+ coordinates: Coordinates
37
+
38
+
39
+ class Message(VKModel):
40
+ id: int
41
+ from_id: int
42
+ peer_id: int
43
+ conversation_message_id: int
44
+ text: str
45
+ geo: Geo | None = None
46
+ payload: str | None = None
47
+ attachments: list[dict[str, JsonValue]] = Field(default_factory=list)
48
+
49
+ @property
50
+ def typed_attachments(self) -> list[Attachment]:
51
+ """Return fresh typed views; edits to the raw list remain visible."""
52
+ return [parse_attachment(value) for value in self.attachments]
53
+
54
+
55
+ class MessageObject(VKModel):
56
+ message: Message
57
+
58
+
59
+ class MessageEvent(VKModel):
60
+ user_id: int
61
+ peer_id: int
62
+ event_id: str
63
+ conversation_message_id: int | None = None
64
+ # Official schema says string; deployed button events may contain JSON objects.
65
+ # Preserve both without silently decoding or discarding the original value.
66
+ payload: JsonValue = None
67
+
68
+
69
+ class User(VKModel):
70
+ id: int
71
+ first_name: str | None = None
72
+ last_name: str | None = None
73
+ screen_name: str | None = None
74
+
75
+
76
+ class Keyboard(VKModel):
77
+ model_config = ConfigDict(validate_assignment=True)
78
+
79
+ buttons: list[list[TypedButton | dict[str, JsonValue]]]
80
+ one_time: bool = False
81
+ inline: bool = False
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
+
129
+
130
+ class MessagePage(VKModel):
131
+ count: int
132
+ items: list[Message]
@@ -1,64 +0,0 @@
1
- """The message fields used by this framework, not the entire VK schema."""
2
-
3
- from pydantic import Field, JsonValue
4
-
5
- from .attachments import Attachment, parse_attachment
6
- from .base import VKModel
7
- from .keyboards import TypedButton
8
-
9
-
10
- class Coordinates(VKModel):
11
- latitude: float
12
- longitude: float
13
-
14
-
15
- class Geo(VKModel):
16
- coordinates: Coordinates
17
-
18
-
19
- class Message(VKModel):
20
- id: int
21
- from_id: int
22
- peer_id: int
23
- conversation_message_id: int
24
- text: str
25
- geo: Geo | None = None
26
- payload: str | None = None
27
- attachments: list[dict[str, JsonValue]] = Field(default_factory=list)
28
-
29
- @property
30
- def typed_attachments(self) -> list[Attachment]:
31
- """Return fresh typed views; edits to the raw list remain visible."""
32
- return [parse_attachment(value) for value in self.attachments]
33
-
34
-
35
- class MessageObject(VKModel):
36
- message: Message
37
-
38
-
39
- class MessageEvent(VKModel):
40
- user_id: int
41
- peer_id: int
42
- event_id: str
43
- conversation_message_id: int | None = None
44
- # Official schema says string; deployed button events may contain JSON objects.
45
- # Preserve both without silently decoding or discarding the original value.
46
- payload: JsonValue = None
47
-
48
-
49
- class User(VKModel):
50
- id: int
51
- first_name: str | None = None
52
- last_name: str | None = None
53
- screen_name: str | None = None
54
-
55
-
56
- class Keyboard(VKModel):
57
- buttons: list[list[TypedButton | dict[str, JsonValue]]]
58
- one_time: bool = False
59
- inline: bool = False
60
-
61
-
62
- class MessagePage(VKModel):
63
- count: int
64
- items: list[Message]
File without changes
File without changes