pybinbot 2.1.15__tar.gz → 2.1.17__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 (91) hide show
  1. {pybinbot-2.1.15/pybinbot.egg-info → pybinbot-2.1.17}/PKG-INFO +14 -1
  2. {pybinbot-2.1.15 → pybinbot-2.1.17}/README.md +13 -0
  3. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/telegram_delivery.py +76 -48
  4. {pybinbot-2.1.15 → pybinbot-2.1.17/pybinbot.egg-info}/PKG-INFO +14 -1
  5. {pybinbot-2.1.15 → pybinbot-2.1.17}/pyproject.toml +1 -1
  6. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_telegram_delivery.py +111 -2
  7. {pybinbot-2.1.15 → pybinbot-2.1.17}/LICENSE +0 -0
  8. {pybinbot-2.1.15 → pybinbot-2.1.17}/MANIFEST.in +0 -0
  9. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/__init__.py +0 -0
  10. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/apis/binance/base.py +0 -0
  11. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/apis/binance/exceptions.py +0 -0
  12. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/apis/binbot/base.py +0 -0
  13. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/apis/binbot/exceptions.py +0 -0
  14. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/apis/coingecko.py +0 -0
  15. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/apis/kucoin/base.py +0 -0
  16. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/apis/kucoin/exceptions.py +0 -0
  17. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/apis/kucoin/futures.py +0 -0
  18. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/apis/kucoin/market.py +0 -0
  19. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/apis/kucoin/orders.py +0 -0
  20. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/apis/kucoin/rest.py +0 -0
  21. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/__init__.py +0 -0
  22. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/autotrade_settings.py +0 -0
  23. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/bot.py +0 -0
  24. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/bot_base.py +0 -0
  25. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/cvd.py +0 -0
  26. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/deal.py +0 -0
  27. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/derivatives.py +0 -0
  28. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/fastest_movers.py +0 -0
  29. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/futures_market.py +0 -0
  30. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/grid_ladder.py +0 -0
  31. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/order.py +0 -0
  32. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/routes.py +0 -0
  33. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/signals.py +0 -0
  34. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/models/symbol.py +0 -0
  35. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/py.typed +0 -0
  36. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/__init__.py +0 -0
  37. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/beta.py +0 -0
  38. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/breadth.py +0 -0
  39. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/cache.py +0 -0
  40. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/candles.py +0 -0
  41. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/enums.py +0 -0
  42. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/handlers.py +0 -0
  43. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/heikin_ashi.py +0 -0
  44. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/indicators.py +0 -0
  45. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/logging_config.py +0 -0
  46. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/maths.py +0 -0
  47. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/price_crossings.py +0 -0
  48. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/timestamps.py +0 -0
  49. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/types.py +0 -0
  50. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/shared/utils.py +0 -0
  51. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/strategy/beta.py +0 -0
  52. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/strategy/breadth.py +0 -0
  53. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/strategy/price_crossings.py +0 -0
  54. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/strategy/swing_protection.py +0 -0
  55. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/streaming/binance/async_socket_client.py +0 -0
  56. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/streaming/binance/socket_client.py +0 -0
  57. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/streaming/binance/socket_manager.py +0 -0
  58. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot/streaming/kucoin/kucoin_async_client.py +0 -0
  59. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot.egg-info/SOURCES.txt +0 -0
  60. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot.egg-info/dependency_links.txt +0 -0
  61. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot.egg-info/requires.txt +0 -0
  62. {pybinbot-2.1.15 → pybinbot-2.1.17}/pybinbot.egg-info/top_level.txt +0 -0
  63. {pybinbot-2.1.15 → pybinbot-2.1.17}/setup.cfg +0 -0
  64. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_beta.py +0 -0
  65. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_binbot_api.py +0 -0
  66. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_bot_futures_leverage.py +0 -0
  67. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_breadth.py +0 -0
  68. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_candles.py +0 -0
  69. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_closed_bot_status.py +0 -0
  70. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_coingecko.py +0 -0
  71. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_conditional_entry.py +0 -0
  72. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_conditional_futures_orders.py +0 -0
  73. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_cvd_api.py +0 -0
  74. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_deal_model.py +0 -0
  75. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_derivatives_api.py +0 -0
  76. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_fastest_movers.py +0 -0
  77. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_futures_market_api.py +0 -0
  78. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_futures_place_order.py +0 -0
  79. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_grid_ladder.py +0 -0
  80. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_handlers.py +0 -0
  81. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_heikin_ashi.py +0 -0
  82. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_indicators.py +0 -0
  83. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_kucoin_api.py +0 -0
  84. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_logging_config.py +0 -0
  85. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_matching_engine.py +0 -0
  86. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_maths.py +0 -0
  87. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_price_crossings.py +0 -0
  88. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_swing_protection.py +0 -0
  89. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_symbol_model.py +0 -0
  90. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_timestamps.py +0 -0
  91. {pybinbot-2.1.15 → pybinbot-2.1.17}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pybinbot
