python-vk-bot 0.5.0__py3-none-any.whl → 0.6.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
 
@@ -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)
@@ -30,18 +30,18 @@ class ButtonType(StrEnum):
30
30
 
31
31
  TEXT = "text"
32
32
  CALLBACK = "callback"
33
+ OPEN_LINK = "open_link"
34
+ LOCATION = "location"
33
35
 
34
36
 
35
- class _LabeledButton(BaseModel):
37
+ class _Button(BaseModel):
36
38
  model_config = ConfigDict(
37
39
  extra="forbid", validate_assignment=True, hide_input_in_errors=True, allow_inf_nan=False
38
40
  )
39
41
 
40
- label: str = Field(repr=False)
41
42
  payload: dict[str, JsonValue] | SerializeAsAny[BaseModel] | str | None = Field(
42
43
  default=None, repr=False
43
44
  )
44
- color: ButtonColor = ButtonColor.SECONDARY
45
45
 
46
46
  @field_serializer("payload", when_used="json")
47
47
  def serialize_payload(self, value: dict[str, JsonValue] | BaseModel | str | None) -> str | None:
@@ -63,6 +63,11 @@ class _LabeledButton(BaseModel):
63
63
  return button
64
64
 
65
65
 
66
+ class _LabeledButton(_Button):
67
+ label: str = Field(repr=False)
68
+ color: ButtonColor = ButtonColor.SECONDARY
69
+
70
+
66
71
  class TextButton(_LabeledButton):
67
72
  """Send the label and optional payload as a message, handled by MessageHandler."""
68
73
 
@@ -75,4 +80,20 @@ class CallbackButton(_LabeledButton):
75
80
  type: Literal[ButtonType.CALLBACK] = ButtonType.CALLBACK
76
81
 
77
82
 
78
- type TypedButton = Annotated[TextButton | CallbackButton, Field(discriminator="type")]
83
+ class OpenLinkButton(_Button):
84
+ """Open a URL using VK's link action, without a configurable color."""
85
+
86
+ type: Literal[ButtonType.OPEN_LINK] = ButtonType.OPEN_LINK
87
+ label: str = Field(repr=False)
88
+ link: str = Field(repr=False)
89
+
90
+
91
+ class LocationButton(_Button):
92
+ """Let the user choose a location and send it as a message with geo data."""
93
+
94
+ type: Literal[ButtonType.LOCATION] = ButtonType.LOCATION
95
+
96
+
97
+ type TypedButton = Annotated[
98
+ TextButton | CallbackButton | OpenLinkButton | LocationButton, Field(discriminator="type")
99
+ ]
@@ -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.6.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,29 @@
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
10
  python_vk_bot/long_poll.py,sha256=rmAxflq0E3H-tMDybQ7fBf1cKsJQFnaU4VbyQS3BSw4,3777
11
11
  python_vk_bot/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
12
  python_vk_bot/queues.py,sha256=9OCfYBpOpcJBbW-7TwsIb18raJN2pueZbXoJUgu7MOc,2861
13
13
  python_vk_bot/settings.py,sha256=JcbDihGRJGRGvBBSeB3j_LPaoX7dkPHfh-WviKQCrwk,915
14
- python_vk_bot/transport.py,sha256=eVsq0_brPXQ0Yk1ngMhiWHD9Z6S5Y1NhH193jbMTkmE,9812
14
+ python_vk_bot/transport.py,sha256=kdf9NRpZ2KM2yP2IGNAASfJagGvJOcgoEPpj-V9nudM,11936
15
15
  python_vk_bot/.agents/skills/telegram-to-vk/SKILL.md,sha256=WMrNoxLkhhlu8wnS9rFpZi3OlwBlVNHCYFSNtKmkJzM,2828
16
16
  python_vk_bot/.agents/skills/telegram-to-vk/references/migration-mapping.md,sha256=KFxmCQyKbUK7Z0JuS39FocyoFdtnslLLp9j2pNeJAds,9019
17
- python_vk_bot/models/__init__.py,sha256=eAdbM08JcoYv6JPrdorVC6DvEfxhgp-5h9pXFa3B7iQ,772
17
+ python_vk_bot/models/__init__.py,sha256=exCkuHNIqRGVDjinpi0afpdgEvoPbz4JWeQzimw7c0w,937
18
18
  python_vk_bot/models/api.py,sha256=jY9pedj7TZQkt9bRROUo8rMrO2PyAO7DPJz7E1YphYs,1626
19
19
  python_vk_bot/models/attachments.py,sha256=5JWHv37BtSzRI9j_z_yAHToJ61EyBxqRjYp7Y7rP-1o,3887
20
20
  python_vk_bot/models/base.py,sha256=LYcbevtU8jq5QVLo8b1mOv70RzgEYjPtTmhMMe-JN3A,249
21
21
  python_vk_bot/models/donut.py,sha256=qV9OyjDbmTi2UJqvzfXOL6LqYMxZvFwJo2yI1dcLSi0,1373
22
+ python_vk_bot/models/event_answers.py,sha256=BApsLwOySfcr3aLUazQo8rryEsitT3jaEGTQpuVIk14,445
22
23
  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/keyboards.py,sha256=JZ61_Z4VhyvyI9lTk8aNlyuco5z4hQOlDmWR8xS8srw,2932
24
25
  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,,
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,,