python-vk-bot 0.1.0__py3-none-any.whl → 0.3.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
@@ -7,16 +7,37 @@ from .callback import Callback
7
7
  from .context import Context
8
8
  from .handlers import CommandHandler, Handler, MessageEventHandler, MessageHandler
9
9
  from .long_poll import LongPoll
10
- from .models import Keyboard, Message, MessageEvent, Update, User
10
+ from .models import (
11
+ Attachment,
12
+ AudioMessageAttachment,
13
+ ButtonColor,
14
+ ButtonType,
15
+ CallbackButton,
16
+ DocumentAttachment,
17
+ Keyboard,
18
+ Message,
19
+ MessageEvent,
20
+ PhotoAttachment,
21
+ TextButton,
22
+ Update,
23
+ User,
24
+ VideoAttachment,
25
+ )
11
26
  from .settings import BotSettings
12
27
 
13
28
  __all__ = [
14
29
  "Application",
30
+ "Attachment",
31
+ "AudioMessageAttachment",
15
32
  "Bot",
16
33
  "BotSettings",
34
+ "ButtonColor",
35
+ "ButtonType",
17
36
  "Callback",
37
+ "CallbackButton",
18
38
  "CommandHandler",
19
39
  "Context",
40
+ "DocumentAttachment",
20
41
  "Handler",
21
42
  "Keyboard",
22
43
  "LongPoll",
@@ -24,7 +45,10 @@ __all__ = [
24
45
  "MessageEvent",
25
46
  "MessageEventHandler",
26
47
  "MessageHandler",
48
+ "PhotoAttachment",
49
+ "TextButton",
27
50
  "Update",
28
51
  "User",
52
+ "VideoAttachment",
29
53
  "filters",
30
54
  ]
python_vk_bot/bot.py CHANGED
@@ -1,19 +1,34 @@
1
1
  """Typed wrappers for supported VK community bot methods."""
2
2
 
3
3
  import json
4
+ import re
4
5
  import secrets
5
6
  from collections.abc import Mapping
6
7
  from types import TracebackType
7
- from typing import Self
8
+ from typing import Literal, Self
8
9
 
9
10
  import httpx
10
11
  from pydantic import BaseModel, JsonValue, SecretStr, TypeAdapter, ValidationError
11
12
 
12
13
  from ._config import DEFAULT_API_VERSION, DEFAULT_TIMEOUT, TransportConfig
13
- from .errors import InvalidResponseError
14
- from .models.api import LongPollServer
14
+ from .errors import APIError, InvalidResponseError, RateLimitError
15
+ from .models.api import (
16
+ DocumentUpload,
17
+ LongPollServer,
18
+ MessageDeleteResult,
19
+ PhotoUpload,
20
+ UploadServer,
21
+ )
22
+ from .models.attachments import (
23
+ Attachment,
24
+ AudioMessageAttachment,
25
+ DocumentAttachment,
26
+ Photo,
27
+ PhotoAttachment,
28
+ serialize_attachment,
29
+ )
15
30
  from .models.messages import Keyboard, Message, MessagePage, User
16
- from .transport import HTTPTransport, Parameter
31
+ from .transport import FileInput, HTTPTransport, Parameter
17
32
 
18
33
 
19
34
  def _parse[T: BaseModel](model: type[T], payload: JsonValue) -> T:
@@ -37,6 +52,15 @@ def _random_id(value: int | None) -> int:
37
52
  return value
38
53
 
39
54
 
55
+ def _message_identifier(message_id: int | None, conversation_message_id: int | None) -> int:
56
+ if (message_id is None) == (conversation_message_id is None):
57
+ raise ValueError("Provide exactly one message identifier")
58
+ identifier = message_id if message_id is not None else conversation_message_id
59
+ if type(identifier) is not int or identifier <= 0:
60
+ raise ValueError("Message identifiers must be positive integers")
61
+ return identifier
62
+
63
+
40
64
  class Bot:
41
65
  def __init__(
42
66
  self,
@@ -104,10 +128,11 @@ class Bot:
104
128
  *,
105
129
  random_id: int | None = None,
106
130
  keyboard: Keyboard | None = None,
107
- attachment: str | None = None,
131
+ attachment: str | Attachment | None = None,
108
132
  dont_parse_links: bool = False,
109
133
  ) -> int:
110
- if not text and not attachment:
134
+ attachment_id = serialize_attachment(attachment)
135
+ if not text and not attachment_id:
111
136
  raise ValueError("Provide text or an attachment")
112
137
  result = await self.request(
113
138
  "messages.send",
@@ -116,7 +141,7 @@ class Bot:
116
141
  "message": text,
117
142
  "random_id": _random_id(random_id),
118
143
  "keyboard": keyboard.model_dump_json(exclude_none=True) if keyboard else None,
119
- "attachment": attachment,
144
+ "attachment": attachment_id,
120
145
  "dont_parse_links": dont_parse_links,
121
146
  },
122
147
  )
@@ -125,15 +150,19 @@ class Bot:
125
150
  async def edit_message(
126
151
  self,
127
152
  peer_id: int,
128
- text: str,
153
+ text: str | None = None,
129
154
  *,
130
155
  message_id: int | None = None,
131
156
  conversation_message_id: int | None = None,
132
157
  keyboard: Keyboard | None = None,
158
+ attachment: str | Attachment | None = None,
133
159
  dont_parse_links: bool = False,
134
160
  ) -> bool:
