pybinbot 2.1.15__tar.gz → 2.1.18__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.
- {pybinbot-2.1.15/pybinbot.egg-info → pybinbot-2.1.18}/PKG-INFO +14 -1
- {pybinbot-2.1.15 → pybinbot-2.1.18}/README.md +13 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/apis/binbot/base.py +93 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/telegram_delivery.py +76 -48
- {pybinbot-2.1.15 → pybinbot-2.1.18/pybinbot.egg-info}/PKG-INFO +14 -1
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot.egg-info/SOURCES.txt +1 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pyproject.toml +1 -1
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_binbot_api.py +6 -1
- pybinbot-2.1.18/tests/test_binbot_read_methods.py +194 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_telegram_delivery.py +111 -2
- {pybinbot-2.1.15 → pybinbot-2.1.18}/LICENSE +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/MANIFEST.in +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/__init__.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/apis/binance/base.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/apis/binance/exceptions.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/apis/binbot/exceptions.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/apis/coingecko.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/apis/kucoin/base.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/apis/kucoin/exceptions.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/apis/kucoin/futures.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/apis/kucoin/market.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/apis/kucoin/orders.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/apis/kucoin/rest.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/__init__.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/autotrade_settings.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/bot.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/bot_base.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/cvd.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/deal.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/derivatives.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/fastest_movers.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/futures_market.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/grid_ladder.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/order.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/routes.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/signals.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/models/symbol.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/py.typed +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/__init__.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/beta.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/breadth.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/cache.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/candles.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/enums.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/handlers.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/heikin_ashi.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/indicators.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/logging_config.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/maths.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/price_crossings.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/timestamps.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/types.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/shared/utils.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/strategy/beta.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/strategy/breadth.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/strategy/price_crossings.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/strategy/swing_protection.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/streaming/binance/async_socket_client.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/streaming/binance/socket_client.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/streaming/binance/socket_manager.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot/streaming/kucoin/kucoin_async_client.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot.egg-info/dependency_links.txt +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot.egg-info/requires.txt +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/pybinbot.egg-info/top_level.txt +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/setup.cfg +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_beta.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_bot_futures_leverage.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_breadth.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_candles.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_closed_bot_status.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_coingecko.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_conditional_entry.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_conditional_futures_orders.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_cvd_api.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_deal_model.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_derivatives_api.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_fastest_movers.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_futures_market_api.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_futures_place_order.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_grid_ladder.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_handlers.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_heikin_ashi.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_indicators.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_kucoin_api.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_logging_config.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_matching_engine.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_maths.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_price_crossings.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_swing_protection.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_symbol_model.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_timestamps.py +0 -0
- {pybinbot-2.1.15 → pybinbot-2.1.18}/tests/test_utils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pybinbot
|
|
3
|
-
Version: 2.1.
|
|
3
|
+
Version: 2.1.18
|
|
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
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import asyncio
|
|
2
2
|
import logging
|
|
3
3
|
from typing import Any
|
|
4
|
+
from uuid import UUID
|
|
4
5
|
from aiohttp import ClientSession
|
|
5
6
|
from requests import Session
|
|
6
7
|
from pybinbot import (
|
|
@@ -31,6 +32,12 @@ from dateutil.parser import parse
|
|
|
31
32
|
from pybinbot.models.cvd import CvdAggregateResponse, CvdSymbolResponse
|
|
32
33
|
from pybinbot.models.fastest_movers import FastestMoversResponse, FastestMoversSnapshot
|
|
33
34
|
from pybinbot.models.futures_market import FuturesMarketSnapshot
|
|
35
|
+
from pybinbot.models.bot import BotListResponse
|
|
36
|
+
from pybinbot.models.signals import SignalListRecord, SignalListResponse
|
|
37
|
+
from pybinbot.apis.binbot.exceptions import BinbotErrors
|
|
38
|
+
from kucoin_universal_sdk.generate.futures.positions.model_get_position_details_resp import (
|
|
39
|
+
GetPositionDetailsResp,
|
|
40
|
+
)
|
|
34
41
|
|
|
35
42
|
logger = logging.getLogger(__name__)
|
|
36
43
|
|
|
@@ -80,6 +87,7 @@ class BinbotApi:
|
|
|
80
87
|
self.bb_market_breadth_url = f"{bb_base_url}/charts/market-breadth"
|
|
81
88
|
self.bb_cvd_symbol_url = f"{bb_base_url}/charts/cvd-symbol"
|
|
82
89
|
self.bb_futures_market_url = f"{bb_base_url}/charts/futures-market"
|
|
90
|
+
self.bb_futures_position_url = f"{bb_base_url}/order/kucoin/futures/position"
|
|
83
91
|
self.bb_cvd_aggregate_url = f"{bb_base_url}/charts/cvd-aggregate"
|
|
84
92
|
self.bb_gainers_losers_series_url = (
|
|
85
93
|
f"{bb_base_url}/charts/gainers-losers-series"
|
|
@@ -290,6 +298,91 @@ class BinbotApi:
|
|
|
290
298
|
response = self.request(url=f"{self.bb_bot_url}/{bot_id}")
|
|
291
299
|
return BotModel.model_validate(response["data"])
|
|
292
300
|
|
|
301
|
+
def get_bots(
|
|
302
|
+
self,
|
|
303
|
+
*,
|
|
304
|
+
status: Status | None = None,
|
|
305
|
+
include_closed: bool = False,
|
|
306
|
+
start_date: int | None = None,
|
|
307
|
+
end_date: int | None = None,
|
|
308
|
+
bot_name: str | None = None,
|
|
309
|
+
page_size: int = 200,
|
|
310
|
+
) -> list[BotModel]:
|
|
311
|
+
"""Return all matching bots, paging through the API and deduplicating UUIDs."""
|
|
312
|
+
if page_size <= 0:
|
|
313
|
+
raise ValueError("page_size must be positive")
|
|
314
|
+
filters = {
|
|
315
|
+
"include_closed": include_closed,
|
|
316
|
+
"status": status.value if status is not None else None,
|
|
317
|
+
"start_date": start_date,
|
|
318
|
+
"end_date": end_date,
|
|
319
|
+
"bot_name": bot_name,
|
|
320
|
+
}
|
|
321
|
+
params = {key: value for key, value in filters.items() if value is not None}
|
|
322
|
+
bots: dict[UUID, BotModel] = {}
|
|
323
|
+
offset = 0
|
|
324
|
+
while True:
|
|
325
|
+
payload = self.request(
|
|
326
|
+
url=self.bb_bot_url,
|
|
327
|
+
params={**params, "limit": page_size, "offset": offset},
|
|
328
|
+
timeout=(5, 30),
|
|
329
|
+
)
|
|
330
|
+
response = BotListResponse.model_validate(payload)
|
|
331
|
+
if response.error:
|
|
332
|
+
raise BinbotErrors(response.message, response.error)
|
|
333
|
+
bots.update((bot.id, bot) for bot in response.data)
|
|
334
|
+
if len(response.data) < page_size:
|
|
335
|
+
return list(bots.values())
|
|
336
|
+
offset += len(response.data)
|
|
337
|
+
|
|
338
|
+
def get_futures_position(self, symbol: str) -> GetPositionDetailsResp:
|
|
339
|
+
"""Read the live KuCoin futures position through binbot's authenticated proxy."""
|
|
340
|
+
response = self.request(
|
|
341
|
+
url=f"{self.bb_futures_position_url}/{symbol.upper()}",
|
|
342
|
+
timeout=(5, 30),
|
|
343
|
+
)
|
|
344
|
+
if response.get("error"):
|
|
345
|
+
raise BinbotErrors(response["message"], response["error"])
|
|
346
|
+
return GetPositionDetailsResp.model_validate(response["data"])
|
|
347
|
+
|
|
348
|
+
def get_signals(
|
|
349
|
+
self,
|
|
350
|
+
*,
|
|
351
|
+
symbol: str | None = None,
|
|
352
|
+
algorithm_name: str | None = None,
|
|
353
|
+
current_regime: str | None = None,
|
|
354
|
+
autotrade: bool | None = None,
|
|
355
|
+
since: datetime | None = None,
|
|
356
|
+
until: datetime | None = None,
|
|
357
|
+
limit: int = 100,
|
|
358
|
+
offset: int = 0,
|
|
359
|
+
include_payload: bool = True,
|
|
360
|
+
) -> list[SignalListRecord]:
|
|
361
|
+
"""Read a typed page of stored signals, including optional indicator payloads."""
|
|
362
|
+
if not 1 <= limit <= 1000 or offset < 0:
|
|
363
|
+
raise ValueError(
|
|
364
|
+
"Signals require limit between 1 and 1000 and a nonnegative offset"
|
|
365
|
+
)
|
|
366
|
+
filters = {
|
|
367
|
+
"symbol": symbol.upper() if symbol is not None else None,
|
|
368
|
+
"algorithm_name": algorithm_name,
|
|
369
|
+
"current_regime": current_regime,
|
|
370
|
+
"autotrade": autotrade,
|
|
371
|
+
"since": since.isoformat() if since is not None else None,
|
|
372
|
+
"until": until.isoformat() if until is not None else None,
|
|
373
|
+
"limit": limit,
|
|
374
|
+
"offset": offset,
|
|
375
|
+
"include_payload": include_payload,
|
|
376
|
+
}
|
|
377
|
+
response = self.request(
|
|
378
|
+
url=self.bb_signals_url,
|
|
379
|
+
params={key: value for key, value in filters.items() if value is not None},
|
|
380
|
+
timeout=(5, 30),
|
|
381
|
+
)
|
|
382
|
+
if response.get("error"):
|
|
383
|
+
raise BinbotErrors(response["message"], response["error"])
|
|
384
|
+
return SignalListResponse.model_validate(response).data
|
|
385
|
+
|
|
293
386
|
def get_futures_market(self, symbol: str) -> FuturesMarketSnapshot:
|
|
294
387
|
"""Read live contract, book, trades and candles for one futures symbol.
|
|
295
388
|
|
|
@@ -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
|
-
|
|
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 =
|
|
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
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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.
|
|
3
|
+
Version: 2.1.18
|
|
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
|
|
|
@@ -60,6 +60,7 @@ pybinbot/streaming/binance/socket_manager.py
|
|
|
60
60
|
pybinbot/streaming/kucoin/kucoin_async_client.py
|
|
61
61
|
tests/test_beta.py
|
|
62
62
|
tests/test_binbot_api.py
|
|
63
|
+
tests/test_binbot_read_methods.py
|
|
63
64
|
tests/test_bot_futures_leverage.py
|
|
64
65
|
tests/test_breadth.py
|
|
65
66
|
tests/test_candles.py
|
|
@@ -9,7 +9,11 @@ from unittest.mock import patch
|
|
|
9
9
|
|
|
10
10
|
from pydantic import BaseModel, ConfigDict, Field, create_model
|
|
11
11
|
|
|
12
|
-
from pybinbot.models.bot import
|
|
12
|
+
from pybinbot.models.bot import (
|
|
13
|
+
BotModel,
|
|
14
|
+
BotListResponse,
|
|
15
|
+
BotResponse as ProductionBotResponse,
|
|
16
|
+
)
|
|
13
17
|
from pybinbot.models.signals import SignalCreate, SignalModel, SignalResponse
|
|
14
18
|
from pybinbot.shared.enums import ExchangeId
|
|
15
19
|
|
|
@@ -183,6 +187,7 @@ def load_binbot_api_class():
|
|
|
183
187
|
|
|
184
188
|
bot_stub = types.ModuleType("pybinbot.models.bot")
|
|
185
189
|
bot_stub.BotModel = _BotModel
|
|
190
|
+
bot_stub.BotListResponse = BotListResponse
|
|
186
191
|
bot_stub.BotResponse = _BotResponse
|
|
187
192
|
bot_stub.ErrorsRequestBody = _ErrorsRequestBody
|
|
188
193
|
bot_stub.BulkDeleteRequest = _BulkDeleteRequest
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
from datetime import UTC, datetime
|
|
2
|
+
from unittest.mock import Mock
|
|
3
|
+
from uuid import uuid4
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from pydantic import ValidationError
|
|
7
|
+
from requests import Timeout
|
|
8
|
+
|
|
9
|
+
from pybinbot import BinbotApi, BotModel, Status
|
|
10
|
+
from pybinbot.apis.binbot.exceptions import BinbotErrors
|
|
11
|
+
from pybinbot.models.signals import SignalListRecord
|
|
12
|
+
from kucoin_universal_sdk.generate.futures.positions.model_get_position_details_resp import (
|
|
13
|
+
GetPositionDetailsResp,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@pytest.fixture
|
|
18
|
+
def api(monkeypatch):
|
|
19
|
+
monkeypatch.setattr(BinbotApi, "_login_service_account", Mock())
|
|
20
|
+
client = BinbotApi(
|
|
21
|
+
"https://production.example", "service@example.test", "test-password"
|
|
22
|
+
)
|
|
23
|
+
monkeypatch.setattr(client, "request", Mock())
|
|
24
|
+
return client
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_get_bots_returns_typed_deduplicated_bots_from_every_page(api):
|
|
28
|
+
first = BotModel(id=uuid4(), pair="XBTUSDTM", status=Status.active)
|
|
29
|
+
second = BotModel(id=uuid4(), pair="ETHUSDTM", status=Status.active)
|
|
30
|
+
third = BotModel(id=uuid4(), pair="SOLUSDTM", status=Status.active)
|
|
31
|
+
api.request.side_effect = [
|
|
32
|
+
{"message": "Bots found", "data": [bot.model_dump(mode="json") for bot in page]}
|
|
33
|
+
for page in ([first, second], [second, third], [])
|
|
34
|
+
]
|
|
35
|
+
result = api.get_bots(
|
|
36
|
+
status=Status.active,
|
|
37
|
+
bot_name="terminal",
|
|
38
|
+
start_date=100,
|
|
39
|
+
end_date=200,
|
|
40
|
+
page_size=2,
|
|
41
|
+
)
|
|
42
|
+
assert result == [first, second, third]
|
|
43
|
+
assert [call.kwargs["params"]["offset"] for call in api.request.call_args_list] == [
|
|
44
|
+
0,
|
|
45
|
+
2,
|
|
46
|
+
4,
|
|
47
|
+
]
|
|
48
|
+
for call in api.request.call_args_list:
|
|
49
|
+
assert call.kwargs["url"] == "https://production.example/bot"
|
|
50
|
+
assert call.kwargs["timeout"] == (5, 30)
|
|
51
|
+
assert call.kwargs["params"] == {
|
|
52
|
+
"include_closed": False,
|
|
53
|
+
"status": "active",
|
|
54
|
+
"bot_name": "terminal",
|
|
55
|
+
"start_date": 100,
|
|
56
|
+
"end_date": 200,
|
|
57
|
+
"limit": 2,
|
|
58
|
+
"offset": call.kwargs["params"]["offset"],
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_get_bots_can_include_closed_bots_without_a_status_filter(api):
|
|
63
|
+
api.request.return_value = {"message": "Bots found", "data": []}
|
|
64
|
+
assert api.get_bots(include_closed=True) == []
|
|
65
|
+
assert api.request.call_args.kwargs["params"] == {
|
|
66
|
+
"include_closed": True,
|
|
67
|
+
"limit": 200,
|
|
68
|
+
"offset": 0,
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@pytest.mark.parametrize("size", [0, -1])
|
|
73
|
+
def test_get_bots_rejects_invalid_page_sizes_before_requesting(api, size):
|
|
74
|
+
with pytest.raises(ValueError, match="page_size"):
|
|
75
|
+
api.get_bots(page_size=size)
|
|
76
|
+
api.request.assert_not_called()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@pytest.mark.parametrize("quantity", [-17, 0, 12])
|
|
80
|
+
def test_get_futures_position_returns_typed_signed_or_flat_positions(api, quantity):
|
|
81
|
+
api.request.return_value = {
|
|
82
|
+
"message": "Position found",
|
|
83
|
+
"data": {"symbol": "FOLKSUSDTM", "current_qty": quantity},
|
|
84
|
+
}
|
|
85
|
+
result = api.get_futures_position("folksusdtm")
|
|
86
|
+
assert isinstance(result, GetPositionDetailsResp)
|
|
87
|
+
assert result.symbol == "FOLKSUSDTM"
|
|
88
|
+
assert result.current_qty == quantity
|
|
89
|
+
api.request.assert_called_once_with(
|
|
90
|
+
url="https://production.example/order/kucoin/futures/position/FOLKSUSDTM",
|
|
91
|
+
timeout=(5, 30),
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def test_get_signals_sends_typed_filters_and_returns_indicator_payloads(api):
|
|
96
|
+
since = datetime(2026, 12, 2, 12, tzinfo=UTC)
|
|
97
|
+
until = datetime(2026, 12, 2, 13, tzinfo=UTC)
|
|
98
|
+
record = {
|
|
99
|
+
"id": 42,
|
|
100
|
+
"algorithm_name": "skyfall",
|
|
101
|
+
"symbol": "FOLKSUSDTM",
|
|
102
|
+
"generated_at": since.isoformat(),
|
|
103
|
+
"direction": "short",
|
|
104
|
+
"indicators": {"derivatives_positioning": {"timestamp": since.timestamp()}},
|
|
105
|
+
}
|
|
106
|
+
api.request.return_value = {"message": "Signals found", "data": [record]}
|
|
107
|
+
result = api.get_signals(
|
|
108
|
+
symbol="folksusdtm",
|
|
109
|
+
algorithm_name="skyfall",
|
|
110
|
+
current_regime="DOWN",
|
|
111
|
+
autotrade=False,
|
|
112
|
+
since=since,
|
|
113
|
+
until=until,
|
|
114
|
+
limit=20,
|
|
115
|
+
offset=5,
|
|
116
|
+
)
|
|
117
|
+
assert len(result) == 1
|
|
118
|
+
assert isinstance(result[0], SignalListRecord)
|
|
119
|
+
assert result[0].indicators == record["indicators"]
|
|
120
|
+
assert result[0].generated_at == since
|
|
121
|
+
api.request.assert_called_once_with(
|
|
122
|
+
url="https://production.example/signals",
|
|
123
|
+
timeout=(5, 30),
|
|
124
|
+
params={
|
|
125
|
+
"symbol": "FOLKSUSDTM",
|
|
126
|
+
"algorithm_name": "skyfall",
|
|
127
|
+
"current_regime": "DOWN",
|
|
128
|
+
"autotrade": False,
|
|
129
|
+
"since": since.isoformat(),
|
|
130
|
+
"until": until.isoformat(),
|
|
131
|
+
"limit": 20,
|
|
132
|
+
"offset": 5,
|
|
133
|
+
"include_payload": True,
|
|
134
|
+
},
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def test_get_signals_accepts_summary_records_without_optional_payloads(api):
|
|
139
|
+
api.request.return_value = {
|
|
140
|
+
"message": "Signals found",
|
|
141
|
+
"data": [
|
|
142
|
+
{
|
|
143
|
+
"id": 1,
|
|
144
|
+
"algorithm_name": "skyfall",
|
|
145
|
+
"symbol": "XBTUSDTM",
|
|
146
|
+
"generated_at": "2026-12-02T12:00:00Z",
|
|
147
|
+
"direction": "short",
|
|
148
|
+
}
|
|
149
|
+
],
|
|
150
|
+
}
|
|
151
|
+
result = api.get_signals(include_payload=False)
|
|
152
|
+
assert result[0].indicators is None
|
|
153
|
+
assert api.request.call_args.kwargs["params"] == {
|
|
154
|
+
"limit": 100,
|
|
155
|
+
"offset": 0,
|
|
156
|
+
"include_payload": False,
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@pytest.mark.parametrize("kwargs", [{"limit": 0}, {"limit": 1001}, {"offset": -1}])
|
|
161
|
+
def test_get_signals_enforces_the_api_pagination_bounds(api, kwargs):
|
|
162
|
+
with pytest.raises(ValueError, match="Signals require"):
|
|
163
|
+
api.get_signals(**kwargs)
|
|
164
|
+
api.request.assert_not_called()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@pytest.mark.parametrize(
|
|
168
|
+
"method,args",
|
|
169
|
+
[("get_bots", ()), ("get_signals", ()), ("get_futures_position", ("XBTUSDTM",))],
|
|
170
|
+
)
|
|
171
|
+
def test_typed_reads_reject_error_responses_instead_of_returning_empty_data(
|
|
172
|
+
api, method, args
|
|
173
|
+
):
|
|
174
|
+
api.request.return_value = {"message": "Read rejected", "error": 1}
|
|
175
|
+
with pytest.raises(BinbotErrors):
|
|
176
|
+
getattr(api, method)(*args)
|
|
177
|
+
api.request.assert_called_once()
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@pytest.mark.parametrize(
|
|
181
|
+
"method,args",
|
|
182
|
+
[("get_bots", ()), ("get_signals", ()), ("get_futures_position", ("XBTUSDTM",))],
|
|
183
|
+
)
|
|
184
|
+
def test_typed_read_timeouts_propagate_without_retries(api, method, args):
|
|
185
|
+
api.request.side_effect = Timeout("Unavailable")
|
|
186
|
+
with pytest.raises(Timeout):
|
|
187
|
+
getattr(api, method)(*args)
|
|
188
|
+
api.request.assert_called_once()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def test_invalid_signal_rows_cannot_be_returned_as_typed_signals(api):
|
|
192
|
+
api.request.return_value = {"message": "Signals found", "data": [{"id": 1}]}
|
|
193
|
+
with pytest.raises(ValidationError):
|
|
194
|
+
api.get_signals()
|
|
@@ -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
|
|
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 <= 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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|