3
- Version: 2.1.15
3
+ Version: 2.1.17
4
4
  Summary: Utility functions for the binbot project.
5
5
  Author-email: Carlos Wu <carkodw@gmail.com>
6
6
  Requires-Python: >=3.15
@@ -106,6 +106,19 @@ rate-limit retries and optional spacing configured at initialization. Both use
106
106
  HTML formatting and disable link previews. Delivery does not persist messages.
107
107
  The Telegram library is installed as a dependency of pybinbot.
108
108
 
109
+ Use `await send_message(message, reply_markup=..., reply_to_message_id=...)`
110
+ when the caller needs Telegram's delivered `Message` (including `message_id`) or
111
+ must handle delivery errors itself. It shares HTML formatting, preview settings,
112
+ spacing and `expires_at` deadlines with `send`, but raises failures and does not
113
+ retry rate limits unless `retry_on_rate_limit=True`. Timed-out sends are never
114
+ retried because delivery may already have succeeded.
115
+
116
+ Pass `bot=existing_bot` and an explicit `chat_id` to reuse an initialized client;
117
+ the caller remains responsible for its initialization and shutdown. An explicit
118
+ `token` overrides environment configuration, including for dedicated agent bots.
119
+ Delivery does not receive callbacks, persist approvals or authorize updates;
120
+ those remain application responsibilities.
121
+
109
122
 
110
123
  ## Publishing
111
124
 
@@ -77,6 +77,19 @@ rate-limit retries and optional spacing configured at initialization. Both use
77
77
  HTML formatting and disable link previews. Delivery does not persist messages.
78
78
  The Telegram library is installed as a dependency of pybinbot.
79
79
 
80
+ Use `await send_message(message, reply_markup=..., reply_to_message_id=...)`
81
+ when the caller needs Telegram's delivered `Message` (including `message_id`) or
82
+ must handle delivery errors itself. It shares HTML formatting, preview settings,
83
+ spacing and `expires_at` deadlines with `send`, but raises failures and does not
84
+ retry rate limits unless `retry_on_rate_limit=True`. Timed-out sends are never
85
+ retried because delivery may already have succeeded.
86
+
87
+ Pass `bot=existing_bot` and an explicit `chat_id` to reuse an initialized client;
88
+ the caller remains responsible for its initialization and shutdown. An explicit
89
+ `token` overrides environment configuration, including for dedicated agent bots.
90
+ Delivery does not receive callbacks, persist approvals or authorize updates;
91
+ those remain application responsibilities.
92
+
80
93
 
81
94
  ## Publishing
82
95
 
@@ -9,7 +9,7 @@ import time
9
9
 
10
10
  from dotenv import find_dotenv, load_dotenv
11
11
  from requests import post
12
- from telegram import Bot, LinkPreviewOptions
12
+ from telegram import Bot, InlineKeyboardMarkup, LinkPreviewOptions, Message
13
13
  from telegram.constants import ParseMode
14
14
  from telegram.error import RetryAfter, TimedOut
15
15
  from telegram.helpers import escape
@@ -21,15 +21,21 @@ class TelegramDelivery:
21
21
  def __init__(
22
22
  self,
23
23
  token: str | None = None,
24
- chat_id: str | None = None,
24
+ chat_id: str | int | None = None,
25
25
  *,
26
+ bot: Bot | None = None,
26
27
  min_send_interval_seconds: float = 0,
27
28
  retry_after_pad_seconds: float = 2,
28
29
  ) -> None:
29
- load_dotenv(find_dotenv(usecwd=True))
30
+ if token is None and bot is not None:
31
+ token = bot.token
32
+ if token is None or chat_id is None:
33
+ load_dotenv(find_dotenv(usecwd=True))
30
34
  self.token = os.getenv("TELEGRAM_BOT_KEY", "") if token is None else token
