fix: refresh stale Telegram DM topic threads

(cherry picked from commit 26b87057ad)
This commit is contained in:
stepanov1975 2026-05-16 20:01:40 +00:00 committed by Teknium
parent dcd504cea4
commit c394e7919d
5 changed files with 202 additions and 14 deletions

View file

@ -224,7 +224,33 @@ async def test_ensure_dm_topic_creates_on_demand_and_persists():
assert adapter._dm_topics_config == [
{"chat_id": 111, "topics": [{"name": "On Demand", "thread_id": 444}]}
]
adapter._persist_dm_topic_thread_id.assert_called_once_with(111, "On Demand", 444)
adapter._persist_dm_topic_thread_id.assert_called_once_with(
111, "On Demand", 444, replace_existing=False
)
@pytest.mark.asyncio
async def test_ensure_dm_topic_force_create_replaces_persisted_thread_id():
"""Refreshing a stale named topic should replace the cached persisted thread_id."""
adapter = _make_adapter()
bot = AsyncMock()
bot.create_forum_topic.return_value = SimpleNamespace(message_thread_id=777)
adapter._bot = bot
adapter._persist_dm_topic_thread_id = MagicMock()
adapter._dm_topics = {"111:General": 500}
adapter._dm_topics_config = [
{"chat_id": 111, "topics": [{"name": "General", "thread_id": 500}]}
]
result = await adapter.ensure_dm_topic("111", "General", force_create=True)
assert result == "777"
bot.create_forum_topic.assert_called_once_with(chat_id=111, name="General")
assert adapter._dm_topics["111:General"] == 777
assert adapter._dm_topics_config[0]["topics"][0]["thread_id"] == 777
adapter._persist_dm_topic_thread_id.assert_called_once_with(
111, "General", 777, replace_existing=True
)
# ── _persist_dm_topic_thread_id ──
@ -309,6 +335,45 @@ def test_persist_dm_topic_thread_id_skips_if_already_set(tmp_path):
assert topics[0]["thread_id"] == 500 # unchanged
def test_persist_dm_topic_thread_id_replaces_existing_when_requested(tmp_path):
"""Forced refresh should overwrite a stale persisted thread_id."""
import yaml
config_data = {
"platforms": {
"telegram": {
"extra": {
"dm_topics": [
{
"chat_id": 111,
"topics": [
{"name": "General", "icon_color": 123, "thread_id": 500},
],
}
]
}
}
}
}
config_file = tmp_path / ".hermes" / "config.yaml"
config_file.parent.mkdir(parents=True)
with open(config_file, "w") as f:
yaml.dump(config_data, f)
adapter = _make_adapter()
with patch.object(Path, "home", return_value=tmp_path), \
patch.dict(os.environ, {"HERMES_HOME": str(tmp_path / ".hermes")}):
adapter._persist_dm_topic_thread_id(111, "General", 999, replace_existing=True)
with open(config_file) as f:
result = yaml.safe_load(f)
topics = result["platforms"]["telegram"]["extra"]["dm_topics"][0]["topics"]
assert topics[0]["thread_id"] == 999
# ── _get_dm_topic_info ──