Revert "调整插件执行模式并修复全球新闻后台线程"

This reverts commit adbf4471cf.
This commit is contained in:
Liu
2026-05-01 12:45:33 +08:00
parent bb65c465e7
commit 08db0ea07e
10 changed files with 19 additions and 183 deletions

View File

@@ -1,6 +1,6 @@
import asyncio
import threading
import time
import time # 添加这一行
from typing import Dict, Any, List, Optional, Tuple
from base.plugin_common.message_plugin_interface import MessagePluginInterface
@@ -146,43 +146,31 @@ class GlobalNewsPlugin(MessagePluginInterface):
self._news_tasks[task_id] = thread
self.LOG.info(f"启动新闻获取任务: {task_id}")
def _fetch_news_thread(self, task_id: str, sender: str, roomid: str):
"""在单独线程里执行新闻抓取主流程。
这里必须保持为同步函数:
1. `threading.Thread(target=...)` 只能直接执行普通可调用对象;
2. 之前把协程函数直接塞给 `target`,线程里只会得到一个未执行的 coroutine任务实际上不会跑
3. 现在在线程内部显式创建事件循环,再把异步抓取和发消息协程跑完,才能真正脱离主链路执行。
"""
loop = asyncio.new_event_loop()
async def _fetch_news_thread(self, task_id: str, sender: str, roomid: str):
"""在单独线程中运行异步新闻获取任务"""
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
news_result = loop.run_until_complete(self._fetch_news_async())
loop.close()
# 处理结果
receiver = roomid if roomid else sender
if news_result:
# 在线程自有事件循环里把图片和完成提示真正发出去,
# 避免这里只拿到 coroutine 对象却没有执行。
loop.run_until_complete(self.bot.send_image_message(receiver, news_result))
loop.run_until_complete(self.bot.send_text_message(receiver, "🌍全球新闻获取完成!", sender))
# 发送新闻图片
receiver = roomid if roomid else sender
await self.bot.send_image_message(receiver, news_result)
await self.bot.send_text_message("🌍全球新闻获取完成!", receiver, sender)
else:
loop.run_until_complete(self.bot.send_text_message(receiver, "❌获取新闻失败,请稍后再试", sender))
await self.bot.send_text_message(
(roomid if roomid else sender), "❌获取新闻失败,请稍后再试", sender)
except Exception as e:
self.LOG.error(f"新闻获取任务出错: {e}")
try:
receiver = roomid if roomid else sender
loop.run_until_complete(self.bot.send_text_message(receiver, f"❌获取新闻出错: {str(e)}", sender))
except Exception as send_error:
self.LOG.error(f"新闻获取失败后的通知发送异常: {send_error}")
await self.bot.send_text_message((roomid if roomid else sender), f"❌获取新闻出错: {str(e)}",
sender)
finally:
# 清理任务
if task_id in self._news_tasks:
del self._news_tasks[task_id]
try:
loop.close()
except Exception:
pass
async def _fetch_news_async(self) -> str:
"""异步获取所有新闻源的新闻"""