31
35
  self.chat_id = os.getenv("TELEGRAM_USER_ID", "") if chat_id is None else chat_id
32
- self.bot = Bot(token=self.token) if self.token else None
36
+ self.bot = bot
37
+ if self.bot is None and self.token:
38
+ self.bot = Bot(token=self.token)
33
39
  self._send_lock = asyncio.Lock()
34
40
  self._min_send_interval_seconds = min_send_interval_seconds
35
41
  self._retry_after_pad_seconds = retry_after_pad_seconds
@@ -93,54 +99,76 @@ class TelegramDelivery:
93
99
  """Deliver within an optional deadline, including time spent waiting to send."""
94
100
  if not self.token or not self.chat_id or self.bot is None:
95
101
  return False
96
- remaining = expires_at.timestamp() - time.time() if expires_at else None
97
- if remaining is not None and remaining <= 0:
98
- return False
99
102
  try:
100
- async with asyncio.timeout(remaining):
101
- async with self._send_lock:
102
- while True:
103
- await self._sleep_for_send_interval()
104
- if (
105
- expires_at is not None
106
- and time.time() >= expires_at.timestamp()
107
- ):
108
- return False
109
- try:
110
- await self.bot.send_message(
111
- self.chat_id,
112
- text=self._sanitize_html(message),
113
- parse_mode=ParseMode.HTML,
114
- link_preview_options=LinkPreviewOptions(
115
- is_disabled=True
116
- ),
117
- )
118
- self._last_send_at = time.monotonic()
119
- return True
120
- except RetryAfter as e:
121
- if not retry_on_rate_limit:
122
- logging.warning(
123
- "Telegram rate limited; skipping one-shot alert"
124
- )
125
- return False
126
- retry_after = self._retry_after_seconds(e)
127
- sleep_seconds = retry_after + self._retry_after_pad_seconds
128
- logging.warning(
129
- "Telegram flood control active; retrying message in %.1f seconds",
130
- sleep_seconds,
131
- )
132
- await asyncio.sleep(sleep_seconds)
133
- except TimedOut:
134
- logging.warning("Telegram message timed out; skipping")
135
- return False
136
- except Exception as exc:
137
- logging.warning(
138
- "Telegram delivery failed (%s)", type(exc).__name__
139
- )
140
- return False
103
+ await self.send_message(
104
+ message,
105
+ expires_at=expires_at,
106
+ retry_on_rate_limit=retry_on_rate_limit,
107
+ )
108
+ return True
109
+ except RetryAfter:
110
+ logging.warning("Telegram rate limited; skipping one-shot alert")
111
+ return False
112
+ except TimedOut:
113
+ logging.warning("Telegram message timed out; skipping")
114
+ return False
141
115
  except TimeoutError:
142
116
  logging.info("Telegram alert expired before delivery completed; skipping")
143
117
  return False
118
+ except Exception as exc:
119
+ logging.warning("Telegram delivery failed (%s)", type(exc).__name__)
120
+ return False
121
+
122
+ async def send_message(
123
+ self,
124
+ message: str,
125
+ *,
126
+ reply_markup: InlineKeyboardMarkup | None = None,
127
+ reply_to_message_id: int | None = None,
128
+ expires_at: datetime | None = None,
129
+ retry_on_rate_limit: bool = False,
130
+ ) -> Message:
131
+ """Return the delivered message or raise; the caller owns an injected bot.
132
+
133
+ A deadline includes queueing, pacing and network time. Only rate-limit
134
+ rejections may be retried, when explicitly enabled; ambiguous failures
135
+ such as a timed-out send are never retried.
136
+ """
137
+ if not self.chat_id or self.bot is None:
138
+ raise ValueError("Telegram delivery requires a bot and destination chat")
139
+ remaining = expires_at.timestamp() - time.time() if expires_at else None
140
+ if remaining is not None and remaining <= 0:
141
+ raise TimeoutError("Telegram message expired before delivery")
142
+ async with asyncio.timeout(remaining):
143
+ async with self._send_lock:
144
+ while True:
145
+ await self._sleep_for_send_interval()
146
+ if expires_at is not None and time.time() >= expires_at.timestamp():
147
+ raise TimeoutError("Telegram message expired before delivery")
148
+ try:
149
+ sent = await self.bot.send_message(
150
+ chat_id=self.chat_id,
151
+ text=self._sanitize_html(message),
152
+ parse_mode=ParseMode.HTML,
153
+ link_preview_options=LinkPreviewOptions(is_disabled=True),
154
+ reply_markup=reply_markup,
155
+ reply_to_message_id=reply_to_message_id,
156
+ )
157
+ except RetryAfter as error:
158
+ if not retry_on_rate_limit:
159
+ raise
160
+ sleep_seconds = (
161
+ self._retry_after_seconds(error)
162
+ + self._retry_after_pad_seconds
163
+ )
164
+ logging.warning(
165
+ "Telegram flood control active; retrying message in %.1f seconds",
166
+ sleep_seconds,
167
+ )
168
+ await asyncio.sleep(sleep_seconds)
169
+ else:
170
+ self._last_send_at = time.monotonic()
171
+ return sent
144
172
 
