Skip to content

Commit a0864ec

Browse files
authored
Prevent Telegram market symbol auto-links
1 parent 2e3d813 commit a0864ec

2 files changed

Lines changed: 39 additions & 1 deletion

File tree

notifications/telegram.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
from __future__ import annotations
44

5+
import re
6+
57
try:
68
from quant_platform_kit.common.notification_localization import (
79
merge_strategy_plugin_i18n as _merge_strategy_plugin_i18n,
@@ -10,6 +12,18 @@
1012
_merge_strategy_plugin_i18n = None
1113

1214

15+
_TELEGRAM_MARKET_SYMBOL_LINK_RE = re.compile(r"(?<![A-Za-z0-9_])([A-Z0-9]{1,12})\.([A-Z]{2,4})(?![A-Za-z0-9_])")
16+
_TELEGRAM_MARKET_SYMBOL_LINK_JOINER = "\u2060"
17+
18+
19+
def _break_telegram_market_symbol_auto_links(value) -> str:
20+
text = str(value or "")
21+
return _TELEGRAM_MARKET_SYMBOL_LINK_RE.sub(
22+
lambda match: f"{match.group(1)}.{_TELEGRAM_MARKET_SYMBOL_LINK_JOINER}{match.group(2)}",
23+
text,
24+
)
25+
26+
1327
I18N = {
1428
"zh": {
1529
"rebalance_title": "🔔 【调仓指令】",
@@ -451,7 +465,7 @@ def send_telegram_message(
451465
printer(f"TG:\n{message}", flush=True)
452466
response = requests_module.post(
453467
url,
454-
json={"chat_id": chat_id, "text": message},
468+
json={"chat_id": chat_id, "text": _break_telegram_market_symbol_auto_links(message)},
455469
timeout=10,
456470
)
457471
if not 200 <= response.status_code < 300:

tests/test_notifications.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,30 @@ def post(*args, **kwargs):
262262
assert "Telegram send failed with status 401: unauthorized" in captured.out
263263

264264

265+
def test_send_telegram_message_breaks_market_symbol_auto_links():
266+
calls = []
267+
268+
class FakeResponse:
269+
status_code = 200
270+
text = ""
271+
272+
class FakeRequests:
273+
@staticmethod
274+
def post(*args, **kwargs):
275+
calls.append((args, kwargs))
276+
return FakeResponse()
277+
278+
send_telegram_message(
279+
"SOXL.US 预计;00700.HK 持仓;https://example.com 保持原样",
280+
token="token",
281+
chat_id="chat-id",
282+
requests_module=FakeRequests,
283+
)
284+
285+
payload = calls[0][1]["json"]
286+
assert payload["text"] == "SOXL.\u2060US 预计;00700.\u2060HK 持仓;https://example.com 保持原样"
287+
288+
265289
def test_send_telegram_message_redacts_exception_detail(capsys):
266290
class FakeRequests:
267291
@staticmethod

0 commit comments

Comments
 (0)