135
- if (message_id is None) == (conversation_message_id is None):
136
- raise ValueError("Provide exactly one message identifier")
161
+ """Edit text and/or attachments. None omits a field; an empty string sends it."""
162
+ _message_identifier(message_id, conversation_message_id)
163
+ attachment_id = serialize_attachment(attachment)
164
+ if text is None and attachment_id is None:
165
+ raise ValueError("Provide text or an attachment")
137
166
  result = await self.request(
138
167
  "messages.edit",
139
168
  {
@@ -142,11 +171,148 @@ class Bot:
142
171
  "message_id": message_id,
143
172
  "cmid": conversation_message_id,
144
173
  "keyboard": keyboard.model_dump_json(exclude_none=True) if keyboard else None,
174
+ "attachment": attachment_id,
145
175
  "dont_parse_links": dont_parse_links,
146
176
  },
147
177
  )
148
178
  return _integer(result) == 1
149
179
 
180
+ async def upload_photo(
181
+ self,
182
+ peer_id: int,
183
+ photo: FileInput,
184
+ *,
185
+ filename: str | None = None,
186
+ ) -> PhotoAttachment:
187
+ """Upload and save one photo for messaging; this does not send a message."""
188
+ server = _parse(
189
+ UploadServer, await self.request("photos.getMessagesUploadServer", {"peer_id": peer_id})
190
+ )
191
+ uploaded = _parse(
192
+ PhotoUpload,
193
+ await self.transport.upload(server.upload_url, photo, field="photo", filename=filename),
194
+ )
195
+ result = await self.request(
196
+ "photos.saveMessagesPhoto",
197
+ {"server": uploaded.server, "photo": uploaded.photo, "hash": uploaded.hash},
198
+ )
199
+ if not isinstance(result, list) or len(result) != 1:
200
+ raise InvalidResponseError("Expected one saved photo")
201
+ return PhotoAttachment(photo=_parse(Photo, result[0]))
202
+
203
+ async def upload_document(
204
+ self,
205
+ peer_id: int,
206
+ document: FileInput,
207
+ *,
208
+ filename: str | None = None,
209
+ type: Literal["doc", "audio_message"] = "doc",
210
+ title: str | None = None,
211
+ tags: str | None = None,
212
+ ) -> DocumentAttachment | AudioMessageAttachment:
213
+ """Upload and save a document or voice file without sending it."""
214
+ if type not in {"doc", "audio_message"}:
215
+ raise ValueError("Unsupported document upload type")
216
+ server = _parse(
217
+ UploadServer,
218
+ await self.request("docs.getMessagesUploadServer", {"peer_id": peer_id, "type": type}),
219
+ )
220
+ uploaded = _parse(
221
+ DocumentUpload,
222
+ await self.transport.upload(
223
+ server.upload_url, document, field="file", filename=filename
224
+ ),
225
+ )
226
+ result = await self.request(
227
+ "docs.save", {"file": uploaded.file, "title": title, "tags": tags}
228
+ )
229
+ # A save response must contain the requested kind, unlike tolerant inbound views.
230
+ if not isinstance(result, dict) or result.get("type") != type:
231
+ raise InvalidResponseError("Unexpected saved document type")
232
+ if type == "audio_message":
233
+ return _parse(AudioMessageAttachment, result)
234
+ return _parse(DocumentAttachment, result)
235
+
236
+ async def edit_message_media(
237
+ self,
238
+ peer_id: int,
239
+ media: FileInput | str | PhotoAttachment,
240
+ *,
241
+ message_id: int | None = None,
242
+ conversation_message_id: int | None = None,
243
+ caption: str | None = None,
244
+ keyboard: Keyboard | None = None,
245
+ filename: str | None = None,
246
+ dont_parse_links: bool = False,
247
+ ) -> bool:
248
+ """Replace a photo, optionally changing text/keyboard; never send a fallback.
249
+
250
+ A photo object or VK photo identifier bypasses upload. None omits caption or
251
+ keyboard from messages.edit; supply their desired values explicitly to avoid
252
+ relying on VK's handling of omitted fields. Failed edits leave the saved photo.
253
+ """
254
+ _message_identifier(message_id, conversation_message_id)
255
+ attachment: str | PhotoAttachment
256
+ if isinstance(media, str):
257
+ if re.fullmatch(r"photo-?[1-9][0-9]*_[1-9][0-9]*(?:_[^,\s]+)?", media) is None:
258
+ raise ValueError("media must be a VK photo identifier or a local binary file")
259
+ attachment = media
260
+ elif isinstance(media, PhotoAttachment):
261
+ attachment = media
262
+ else:
263
+ attachment = await self.upload_photo(peer_id, media, filename=filename)
264
+ return await self.edit_message(
265
+ peer_id,
266
+ caption,
267
+ message_id=message_id,
268
+ conversation_message_id=conversation_message_id,
269
+ keyboard=keyboard,
270
+ attachment=attachment,
271
+ dont_parse_links=dont_parse_links,
272
+ )
273
+
274
+ async def delete_message(
275
+ self,
276
+ peer_id: int,
277
+ *,
278
+ message_id: int | None = None,
279
+ conversation_message_id: int | None = None,
280
+ delete_for_all: bool = False,
281
+ spam: bool = False,
282
+ ) -> bool:
283
+ """Delete one message. Recipient-side deletion must be explicitly requested."""
284
+ identifier = _message_identifier(message_id, conversation_message_id)
285
+ result = await self.request(
286
+ "messages.delete",
287
+ {
288
+ "peer_id": peer_id,
289
+ "message_ids": message_id,
290
+ "cmids": conversation_message_id,
291
+ "delete_for_all": delete_for_all,
292
+ "spam": spam,
293
+ },
294
+ )
295
+ # VK's method page describes per-ID success; its current schema additionally
296
+ # describes full result objects. Do not mistake an unrecognized response for success.
297
+ if isinstance(result, dict) and message_id is not None:
298
+ status = result.get(str(message_id))
299
+ if type(status) is int and status in (0, 1):
300
+ return status == 1
301
+ if not isinstance(result, list) or len(result) != 1:
302
+ raise InvalidResponseError("Expected one message deletion result")
303
+ deleted = _parse(MessageDeleteResult, result[0])
304
+ actual_id = (
305
+ deleted.message_id if message_id is not None else deleted.conversation_message_id
306
+ )
307
+ if actual_id != identifier or (deleted.peer_id is not None and deleted.peer_id != peer_id):
308
+ raise InvalidResponseError("Message deletion result has an unexpected identifier")
309
+ if deleted.error is not None:
310
+ error_type = RateLimitError if deleted.error.code == 6 else APIError
311
+ raise error_type(deleted.error.code, "messages.delete")
312
+ if deleted.response is None:
313
+ raise InvalidResponseError("Message deletion result has no status")
314
+ return deleted.response == 1
315
+
150
316
  async def forward_message(
151
317
  self, peer_id: int, message: Message, *, random_id: int | None = None
152
318
  ) -> int:
python_vk_bot/errors.py CHANGED
@@ -30,6 +30,10 @@ class InvalidResponseError(VKError):
30
30
  """Malformed JSON or an unexpected response shape."""
31
31
 
32
32
 
33
+ class UploadError(VKError):
34
+ """The upload server rejected a file; its potentially sensitive reply is omitted."""
35
+
36
+
33
37
  class InvalidUpdateError(VKError):
34
38
  """An event does not match the supported data boundary."""
35
39
 
@@ -1,4 +1,29 @@
1
+ from .attachments import (
2
+ Attachment,
3
+ AudioMessageAttachment,
4
+ DocumentAttachment,
5
+ PhotoAttachment,
6
+ VideoAttachment,
7
+ )
1
8
  from .events import Update
9
+ from .keyboards import ButtonColor, ButtonType, CallbackButton, TextButton
2
10
  from .messages import Coordinates, Geo, Keyboard, Message, MessageEvent, User
3
11
 
4
- __all__ = ["Coordinates", "Geo", "Keyboard", "Message", "MessageEvent", "Update", "User"]
12
+ __all__ = [
13
+ "Attachment",
14
+ "AudioMessageAttachment",
15
+ "ButtonColor",
16
+ "ButtonType",
17
+ "CallbackButton",
18
+ "Coordinates",
19
+ "DocumentAttachment",
20
+ "Geo",
21
+ "Keyboard",
22
+ "Message",
23
+ "MessageEvent",
24
+ "PhotoAttachment",
25
+ "TextButton",
26
+ "Update",
27
+ "User",
28
+ "VideoAttachment",
29
+ ]
@@ -35,3 +35,29 @@ class LongPollResponse(VKModel):
35
35
  @classmethod
36
36
  def normalize_ts(cls, value: object) -> object:
37
37
  return str(value) if type(value) is int else value
