python-vk-bot 0.6.0__py3-none-any.whl → 0.8.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
@@ -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",
python_vk_bot/bot.py CHANGED
@@ -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
 
@@ -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
@@ -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
@@ -1,12 +1,13 @@
1
- python_vk_bot/__init__.py,sha256=H-6FJF2oBDG-AjBZN8SpSXOfy9dVA7ReDekjrnq53Rs,1583
1
+ python_vk_bot/__init__.py,sha256=f6S37kGsoT0yoVT19IMpkweIMG8CyoeTxUQprFtT-LM,1631
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=Ewt7ebW00rklpAXyZkiBcnZnKdzHwABD5mPAz7scqw8,13640
4
+ python_vk_bot/bot.py,sha256=T1ORFc9Bcrj_YAzM288V9QmrwwwSwQ7fqQ_nsIfNBLU,17108
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=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
@@ -14,16 +15,16 @@ python_vk_bot/settings.py,sha256=JcbDihGRJGRGvBBSeB3j_LPaoX7dkPHfh-WviKQCrwk,915
14
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=exCkuHNIqRGVDjinpi0afpdgEvoPbz4JWeQzimw7c0w,937
18
- python_vk_bot/models/api.py,sha256=jY9pedj7TZQkt9bRROUo8rMrO2PyAO7DPJz7E1YphYs,1626
18
+ python_vk_bot/models/__init__.py,sha256=YhwGTUnNMchldEjw3o1nsVQEQonOhbeFhebIrr9T1q0,997
19
+ python_vk_bot/models/api.py,sha256=l6wVrJJyxA23hUg5cFLc7rl2RkbGdEjnzDAe1jpwqcc,2543
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
22
23
  python_vk_bot/models/event_answers.py,sha256=BApsLwOySfcr3aLUazQo8rryEsitT3jaEGTQpuVIk14,445
23
24
  python_vk_bot/models/events.py,sha256=7JPZykMTRy8hiMKsX45ZZbwGiK8-sZFtzXZqprYxK18,2826
24
- python_vk_bot/models/keyboards.py,sha256=JZ61_Z4VhyvyI9lTk8aNlyuco5z4hQOlDmWR8xS8srw,2932
25
- python_vk_bot/models/messages.py,sha256=WAUsa7VMDNl0xK2LXa91kg6RQsWBXoQATI1aAMDiHLU,1543
26
- python_vk_bot-0.6.0.dist-info/METADATA,sha256=llvvyyVVHt7oJZS1LMfZxt5GrOgqTwz0cpgXkRefoRQ,13340
27
- python_vk_bot-0.6.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
28
- python_vk_bot-0.6.0.dist-info/licenses/LICENSE,sha256=F-35ycqPcYW243OjxMHCggr_AHQgZLX2zvtZgobVEvo,1072
29
- python_vk_bot-0.6.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.8.0.dist-info/METADATA,sha256=vN1_zAYcrh5Y-ErIaSrHUwsvvvXRdO74ywO7dVCuuSE,15255
28
+ python_vk_bot-0.8.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
29
+ python_vk_bot-0.8.0.dist-info/licenses/LICENSE,sha256=F-35ycqPcYW243OjxMHCggr_AHQgZLX2zvtZgobVEvo,1072
30
+ python_vk_bot-0.8.0.dist-info/RECORD,,