Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 67 additions & 16 deletions plugins/platforms/discord/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -6310,6 +6310,27 @@ def _standalone_sanitize_error(text) -> str:
)


# Maximum number of attempts for 429 retries in the standalone send path.
_STANDALONE_MAX_RETRIES = 3


def _standalone_parse_retry_after(body_text: str) -> Optional[float]:
"""Extract ``retry_after`` from a Discord 429 JSON response body.

Returns the delay in seconds (floored at 0.5, capped at 10), or ``None``
if the body doesn't contain a parseable ``retry_after`` field.
"""
try:
import json as _json
data = _json.loads(body_text)
raw = data.get("retry_after")
if raw is not None:
return max(0.5, min(10.0, float(raw)))
except Exception:
pass
return None


async def _standalone_send(
pconfig,
chat_id: str,
Expand Down Expand Up @@ -6470,12 +6491,26 @@ async def _standalone_send(

async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30), **_sess_kw) as session:
# Send text message (skip if empty and media is present)
# Retries on 429 rate-limit using Discord's retry_after field.
if message.strip() or not media_files:
async with session.post(url, headers=json_headers, json={"content": message}, **_req_kw) as resp:
if resp.status not in {200, 201}:
body = await resp.text()
return {"error": f"Discord API error ({resp.status}): {body}"}
last_data = await resp.json()
for _attempt in range(_STANDALONE_MAX_RETRIES):
async with session.post(url, headers=json_headers, json={"content": message}, **_req_kw) as resp:
if resp.status == 429:
body = await resp.text()
delay = _standalone_parse_retry_after(body)
if delay is not None and _attempt < _STANDALONE_MAX_RETRIES - 1:
logger.warning(
"Discord standalone send rate-limited (attempt %d/%d), retrying in %.1fs",
_attempt + 1, _STANDALONE_MAX_RETRIES, delay,
)
await asyncio.sleep(delay)
continue
return {"error": f"Discord API error (429): {body}"}
if resp.status not in {200, 201}:
body = await resp.text()
return {"error": f"Discord API error ({resp.status}): {body}"}
last_data = await resp.json()
break