38
+
39
+
40
+ class UploadServer(VKModel):
41
+ upload_url: str = Field(min_length=1, repr=False)
42
+
43
+
44
+ class PhotoUpload(VKModel):
45
+ server: int = Field(strict=True)
46
+ photo: str = Field(min_length=1, repr=False)
47
+ hash: str = Field(min_length=1, repr=False)
48
+
49
+
50
+ class DocumentUpload(VKModel):
51
+ file: str = Field(min_length=1, repr=False)
52
+
53
+
54
+ class MessageDeleteError(VKModel):
55
+ code: int = Field(strict=True)
56
+
57
+
58
+ class MessageDeleteResult(VKModel):
59
+ peer_id: int | None = None
60
+ message_id: int | None = None
61
+ conversation_message_id: int | None = None
62
+ response: int | None = Field(default=None, strict=True, ge=0, le=1)
63
+ error: MessageDeleteError | None = Field(default=None, repr=False)
@@ -0,0 +1,138 @@
1
+ """Typed VK attachment envelopes, retaining fields outside our supported subset."""
2
+
3
+ from copy import deepcopy
4
+ from typing import Literal
5
+
6
+ from pydantic import Field, JsonValue, ValidationError, field_validator
7
+
8
+ from .base import VKModel
9
+
10
+
11
+ class Media(VKModel):
12
+ id: int = Field(strict=True, gt=0)
13
+ owner_id: int = Field(strict=True)
14
+ access_key: str | None = Field(default=None, repr=False)
15
+
16
+ @field_validator("owner_id")
17
+ @classmethod
18
+ def validate_owner(cls, value: int) -> int:
19
+ if value == 0:
20
+ raise ValueError("owner_id must be nonzero")
21
+ return value
22
+
23
+
24
+ class Photo(Media):
25
+ album_id: int | None = None
26
+ date: int | None = None
27
+ text: str | None = None
28
+ sizes: list[dict[str, JsonValue]] = Field(default_factory=list)
29
+
30
+
31
+ class Document(Media):
32
+ title: str | None = None
33
+ size: int | None = None
34
+ ext: str | None = None
35
+ url: str | None = Field(default=None, repr=False)
36
+ type: int | None = None
37
+
38
+
39
+ class Video(Media):
40
+ title: str | None = None
41
+ duration: int | None = None
42
+ image: list[dict[str, JsonValue]] = Field(default_factory=list)
43
+
44
+
45
+ class AudioMessage(Media):
46
+ duration: int | None = None
47
+ waveform: list[int] = Field(default_factory=list)
48
+ link_mp3: str | None = Field(default=None, repr=False)
49
+ link_ogg: str | None = Field(default=None, repr=False)
50
+
51
+
52
+ class Attachment(VKModel, frozen=True):
53
+ """Fallback envelope. Unknown or incomplete attachments cannot be resent implicitly."""
54
+
55
+ type: JsonValue = None
56
+
57
+ @property
58
+ def media(self) -> Media | None:
59
+ return None
60
+
61
+ @property
62
+ def id(self) -> int | None:
63
+ return self.media.id if self.media is not None else None
64
+
65
+ @property
66
+ def owner_id(self) -> int | None:
67
+ return self.media.owner_id if self.media is not None else None
68
+
69
+ def to_attachment(self) -> str:
70
+ """Return VK's wire identifier, including an access key when present."""
71
+ media = self.media
72
+ if media is None:
73
+ raise ValueError("Only a supported, complete attachment can be sent")
74
+ prefix = "doc" if self.type == "audio_message" else self.type
75
+ identifier = f"{prefix}{media.owner_id}_{media.id}"
76
+ return f"{identifier}_{media.access_key}" if media.access_key else identifier
77
+
78
+
79
+ class PhotoAttachment(Attachment):
80
+ type: Literal["photo"] = "photo"
81
+ photo: Photo
82
+
83
+ @property
84
+ def media(self) -> Photo:
85
+ return self.photo
86
+
87
+
88
+ class DocumentAttachment(Attachment):
89
+ type: Literal["doc"] = "doc"
90
+ doc: Document
91
+
92
+ @property
93
+ def media(self) -> Document:
94
+ return self.doc
95
+
96
+
97
+ class VideoAttachment(Attachment):
98
+ type: Literal["video"] = "video"
99
+ video: Video
100
+
101
+ @property
102
+ def media(self) -> Video:
103
+ return self.video
104
+
105
+
106
+ class AudioMessageAttachment(Attachment):
107
+ type: Literal["audio_message"] = "audio_message"
108
+ audio_message: AudioMessage
109
+
110
+ @property
111
+ def media(self) -> AudioMessage:
112
+ return self.audio_message
113
+
114
+
115
+ _ATTACHMENT_MODELS: dict[str, type[Attachment]] = {
116
+ "photo": PhotoAttachment,
117
+ "doc": DocumentAttachment,
118
+ "video": VideoAttachment,
119
+ "audio_message": AudioMessageAttachment,
120
+ }
121
+
122
+
123
+ def parse_attachment(value: dict[str, JsonValue]) -> Attachment:
124
+ """Parse a view without making an otherwise valid Message fail validation."""
125
+ value = deepcopy(value)
126
+ kind = value.get("type")
127
+ model = _ATTACHMENT_MODELS.get(kind) if isinstance(kind, str) else None
128
+ if model is not None:
129
+ try:
130
+ return model.model_validate(value)
131
+ except ValidationError:
132
+ pass
133
+ # The fallback also retains a missing or malformed type as its original JSON value.
134
+ return Attachment.model_validate(value)
135
+
136
+
137
+ def serialize_attachment(value: str | Attachment | None) -> str | None:
138
+ return value.to_attachment() if isinstance(value, Attachment) else value
@@ -0,0 +1,78 @@
1
+ """Convenient outgoing button models with VK JSON serialization."""
2
+
3
+ import json
4
+ from enum import StrEnum
5
+ from typing import Annotated, Literal
6
+
7
+ from pydantic import (
8
+ BaseModel,
9
+ ConfigDict,
10
+ Field,
11
+ JsonValue,
12
+ SerializeAsAny,
13
+ SerializerFunctionWrapHandler,
14
+ field_serializer,
15
+ model_serializer,
16
+ )
17
+
18
+
19
+ class ButtonColor(StrEnum):
20
+ """Colors documented by the VK keyboard guide."""
21
+
22
+ PRIMARY = "primary"
23
+ SECONDARY = "secondary"
24
+ POSITIVE = "positive"
25
+ NEGATIVE = "negative"
26
+
27
+
28
+ class ButtonType(StrEnum):
29
+ """Action types supported by the typed button models."""
30
+
31
+ TEXT = "text"
32
+ CALLBACK = "callback"
33
+
34
+
35
+ class _LabeledButton(BaseModel):
36
+ model_config = ConfigDict(
37
+ extra="forbid", validate_assignment=True, hide_input_in_errors=True, allow_inf_nan=False
38
+ )
39
+
40
+ label: str = Field(repr=False)
41
+ payload: dict[str, JsonValue] | SerializeAsAny[BaseModel] | str | None = Field(
42
+ default=None, repr=False
43
+ )
44
+ color: ButtonColor = ButtonColor.SECONDARY
45
+
46
+ @field_serializer("payload", when_used="json")
47
+ def serialize_payload(self, value: dict[str, JsonValue] | BaseModel | str | None) -> str | None:
48
+ if isinstance(value, BaseModel):
49
+ return value.model_dump_json(by_alias=True)
50
+ if isinstance(value, dict):
51
+ return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
52
+ return value
53
+
54
+ @model_serializer(mode="wrap", when_used="json")
55
+ def serialize_button(self, handler: SerializerFunctionWrapHandler) -> dict[str, JsonValue]:
56
+ action: dict[str, JsonValue] = handler(self)
57
+ button: dict[str, JsonValue] = {"action": action}
58
+ if "color" in action:
59
+ button["color"] = action.pop("color")
60
+ # Absence of payload is represented by an omitted action field, never JSON null.
61
+ if action.get("payload") is None:
62
+ action.pop("payload", None)
63
+ return button
64
+
65
+
66
+ class TextButton(_LabeledButton):
67
+ """Send the label and optional payload as a message, handled by MessageHandler."""
68
+
69
+ type: Literal[ButtonType.TEXT] = ButtonType.TEXT
70
+
71
+
72
+ class CallbackButton(_LabeledButton):
73
+ """Emit a message_event, handled by MessageEventHandler."""
74
+
75
+ type: Literal[ButtonType.CALLBACK] = ButtonType.CALLBACK
76
+
77
+
78
+ type TypedButton = Annotated[TextButton | CallbackButton, Field(discriminator="type")]
@@ -2,7 +2,9 @@
2
2
 