145
173
  def send_once(self, message: str) -> bool:
146
174
  """Attempt an ephemeral synchronous delivery, without retries or cooldowns."""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pybinbot
3
- Version: 2.1.15
3
+ Version: 2.1.17
4
4
  Summary: Utility functions for the binbot project.
5
5
  Author-email: Carlos Wu <carkodw@gmail.com>
6
6
  Requires-Python: >=3.15
@@ -106,6 +106,19 @@ rate-limit retries and optional spacing configured at initialization. Both use
106
106
  HTML formatting and disable link previews. Delivery does not persist messages.
107
107
  The Telegram library is installed as a dependency of pybinbot.
108
108
 
109
+ Use `await send_message(message, reply_markup=..., reply_to_message_id=...)`
110
+ when the caller needs Telegram's delivered `Message` (including `message_id`) or
111
+ must handle delivery errors itself. It shares HTML formatting, preview settings,
112
+ spacing and `expires_at` deadlines with `send`, but raises failures and does not
113
+ retry rate limits unless `retry_on_rate_limit=True`. Timed-out sends are never
114
+ retried because delivery may already have succeeded.
115
+
116
+ Pass `bot=existing_bot` and an explicit `chat_id` to reuse an initialized client;
117
+ the caller remains responsible for its initialization and shutdown. An explicit
118
+ `token` overrides environment configuration, including for dedicated agent bots.
119
+ Delivery does not receive callbacks, persist approvals or authorize updates;
120
+ those remain application responsibilities.
121
+
109
122
 
110
123
  ## Publishing
111
124
 
@@ -23,7 +23,7 @@ build-backend = "setuptools.build_meta"
23
23
 
24
24
  [project]
25
25
  name = "pybinbot"
26
- version = "2.1.15"
26
+ version = "2.1.17"
27
27
  description = "Utility functions for the binbot project."
28
28
  authors = [
29
29
  { name="Carlos Wu", email="carkodw@gmail.com" }
@@ -1,9 +1,10 @@
1
1
  import asyncio
2
2
  from datetime import UTC, datetime, timedelta
3
- from unittest.mock import AsyncMock, patch
3
+ from unittest.mock import AsyncMock, Mock, patch
4
4
 
5
5
  import pytest
6
- from telegram.error import RetryAfter
6
+ from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup, Message
7
+ from telegram.error import BadRequest, RetryAfter, TimedOut
7
8
 
8
9
  from pybinbot.shared.telegram_delivery import TelegramDelivery
9
10
 
@@ -147,3 +148,111 @@ async def test_delivery_deadline_cancels_a_stalled_request():
147
148
  is False
148
149
  )
149
150
  assert cancelled.is_set()