# Send each media file as a separate multipart upload
for media_path, _is_voice in media_files:
Expand All @@ -6485,18 +6520,34 @@ async def _standalone_send(
warnings.append(warning)
continue
try:
form = aiohttp.FormData()
filename = os.path.basename(media_path)
with open(media_path, "rb") as f:
form.add_field("files[0]", f, filename=filename)
async with session.post(url, headers=auth_headers, data=form, **_req_kw) as resp:
if resp.status not in {200, 201}:
body = await resp.text()
warning = _standalone_sanitize_error(f"Failed to send media {media_path}: Discord API error ({resp.status}): {body}")
logger.error(warning)
warnings.append(warning)
continue
last_data = await resp.json()
for _m_attempt in range(_STANDALONE_MAX_RETRIES):
form = aiohttp.FormData()
with open(media_path, "rb") as f:
form.add_field("files[0]", f, filename=filename)
async with session.post(url, headers=auth_headers, data=form, **_req_kw) as resp:
if resp.status == 429:
body = await resp.text()
delay = _standalone_parse_retry_after(body)
if delay is not None and _m_attempt < _STANDALONE_MAX_RETRIES - 1:
logger.warning(
"Discord media upload rate-limited (attempt %d/%d), retrying in %.1fs",
_m_attempt + 1, _STANDALONE_MAX_RETRIES, delay,
)
await asyncio.sleep(delay)
continue
warning = _standalone_sanitize_error(f"Failed to send media {media_path}: Discord API error (429): {body}")
logger.error(warning)
warnings.append(warning)
break
if resp.status not in {200, 201}:
body = await resp.text()
warning = _standalone_sanitize_error(f"Failed to send media {media_path}: Discord API error ({resp.status}): {body}")
logger.error(warning)
warnings.append(warning)
break
last_data = await resp.json()
break
except Exception as e:
warning = _standalone_sanitize_error(f"Failed to send media {media_path}: {e}")
logger.error(warning)
Expand Down
110 changes: 110 additions & 0 deletions tests/tools/test_send_message_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -1414,6 +1414,116 @@ def test_error_status_returns_error_dict(self):
assert "403" in result["error"]


class TestStandaloneParseRetryAfter:
"""_standalone_parse_retry_after extracts retry_after from 429 bodies."""

def test_parses_retry_after_float(self):
from plugins.platforms.discord.adapter import _standalone_parse_retry_after
body = '{"message": "You are being rate limited.", "retry_after": 0.3}'
assert _standalone_parse_retry_after(body) == 0.5 # floored at 0.5

def test_parses_retry_after_large_value(self):
from plugins.platforms.discord.adapter import _standalone_parse_retry_after
body = '{"retry_after": 15.0}'
assert _standalone_parse_retry_after(body) == 10.0 # capped at 10

def test_returns_none_on_missing_field(self):
from plugins.platforms.discord.adapter import _standalone_parse_retry_after
body = '{"message": "You are being rate limited."}'
assert _standalone_parse_retry_after(body) is None

def test_returns_none_on_invalid_json(self):
from plugins.platforms.discord.adapter import _standalone_parse_retry_after
assert _standalone_parse_retry_after("not json") is None

def test_returns_none_on_non_numeric(self):
from plugins.platforms.discord.adapter import _standalone_parse_retry_after
body = '{"retry_after": "abc"}'
assert _standalone_parse_retry_after(body) is None


class TestSendDiscord429Retry:
"""_standalone_send retries on 429 rate-limit responses."""

@staticmethod
def _build_mock_sequence(responses):
"""Build a mock aiohttp session that returns different responses per call.

``responses`` is a list of (status, json_data, text_body) tuples.
"""
mock_session = MagicMock()
mock_session.__aenter__ = AsyncMock(return_value=mock_session)
mock_session.__aexit__ = AsyncMock(return_value=None)

call_count = 0

def _make_resp(status, data, text_body):
resp = MagicMock()
resp.status = status
resp.json = AsyncMock(return_value=data)
resp.text = AsyncMock(return_value=text_body)
resp.__aenter__ = AsyncMock(return_value=resp)
resp.__aexit__ = AsyncMock(return_value=None)
return resp

def _post(*args, **kwargs):
nonlocal call_count
idx = min(call_count, len(responses) - 1)
call_count += 1
s, d, t = responses[idx]
return _make_resp(s, d, t)

mock_session.post = MagicMock(side_effect=_post)
return mock_session

def test_429_then_success_retries_and_succeeds(self):
"""A 429 with retry_after followed by 200 should succeed."""
mock_session = self._build_mock_sequence([
(429, {"retry_after": 0.5}, '{"retry_after": 0.5}'),
(200, {"id": "msg123"}, '{}'),
])
with patch("aiohttp.ClientSession", return_value=mock_session):
result = asyncio.run(_send_discord("tok", "111", "hello"))
assert result["success"] is True
assert result["message_id"] == "msg123"
assert mock_session.post.call_count == 2

def test_429_exhausted_retries_returns_error(self):
"""Three consecutive 429s should return an error."""
mock_session = self._build_mock_sequence([
(429, {"retry_after": 0.5}, '{"retry_after": 0.5}'),
(429, {"retry_after": 0.5}, '{"retry_after": 0.5}'),
(429, {"retry_after": 0.5}, '{"retry_after": 0.5}'),
])
with patch("aiohttp.ClientSession", return_value=mock_session):
result = asyncio.run(_send_discord("tok", "111", "hello"))
assert "error" in result
assert "429" in result["error"]
assert mock_session.post.call_count == 3

def test_429_no_retry_after_returns_error_immediately(self):
"""429 without parseable retry_after should return error on first attempt."""
mock_session = self._build_mock_sequence([
(429, {"message": "rate limited"}, '{"message": "rate limited"}'),
])
with patch("aiohttp.ClientSession", return_value=mock_session):
result = asyncio.run(_send_discord("tok", "111", "hello"))
assert "error" in result
assert "429" in result["error"]
assert mock_session.post.call_count == 1

def test_non_429_error_returns_immediately(self):
"""Non-429 errors (e.g. 403) should not retry."""
mock_session = self._build_mock_sequence([
(403, {"message": "Forbidden"}, '{"message": "Forbidden"}'),
])
with patch("aiohttp.ClientSession", return_value=mock_session):
result = asyncio.run(_send_discord("tok", "111", "hello"))
assert "error" in result
assert "403" in result["error"]
assert mock_session.post.call_count == 1


class TestSendToPlatformDiscordThread:
"""_send_to_platform passes thread_id through to _send_discord."""

Expand Down
Loading