3
3
  from pydantic import Field, JsonValue
4
4
 
5
+ from .attachments import Attachment, parse_attachment
5
6
  from .base import VKModel
7
+ from .keyboards import TypedButton
6
8
 
7
9
 
8
10
  class Coordinates(VKModel):
@@ -24,6 +26,11 @@ class Message(VKModel):
24
26
  payload: str | None = None
25
27
  attachments: list[dict[str, JsonValue]] = Field(default_factory=list)
26
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
+
27
34
 
28
35
  class MessageObject(VKModel):
29
36
  message: Message
@@ -47,7 +54,7 @@ class User(VKModel):
47
54
 
48
55
 
49
56
  class Keyboard(VKModel):
50
- buttons: list[list[dict[str, JsonValue]]]
57
+ buttons: list[list[TypedButton | dict[str, JsonValue]]]
51
58
  one_time: bool = False
52
59
  inline: bool = False
53
60
 
@@ -1,10 +1,14 @@
1
1
  """Reusable HTTP transport; request credentials never become client defaults."""
2
2
 
3
+ import asyncio
3
4
  import logging
4
5
  import re
5
6
  from collections.abc import Mapping
7
+ from contextlib import suppress
8
+ from pathlib import Path
6
9
  from types import TracebackType
7
- from typing import Self, cast
10
+ from typing import BinaryIO, Literal, Self, cast
11
+ from urllib.parse import urlsplit
8
12
 
9
13
  import httpx
10
14
  from pydantic import JsonValue, SecretStr, ValidationError
@@ -17,10 +21,23 @@ from .errors import (
17
21
  LifecycleError,
18
22
  NetworkError,
19
23
  RateLimitError,
24
+ UploadError,
20
25
  )
21
26
  from .models.api import APIEnvelope
22
27
 
23
28
  type Parameter = str | int | float | bool | None
29
+ type FileInput = bytes | Path | BinaryIO
30
+
31
+
32
+ def _read_upload(source: Path | BinaryIO) -> bytes:
33
+ """Read in a worker; Path.read_bytes closes its own file even on failure."""
34
+ try:
35
+ content = source.read_bytes() if isinstance(source, Path) else source.read()
36
+ except OSError, ValueError:
37
+ raise ValueError("Could not read the upload file") from None
38
+ if not isinstance(content, bytes):
39
+ raise TypeError("Upload files must be opened in binary mode")
40
+ return content
24
41
 
25
42
 
26
43
  class _RedactQuery(logging.Filter):
@@ -89,6 +106,7 @@ class HTTPTransport:
89
106
  params: Mapping[str, str] | None = None,
90
107
  headers: Mapping[str, str] | None = None,
91
108
  timeout: float | None = None,
109
+ files: Mapping[str, tuple[str, bytes]] | None = None,
92
110
  ) -> JsonValue:
93
111
  if not self._started or self._client is None:
94
112
  raise LifecycleError("Initialize the bot or use its async context manager")
@@ -99,6 +117,7 @@ class HTTPTransport:
99
117
  data=data,
100
118
  params=params,
101
119
  headers=headers,
120
+ files=files,
102
121
  timeout=self.config.timeout if timeout is None else timeout,
103
122
  follow_redirects=False,
104
123
  auth=None,
@@ -141,6 +160,71 @@ class HTTPTransport:
141
160
  raise InvalidResponseError("VK API envelope has no response")
142
161
  return envelope.response
143
162
 
163
+ async def upload(
164
+ self,
165
+ server: str,
166
+ source: FileInput,
167
+ *,
168
+ field: Literal["photo", "file"],
169
+ filename: str | None = None,
170
+ ) -> JsonValue:
171
+ """Buffer a local file off-loop, then upload without community credentials.
172
+
173
+ Memory usage is proportional to file size. Borrowed files are read from their
174
+ current position and remain open. Cancellation drains a pending local read
175
+ before returning ownership of a borrowed file to its caller.
176
+ """
177
+ if not self._started or self._client is None:
178
+ raise LifecycleError("Initialize the bot or use its async context manager")
179
+ if self._client.params:
180
+ raise ValueError("Upload clients must not define default query parameters")
181
+ if "content-type" in self._client.headers:
182
+ raise ValueError("Upload clients must not define a default Content-Type header")
183
+ try:
184
+ # HTTPX percent-encodes an unmatched '[' in a host; reject malformed
185
+ # bracketed hosts before that normalization can turn them into a request.
186
+ urlsplit(server)
187
+ url = httpx.URL(server)
188
+ except httpx.InvalidURL, ValueError:
189
+ raise InvalidResponseError("Invalid upload server URL") from None
190
+ if url.scheme != "https" or not url.host or url.userinfo or url.fragment:
191
+ raise InvalidResponseError("Unexpected upload server URL")
192
+ if not isinstance(source, (bytes, Path)) and not callable(getattr(source, "read", None)):
193
+ raise TypeError("Provide bytes, a Path, or a binary file")
194
+ if filename is None:
195
+ name = getattr(source, "name", None)
196
+ filename = Path(name).name if isinstance(name, str) else None
197
+ if filename is None:
198
+ filename = "photo.png" if field == "photo" else "document.bin"
199
+ if (
200
+ not filename
201
+ or filename in {".", ".."}
202
+ or any(char in filename for char in '/\\"')
203
+ or any(ord(char) < 32 or ord(char) == 127 for char in filename)
204
+ ):
205
+ raise ValueError("filename must be a plain, nonempty file name")
206
+ if isinstance(source, bytes):
207
+ content = source
208
+ else:
209
+ reading = asyncio.create_task(asyncio.to_thread(_read_upload, source))
210
+ try:
211
+ content = await asyncio.shield(reading)
212
+ except asyncio.CancelledError:
213
+ # Repeated cancellation must not return a borrowed file while the
214
+ # worker is still consuming it. Retrieve any read exception as well.
215
+ while not reading.done():
216
+ with suppress(Exception, asyncio.CancelledError):
217
+ await asyncio.shield(reading)
218
+ with suppress(Exception):
219
+ reading.result()
220
+ raise
221
+ if not content:
222
+ raise ValueError("Cannot upload an empty file")
223
+ payload = await self._request("POST", server, files={field: (filename, content)})
224
+ if isinstance(payload, dict) and ("error" in payload or "error_code" in payload):
225
+ raise UploadError("VK upload server rejected the file")
226
+ return payload
227
+
144
228
  async def poll(self, server: str, *, key: SecretStr, ts: str, wait: int) -> JsonValue:
145
229
  url = httpx.URL(server)
146
230
  if url.scheme != "https" or not url.host or url.userinfo or url.query or url.fragment:
@@ -1,7 +1,12 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-vk-bot
3
- Version: 0.1.0
3
+ Version: 0.3.0
4
4
  Summary: An asynchronous framework for VK community bots.
5
+ Project-URL: Homepage, https://github.com/fomenko-ai/python-vk-bot
6
+ Project-URL: Repository, https://github.com/fomenko-ai/python-vk-bot
7
+ Project-URL: Documentation, https://github.com/fomenko-ai/python-vk-bot/blob/main/README.md
8
+ Project-URL: Issues, https://github.com/fomenko-ai/python-vk-bot/issues
9
+ Project-URL: Changelog, https://github.com/fomenko-ai/python-vk-bot/blob/main/CHANGELOG.md
5
10
  Author-email: Aleksei Fomenko <fomenko_ai@proton.me>
6
11
  License-Expression: MIT
7
12
  License-File: LICENSE
@@ -23,11 +28,14 @@ Description-Content-Type: text/markdown
23
28
  <img src="logo.png" alt="python-vk-bot logo" width="720">
24
29
  </p>
25
30
 