151
+
152
+
153
+ @pytest.mark.asyncio
154
+ async def test_message_delivery_reuses_the_callers_bot_and_returns_its_receipt(
155
+ monkeypatch,
156
+ ):
157
+ monkeypatch.setenv("TELEGRAM_BOT_KEY", "signal-token")
158
+ sent = Mock(spec=Message, message_id=42)
159
+ client = Mock(
160
+ spec=Bot,
161
+ token="agent-token",
162
+ send_message=AsyncMock(return_value=sent),
163
+ initialize=AsyncMock(),
164
+ shutdown=AsyncMock(),
165
+ )
166
+ buttons = InlineKeyboardMarkup(
167
+ [[InlineKeyboardButton("Approve", callback_data="approve:42")]]
168
+ )
169
+ with patch("pybinbot.shared.telegram_delivery.Bot") as constructor:
170
+ delivery = TelegramDelivery(bot=client, chat_id=123)
171
+ receipt = await delivery.send_message(
172
+ '<b>Proposal</b> <a href="https://example.com">Dashboard</a> ratio <= 1',
173
+ reply_markup=buttons,
174
+ reply_to_message_id=17,
175
+ )
176
+ assert delivery.token == "agent-token"
177
+ assert receipt is sent
178
+ assert receipt.message_id == 42
179
+ constructor.assert_not_called()
180
+ client.initialize.assert_not_awaited()
181
+ client.shutdown.assert_not_awaited()
182
+ client.send_message.assert_awaited_once()
183
+ kwargs = client.send_message.await_args.kwargs
184
+ assert kwargs["chat_id"] == 123
185
+ assert kwargs["reply_markup"] is buttons
186
+ assert kwargs["reply_to_message_id"] == 17
187
+ assert kwargs["text"] == (
188
+ '<b>Proposal</b> <a href="https://example.com">Dashboard</a> ratio &lt;= 1'
189
+ )
190
+ assert kwargs["parse_mode"] == "HTML"
191
+ assert kwargs["link_preview_options"].is_disabled is True
192
+
193
+
194
+ def test_explicit_agent_token_overrides_the_signal_bot_environment(monkeypatch):
195
+ monkeypatch.setenv("TELEGRAM_BOT_KEY", "signal-token")
196
+ with patch("pybinbot.shared.telegram_delivery.Bot") as constructor:
197
+ delivery = TelegramDelivery(token="agent-token", chat_id=123)
198
+ constructor.assert_called_once_with(token="agent-token")
199
+ assert delivery.token == "agent-token"
200
+
201
+
202
+ @pytest.mark.asyncio
203
+ @pytest.mark.parametrize("error", [RetryAfter(60), TimedOut(), BadRequest("rejected")])
204
+ async def test_message_delivery_propagates_failures_without_retrying(error):
205
+ client = Mock(
206
+ spec=Bot, token="agent-token", send_message=AsyncMock(side_effect=error)
207
+ )
208
+ delivery = TelegramDelivery(bot=client, chat_id=123)
209
+ with pytest.raises(type(error)) as caught:
210
+ await delivery.send_message("Proposal")
211
+ assert caught.value is error
212
+ client.send_message.assert_awaited_once()
213
+
214
+
215
+ @pytest.mark.asyncio
216
+ async def test_rate_limit_retry_stays_within_the_message_delivery_deadline():
217
+ client = Mock(
218
+ spec=Bot,
219
+ token="agent-token",
220
+ send_message=AsyncMock(side_effect=RetryAfter(60)),
221
+ )
222
+ delivery = TelegramDelivery(bot=client, chat_id=123)
223
+ with pytest.raises(TimeoutError):
224
+ await delivery.send_message(
225
+ "Proposal",
226
+ expires_at=datetime.now(UTC) + timedelta(milliseconds=20),
227
+ retry_on_rate_limit=True,
228
+ )
229
+ client.send_message.assert_awaited_once()
230
+
231
+
232
+ @pytest.mark.asyncio
233
+ async def test_delivery_cancellation_reaches_the_callers_task():
234
+ client = Mock(
235
+ spec=Bot,
236
+ token="agent-token",
237
+ send_message=AsyncMock(side_effect=asyncio.CancelledError),
238
+ )
239
+ delivery = TelegramDelivery(bot=client, chat_id=123)
240
+ with pytest.raises(asyncio.CancelledError):
241
+ await delivery.send("Signal")
242
+ client.send_message.assert_awaited_once()
243
+
244
+
245
+ @pytest.mark.asyncio
246
+ async def test_boolean_delivery_reports_failure_without_logging_credentials(caplog):
247
+ caplog.set_level("WARNING")
248
+ client = Mock(
249
+ spec=Bot,
250
+ token="agent-token",
251
+ send_message=AsyncMock(
252
+ side_effect=BadRequest("https://api.telegram.org/agent-token")
253
+ ),
254
+ )
255
+ delivery = TelegramDelivery(bot=client, chat_id=123)
256
+ assert await delivery.send("Signal") is False
257
+ assert "BadRequest" in caplog.text
258
+ assert "agent-token" not in caplog.text
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes