From 3e419fba22b94b941fe1f496af2288232b122048 Mon Sep 17 00:00:00 2001 From: liuwei Date: Wed, 4 Jun 2025 11:03:56 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=97=A0=E7=94=A8=E7=9A=84AI?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base/func_english_news.py | 4 +- base/func_news.py | 1 - plugins/global_news/config.toml | 7 +++- plugins/global_news/main.py | 67 ++++++++++++++++++++++++++++-- utils/ai/dify_news_analyze.py | 73 --------------------------------- 5 files changed, 71 insertions(+), 81 deletions(-) delete mode 100644 utils/ai/dify_news_analyze.py diff --git a/base/func_english_news.py b/base/func_english_news.py index 9331d20..6710551 100644 --- a/base/func_english_news.py +++ b/base/func_english_news.py @@ -6,7 +6,7 @@ Created Date: 2024-01-21 Last Modified: 2024-03-24 Modified by: MrCrawL """ -from utils.ai.dify_news_analyze import dify_news_title_analyze +from plugins.global_news.dify_news_analyze import dify_news_title_analyze from utils.markdown_to_image import convert_md_str_to_image '''Existing problem: text with hyperlink won't be saved''' @@ -15,8 +15,6 @@ import requests from time import localtime, sleep from lxml import etree from loguru import logger -from datetime import datetime - # 请求配置 HEADERS = { diff --git a/base/func_news.py b/base/func_news.py index 7ae4268..f94f338 100644 --- a/base/func_news.py +++ b/base/func_news.py @@ -11,7 +11,6 @@ import requests from lxml import etree from base import func_english_news -from utils.ai.dify_news_analyze import dify_news_title_analyze class News(object): diff --git a/plugins/global_news/config.toml b/plugins/global_news/config.toml index d56b34c..2b4e67c 100644 --- a/plugins/global_news/config.toml +++ b/plugins/global_news/config.toml @@ -1,6 +1,11 @@ +[GlobalNews] enable = true command = ["全球新闻", "国际新闻", "环球新闻", "政经新闻", "政治经济新闻"] command-format = """ 🌍全球新闻指令: 全球新闻 - 获取最新的全球政治经济新闻 -""" \ No newline at end of file +""" + + +authorization = "Bearer app-rhhKkbvHd2IAQoGX7xTzXZJj" # 请替换为真实的Authorization token +url = 'http://192.168.2.240/v1/chat-messages' \ No newline at end of file diff --git a/plugins/global_news/main.py b/plugins/global_news/main.py index 650f77f..d3381cb 100644 --- a/plugins/global_news/main.py +++ b/plugins/global_news/main.py @@ -1,6 +1,8 @@ import asyncio +import json import threading import time # 添加这一行 +import aiohttp from typing import Dict, Any, List, Optional, Tuple from base.plugin_common.message_plugin_interface import MessagePluginInterface @@ -8,7 +10,6 @@ from base.plugin_common.plugin_interface import PluginStatus from utils.decorator.plugin_decorators import plugin_stats_decorator from utils.robot_cmd.robot_command import Feature, PermissionStatus, GroupBotManager from utils.decorator.points_decorator import plugin_points_cost -from utils.ai.dify_news_analyze import dify_news_title_analyze from utils.markdown_to_image import convert_md_str_to_image from wechat_ipad import WechatAPIClient @@ -61,7 +62,8 @@ class GlobalNewsPlugin(MessagePluginInterface): self.command_format = self._config.get("GlobalNews", {}).get("command-format", "全球新闻 - 获取最新的全球政治经济新闻") self.enable = self._config.get("GlobalNews", {}).get("enable", True) - + self._key = self._config.get("GlobalNews", {}).get("authorization", "") + self._url = self._config.get("GlobalNews", {}).get("url", "") self.LOG.info(f"[{self.name}] 插件初始化完成,指令:{self._commands}") return True @@ -171,7 +173,7 @@ class GlobalNewsPlugin(MessagePluginInterface): # 使用AI分析新闻 markdown_news = await self._run_in_executor( - dify_news_title_analyze, news_titles + self.dify_news_title_analyze, news_titles ) # 转换为图片 @@ -188,3 +190,62 @@ class GlobalNewsPlugin(MessagePluginInterface): """在线程池中运行同步函数""" loop = asyncio.get_event_loop() return await loop.run_in_executor(None, func, *args) + + async def dify_news_title_analyze(self, content: str) -> str: + """异步分析新闻标题 + Args: + content: 新闻标题内容 + Returns: + str: 分析后的内容 + """ + # 设置Authorization和URL + data = { + "response_mode": "blocking", + "conversation_id": "", + "inputs": {}, + "query": content, + "user": "a-bot-global_news" + } + + # 设置请求头 + headers = { + "Content-Type": "application/json; charset=utf-8", + "Authorization": self._key + } + + try: + async with aiohttp.ClientSession() as session: + async with session.post(self._url, headers=headers, json=data) as response: + if response.status != 200: + self.LOG.error(f"新闻分析请求失败: {response.status}") + return None + + response_data = await response.json() + self.LOG.debug(f"新闻分析响应: {response_data}") + return self.extract_content(response_data) + + except Exception as e: + self.LOG.error(f"新闻分析请求出错: {e}") + return None + + def extract_content(self, data): + """解析API响应内容 + Args: + data: API返回的响应数据,可以是字典或字符串 + Returns: + str: 提取的answer内容 + """ + try: + # 如果是字符串,尝试解析为字典 + if isinstance(data, str): + data = json.loads(data) + # 如果是字典,直接获取answer + if isinstance(data, dict): + answer = data.get('answer', '') + if answer: + return answer + + return None + except Exception as e: + self.LOG.error(f"解析响应失败: {str(e)}") + return None diff --git a/utils/ai/dify_news_analyze.py b/utils/ai/dify_news_analyze.py deleted file mode 100644 index 07122e3..0000000 --- a/utils/ai/dify_news_analyze.py +++ /dev/null @@ -1,73 +0,0 @@ -# -# curl -X POST 'http://192.168.2.240/v1/chat-messages' \ -# --header 'Authorization: Bearer {api_key}' \ -# --header 'Content-Type: application/json' \ -# --data-raw '{ -# "inputs": {}, -# "query": "What are the specs of the iPhone 13 Pro Max?", -# "response_mode": "streaming", -# "conversation_id": "", -# "user": "abc-123", -# "files": [ -# { -# "type": "image", -# "transfer_method": "remote_url", -# "url": "https://cloud.dify.ai/logo/logo-site.png" -# } -# ] -# }' -import json - -import requests - - -def dify_news_title_analyze(content): - # 设置Authorization和URL - authorization = "Bearer app-rhhKkbvHd2IAQoGX7xTzXZJj" # 请替换为真实的Authorization token - url = 'http://192.168.2.240/v1/chat-messages' - - data = { - "response_mode": "blocking", - "conversation_id": "", - "inputs": {}, - "query": content, - "user": "a-bot" - } - - # 设置请求头 - headers = { - "Content-Type": "application/json; charset=utf-8", - "Authorization": authorization - } - - # 发送POST请求 - response = requests.post(url, headers=headers, data=json.dumps(data), ) - response.encoding = 'utf-8' - - # 输出响应内容 - print(response.status_code) - print(response.json()) - return extract_content(response.json()) - - -def extract_content(data): - """解析API响应内容 - Args: - data: API返回的响应数据,可以是字典或字符串 - Returns: - str: 提取的answer内容 - """ - try: - # 如果是字符串,尝试解析为字典 - if isinstance(data, str): - data = json.dumps(data) - # 如果是字典,直接获取answer - if isinstance(data, dict): - answer = data.get('answer', '') - if answer: - return answer - - return None - except Exception as e: - print(f"解析响应失败: {str(e)}") - return None