31
+ [![main · Python 3.14+](https://img.shields.io/badge/main-Python%203.14%2B-blue.svg)](https://github.com/fomenko-ai/python-vk-bot/tree/main)
32
+ [![compat/py39 · Python 3.9–3.14](https://img.shields.io/badge/compat%2Fpy39-Python%203.9%E2%80%933.14-blue.svg)](https://github.com/fomenko-ai/python-vk-bot/tree/compat/py39)
33
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
34
+
26
35
  # python-vk-bot
27
36
 
28
37
  An asynchronous framework for VK community bots, inspired by python-telegram-bot.
29
- Development targets **Python 3.14** and VK API **5.199**. The regression suite runs without
30
- network access; see [verification results](docs/development/verification.md).
38
+ Supports VK API **5.199**.
31
39
 
32
40
  ## Installation
33
41
 
@@ -35,6 +43,15 @@ network access; see [verification results](docs/development/verification.md).
35
43
  uv add python-vk-bot
36
44
  ```
37
45
 
46
+ For Python 3.9–3.13, use the `compat/py39` branch:
47
+
48
+ ```bash
49
+ uv add git+https://github.com/fomenko-ai/python-vk-bot.git --branch compat/py39
50
+ ```
51
+
52
+ See [Python compatibility](docs/development/python-compatibility.md) for branch
53
+ differences, optional dependencies and installation with pip.
54
+
38
55
  ### Install from this checkout
39
56
 
40
57
  ```bash
@@ -47,6 +64,17 @@ For the optional Callback HTTP receiver:
47
64
  uv sync --locked --extra callback
48
65
  ```
49
66
 
67
+ ## Examples
68
+
69
+ See the [examples guide](examples/README.md) for setup, required events and run commands.
70
+
71
+ | Example | Description |
72
+ | --- | --- |
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 |
75
+ | [Interactive map](examples/interactive_map.py) | Generate, upload and replace a PNG using navigation buttons |
76
+ | [Callback receiver](examples/callback.py) | Receive events through an ASGI application |
77
+
50
78
  ## Long Poll bot
51
79
 
52
80
  Enable Bots Long Poll and the `message_new` event in the community settings. Configure
@@ -158,8 +186,8 @@ async with Bot(token) as bot:
158
186
  user = await bot.get_user_info(user_id)
159
187
  ```
160
188
 
161
- An injected `httpx.AsyncClient` remains caller-owned. Methods cover sending, editing,
162
- forwarding, fetching a message/user, answering message events, and obtaining Long Poll
189
+ An injected `httpx.AsyncClient` remains caller-owned. Methods cover uploading, sending,
190
+ editing, deleting, forwarding, fetching a message/user, answering message events, and obtaining Long Poll
163
191
  connection data. `Bot.request(method, parameters)` exposes raw JSON results for additional
164
192
  VK methods; nested request parameters must be JSON encoded explicitly.
165
193
 
@@ -212,6 +240,53 @@ Partial handler failures, restarts and multiple workers can repeat side effects;
212
240
  is not a durable queue or an exactly-once processing guarantee. See the architecture
213
241
  for delivery limitations and resource limits.
214
242
 
243
+ ## Media and location
244
+
245
+ With an initialized bot:
246
+
247
+ ```python
248
+ from pathlib import Path
249
+
250
+ photo = await bot.upload_photo(peer_id, Path("map.png"))
251
+ message_id = await bot.send_message(peer_id, "Map", attachment=photo, keyboard=keyboard)
252
+
253
+ document = await bot.upload_document(peer_id, Path("report.pdf"))
254
+ await bot.send_message(peer_id, "Report", attachment=document)
255
+
256
+ await bot.edit_message_media(
257
+ peer_id,
258
+ new_png_bytes,
259
+ message_id=message_id,
260
+ caption="Updated map",
261
+ keyboard=keyboard,
262
+ filename="map.png",
263
+ )
264
+ ```
265
+
266
+ Uploads accept bytes, `Path` and binary file objects. Files are read off the event loop
267
+ and buffered in memory; use inputs that fit comfortably in memory. Existing attachment
268
+ identifiers can be passed directly to send/edit methods, and a saved photo passed to
269
+ `edit_message_media` skips uploading. Supply the desired caption and keyboard explicitly;
270
+ there is no automatic fallback send when editing fails.
271
+
272
+ Incoming `message.attachments` remain raw dictionaries. Use `message.typed_attachments`
273
+ for `PhotoAttachment`, `DocumentAttachment`, `VideoAttachment`, `AudioMessageAttachment`
274
+ or a generic `Attachment` preserving unknown fields. With `message.geo is not None`,
275
+ read `message.geo.coordinates.latitude` and `.longitude`; `filters.LOCATION` selects
276
+ these messages. Incomplete coordinate objects fail validation.
277
+
278
+ See the [media API guide](docs/development/media-api.md) for incoming attachment examples,
279
+ deletion, errors and VK restrictions, and [interactive_map.py](examples/interactive_map.py)
280
+ for a PNG grid with navigation buttons. Enable `message_new` and `message_event`, then run:
281
+
282
+ ```bash
283
+ uv run python examples/interactive_map.py
284
+ ```
285
+
286
+ The media API has network-free regression tests. Actual replacement of a photo in an
287
+ existing VK message has not yet been verified with a live token; an explicitly enabled
288
+ [integration test](docs/development/media-api.md#live-integration-test) is provided.
289
+
215
290
  ## Agent Skills
216
291
 
217
292
  The bundled **telegram-to-vk** Agent Skill helps AI coding agents migrate
@@ -234,4 +309,5 @@ checkout, and usage examples.
234
309
  - [python-telegram-bot design mapping](docs/architecture/python-telegram-bot-compatibility.md)
235
310
  - [VK API support](docs/development/api-compatibility.md)
236
311
  - [Contributing and verification](CONTRIBUTING.md)
312
+ - [Python compatibility branches](docs/development/python-compatibility.md)
237
313
  - [Changelog](CHANGELOG.md)
@@ -1,24 +1,26 @@
1
- python_vk_bot/__init__.py,sha256=4Qy_CyBUsznCQJ5h3I2VVLMQNWUoTlQc5mOCjYVUMIM,693
1
+ python_vk_bot/__init__.py,sha256=K13sH66cbtWhwr-yB2TcrW5f7L2W0pe4rhCueBDCA50,1094
2
2
  python_vk_bot/_config.py,sha256=Rju-sjCKAfk70ajQbpPMzOuefBIjtgF8tKjOuSYo0AE,744
3
3
  python_vk_bot/application.py,sha256=rHjKVJRUTGwqgpp7DRJrZOV1eP-_LZ9_ei90EYsTQcs,8741
4
- python_vk_bot/bot.py,sha256=rZgunz4lG-P2EFxLMuTl3Smory8soeIbe00YOVkyJ78,6386
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=pzsnUSdJsVLCAsCeItf0L804HclyDtzG2laZrLlHDpk,445
7
- python_vk_bot/errors.py,sha256=36sWLepB5JoZh2-n89wA2CiaEzbKES86Qc818dLkfCw,1148
7
+ python_vk_bot/errors.py,sha256=qWA1OwH0HOIzZiL3LUBHKE5dMNkphNRIUKQ9OcLmqC0,1267
8
8
  python_vk_bot/filters.py,sha256=5fpOdxTZvFmrgokWUvYj1nowCWvPlLt9EUhRmB-0HVg,1285
9
9
  python_vk_bot/handlers.py,sha256=iG91bzA40evZFY6Qp78nvoz_O4pjG0lE6p1IwLuCQSY,1974
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/settings.py,sha256=JcbDihGRJGRGvBBSeB3j_LPaoX7dkPHfh-WviKQCrwk,915
13
- python_vk_bot/transport.py,sha256=sfNIEtiKGvaUgU2wm4IrWjrIU1CXMwtR9TnaoBXUzfM,5833
13
+ python_vk_bot/transport.py,sha256=eVsq0_brPXQ0Yk1ngMhiWHD9Z6S5Y1NhH193jbMTkmE,9812
14
14
  python_vk_bot/.agents/skills/telegram-to-vk/SKILL.md,sha256=WMrNoxLkhhlu8wnS9rFpZi3OlwBlVNHCYFSNtKmkJzM,2828
15
15
  python_vk_bot/.agents/skills/telegram-to-vk/references/migration-mapping.md,sha256=KFxmCQyKbUK7Z0JuS39FocyoFdtnslLLp9j2pNeJAds,9019
16
- python_vk_bot/models/__init__.py,sha256=L9huCyAM2WWt5JKXyaC8dS0OfTydubdtrGUmvvTnyak,196
17
- python_vk_bot/models/api.py,sha256=WrPGsBOIO1yFD376b0nlVY75rZWhJPXEJ4VzZeUW6uI,931
16
+ python_vk_bot/models/__init__.py,sha256=znIpo8F8TrxEGxeEkAkA-M5qp6aqH-NPRNdblgOBBsk,638
17
+ python_vk_bot/models/api.py,sha256=jY9pedj7TZQkt9bRROUo8rMrO2PyAO7DPJz7E1YphYs,1626
18
+ python_vk_bot/models/attachments.py,sha256=5JWHv37BtSzRI9j_z_yAHToJ61EyBxqRjYp7Y7rP-1o,3887
18
19
  python_vk_bot/models/base.py,sha256=LYcbevtU8jq5QVLo8b1mOv70RzgEYjPtTmhMMe-JN3A,249
19
20
  python_vk_bot/models/events.py,sha256=bS8XC0TJrj_AG0u6H9fs35kMkg47EeVoxtaUH7ya1gM,2222
20
- python_vk_bot/models/messages.py,sha256=CmchlimGmKfj_i-ogHPDZbAk0vPwHKUymfMr_bsWlPc,1223
21
- python_vk_bot-0.1.0.dist-info/METADATA,sha256=61pB87s_jpj9l0CI6CvvMe-r_av1dGnwonXWexwQJ9Y,8275
22
- python_vk_bot-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
23
- python_vk_bot-0.1.0.dist-info/licenses/LICENSE,sha256=F-35ycqPcYW243OjxMHCggr_AHQgZLX2zvtZgobVEvo,1072
24
- python_vk_bot-0.1.0.dist-info/RECORD,,
21
+ python_vk_bot/models/keyboards.py,sha256=ZtwBLSbd-DROuohl9mM0Ui4i7FRUzXVePnfDnmkYzvc,2395
22
+ python_vk_bot/models/messages.py,sha256=WAUsa7VMDNl0xK2LXa91kg6RQsWBXoQATI1aAMDiHLU,1543
23
+ python_vk_bot-0.3.0.dist-info/METADATA,sha256=E40KM33dn9qnJv51LV8dAkGJ8rdQIlEGDURo2nsUXkY,11789
24
+ python_vk_bot-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
25
+ python_vk_bot-0.3.0.dist-info/licenses/LICENSE,sha256=F-35ycqPcYW243OjxMHCggr_AHQgZLX2zvtZgobVEvo,1072
26
+ python_vk_bot-0.3.0.dist-info/RECORD,,