mirror of
https://github.com/langbot-app/LangBot.git
synced 2025-11-25 19:37:36 +08:00
fix: format the code
This commit is contained in:
@@ -104,7 +104,7 @@ class QQOfficialClient:
|
||||
return {'code': 0, 'message': 'success'}
|
||||
|
||||
except Exception as e:
|
||||
await self.logger.error(f"Error in handle_callback_request: {traceback.format_exc()}")
|
||||
await self.logger.error(f'Error in handle_callback_request: {traceback.format_exc()}')
|
||||
return {'error': str(e)}, 400
|
||||
|
||||
async def run_task(self, host: str, port: int, *args, **kwargs):
|
||||
@@ -168,7 +168,6 @@ class QQOfficialClient:
|
||||
if not await self.check_access_token():
|
||||
await self.get_access_token()
|
||||
|
||||
|
||||
url = self.base_url + '/v2/users/' + user_openid + '/messages'
|
||||
async with httpx.AsyncClient() as client:
|
||||
headers = {
|
||||
@@ -193,7 +192,6 @@ class QQOfficialClient:
|
||||
if not await self.check_access_token():
|
||||
await self.get_access_token()
|
||||
|
||||
|
||||
url = self.base_url + '/v2/groups/' + group_openid + '/messages'
|
||||
async with httpx.AsyncClient() as client:
|
||||
headers = {
|
||||
@@ -209,7 +207,7 @@ class QQOfficialClient:
|
||||
if response.status_code == 200:
|
||||
return
|
||||
else:
|
||||
await self.logger.error(f"发送群聊消息失败:{response.json()}")
|
||||
await self.logger.error(f'发送群聊消息失败:{response.json()}')
|
||||
raise Exception(response.read().decode())
|
||||
|
||||
async def send_channle_group_text_msg(self, channel_id: str, content: str, msg_id: str):
|
||||
@@ -217,7 +215,6 @@ class QQOfficialClient:
|
||||
if not await self.check_access_token():
|
||||
await self.get_access_token()
|
||||
|
||||
|
||||
url = self.base_url + '/channels/' + channel_id + '/messages'
|
||||
async with httpx.AsyncClient() as client:
|
||||
headers = {
|
||||
@@ -241,7 +238,6 @@ class QQOfficialClient:
|
||||
if not await self.check_access_token():
|
||||
await self.get_access_token()
|
||||
|
||||
|
||||
url = self.base_url + '/dms/' + guild_id + '/messages'
|
||||
async with httpx.AsyncClient() as client:
|
||||
headers = {
|
||||
|
||||
@@ -35,7 +35,6 @@ class SlackClient:
|
||||
if self.bot_user_id and bot_user_id == self.bot_user_id:
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
# 处理私信
|
||||
if data and data.get('event', {}).get('channel_type') in ['im']:
|
||||
event = SlackEvent.from_payload(data)
|
||||
@@ -52,7 +51,7 @@ class SlackClient:
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
except Exception as e:
|
||||
await self.logger.error(f"Error in handle_callback_request: {traceback.format_exc()}")
|
||||
await self.logger.error(f'Error in handle_callback_request: {traceback.format_exc()}')
|
||||
raise (e)
|
||||
|
||||
async def _handle_message(self, event: SlackEvent):
|
||||
@@ -82,7 +81,7 @@ class SlackClient:
|
||||
self.bot_user_id = response['message']['bot_id']
|
||||
return
|
||||
except Exception as e:
|
||||
await self.logger.error(f"Error in send_message: {e}")
|
||||
await self.logger.error(f'Error in send_message: {e}')
|
||||
raise e
|
||||
|
||||
async def send_message_to_one(self, text: str, user_id: str):
|
||||
@@ -93,7 +92,7 @@ class SlackClient:
|
||||
|
||||
return
|
||||
except Exception as e:
|
||||
await self.logger.error(f"Error in send_message: {traceback.format_exc()}")
|
||||
await self.logger.error(f'Error in send_message: {traceback.format_exc()}')
|
||||
raise e
|
||||
|
||||
async def run_task(self, host: str, port: int, *args, **kwargs):
|
||||
|
||||
@@ -12,12 +12,9 @@ class UserApi:
|
||||
|
||||
return get_json(base_url=url, token=self.token)
|
||||
|
||||
def get_qr_code(self, recover:bool=True, style:int=8):
|
||||
def get_qr_code(self, recover: bool = True, style: int = 8):
|
||||
"""获取自己的二维码"""
|
||||
param = {
|
||||
"Recover": recover,
|
||||
"Style": style
|
||||
}
|
||||
param = {'Recover': recover, 'Style': style}
|
||||
url = f'{self.base_url}/user/GetMyQRCode'
|
||||
return post_json(base_url=url, token=self.token, data=param)
|
||||
|
||||
@@ -26,12 +23,8 @@ class UserApi:
|
||||
url = f'{self.base_url}/equipment/GetSafetyInfo'
|
||||
return post_json(base_url=url, token=self.token)
|
||||
|
||||
|
||||
|
||||
async def update_head_img(self, head_img_base64):
|
||||
async def update_head_img(self, head_img_base64):
|
||||
"""修改头像"""
|
||||
param = {
|
||||
"Base64": head_img_base64
|
||||
}
|
||||
param = {'Base64': head_img_base64}
|
||||
url = f'{self.base_url}/user/UploadHeadImage'
|
||||
return await async_request(base_url=url, token_key=self.token, json=param)
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
from libs.wechatpad_api.api.login import LoginApi
|
||||
from libs.wechatpad_api.api.friend import FriendApi
|
||||
from libs.wechatpad_api.api.message import MessageApi
|
||||
@@ -7,9 +6,6 @@ from libs.wechatpad_api.api.downloadpai import DownloadApi
|
||||
from libs.wechatpad_api.api.chatroom import ChatRoomApi
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class WeChatPadClient:
|
||||
def __init__(self, base_url, token, logger=None):
|
||||
self._login_api = LoginApi(base_url, token)
|
||||
@@ -20,16 +16,16 @@ class WeChatPadClient:
|
||||
self._chatroom_api = ChatRoomApi(base_url, token)
|
||||
self.logger = logger
|
||||
|
||||
def get_token(self,admin_key, day: int):
|
||||
'''获取token'''
|
||||
def get_token(self, admin_key, day: int):
|
||||
"""获取token"""
|
||||
return self._login_api.get_token(admin_key, day)
|
||||
|
||||
def get_login_qr(self, Proxy:str=""):
|
||||
def get_login_qr(self, Proxy: str = ''):
|
||||
"""登录二维码"""
|
||||
return self._login_api.get_login_qr(Proxy=Proxy)
|
||||
|
||||
def awaken_login(self, Proxy:str=""):
|
||||
'''唤醒登录'''
|
||||
def awaken_login(self, Proxy: str = ''):
|
||||
"""唤醒登录"""
|
||||
return self._login_api.wake_up_login(Proxy=Proxy)
|
||||
|
||||
def log_out(self):
|
||||
@@ -40,59 +36,57 @@ class WeChatPadClient:
|
||||
"""获取登录状态"""
|
||||
return self._login_api.get_login_status()
|
||||
|
||||
def send_text_message(self, to_wxid, message, ats: list=[]):
|
||||
def send_text_message(self, to_wxid, message, ats: list = []):
|
||||
"""发送文本消息"""
|
||||
return self._message_api.post_text(to_wxid, message, ats)
|
||||
return self._message_api.post_text(to_wxid, message, ats)
|
||||
|
||||
def send_image_message(self, to_wxid, img_url, ats: list=[]):
|
||||
def send_image_message(self, to_wxid, img_url, ats: list = []):
|
||||
"""发送图片消息"""
|
||||
return self._message_api.post_image(to_wxid, img_url, ats)
|
||||
return self._message_api.post_image(to_wxid, img_url, ats)
|
||||
|
||||
def send_voice_message(self, to_wxid, voice_data, voice_forma, voice_duration):
|
||||
"""发送音频消息"""
|
||||
return self._message_api.post_voice(to_wxid, voice_data, voice_forma, voice_duration)
|
||||
return self._message_api.post_voice(to_wxid, voice_data, voice_forma, voice_duration)
|
||||
|
||||
def send_app_message(self, to_wxid, app_message, type):
|
||||
"""发送app消息"""
|
||||
return self._message_api.post_app_msg(to_wxid, app_message, type)
|
||||
return self._message_api.post_app_msg(to_wxid, app_message, type)
|
||||
|
||||
def send_emoji_message(self, to_wxid, emoji_md5, emoji_size):
|
||||
"""发送emoji消息"""
|
||||
return self._message_api.post_emoji(to_wxid,emoji_md5,emoji_size)
|
||||
return self._message_api.post_emoji(to_wxid, emoji_md5, emoji_size)
|
||||
|
||||
def revoke_msg(self, to_wxid, msg_id, new_msg_id, create_time):
|
||||
"""撤回消息"""
|
||||
return self._message_api.revoke_msg(to_wxid, msg_id, new_msg_id, create_time)
|
||||
return self._message_api.revoke_msg(to_wxid, msg_id, new_msg_id, create_time)
|
||||
|
||||
def get_profile(self):
|
||||
"""获取用户信息"""
|
||||
return self._user_api.get_profile()
|
||||
|
||||
def get_qr_code(self, recover:bool=True, style:int=8):
|
||||
def get_qr_code(self, recover: bool = True, style: int = 8):
|
||||
"""获取用户二维码"""
|
||||
return self._user_api.get_qr_code(recover=recover, style=style)
|
||||
return self._user_api.get_qr_code(recover=recover, style=style)
|
||||
|
||||
def get_safety_info(self):
|
||||
"""获取设备信息"""
|
||||
return self._user_api.get_safety_info()
|
||||
return self._user_api.get_safety_info()
|
||||
|
||||
def update_head_img(self, head_img_base64):
|
||||
def update_head_img(self, head_img_base64):
|
||||
"""上传用户头像"""
|
||||
return self._user_api.update_head_img(head_img_base64)
|
||||
return self._user_api.update_head_img(head_img_base64)
|
||||
|
||||
def cdn_download(self, aeskey, file_type, file_url):
|
||||
"""cdn下载"""
|
||||
return self._download_api.send_download( aeskey, file_type, file_url)
|
||||
return self._download_api.send_download(aeskey, file_type, file_url)
|
||||
|
||||
def get_msg_voice(self,buf_id, length, msgid):
|
||||
def get_msg_voice(self, buf_id, length, msgid):
|
||||
"""下载语音"""
|
||||
return self._download_api.get_msg_voice(buf_id, length, msgid)
|
||||
|
||||
async def download_base64(self,url):
|
||||
async def download_base64(self, url):
|
||||
return await self._download_api.download_url_to_base64(download_url=url)
|
||||
|
||||
def get_chatroom_member_detail(self, chatroom_name):
|
||||
"""查看群成员详情"""
|
||||
return self._chatroom_api.get_chatroom_member_detail(chatroom_name)
|
||||
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import qrcode
|
||||
|
||||
|
||||
def print_green(text):
|
||||
print(f"\033[32m{text}\033[0m")
|
||||
print(f'\033[32m{text}\033[0m')
|
||||
|
||||
|
||||
def print_yellow(text):
|
||||
print(f"\033[33m{text}\033[0m")
|
||||
print(f'\033[33m{text}\033[0m')
|
||||
|
||||
|
||||
def print_red(text):
|
||||
print(f"\033[31m{text}\033[0m")
|
||||
print(f'\033[31m{text}\033[0m')
|
||||
|
||||
|
||||
def make_and_print_qr(url):
|
||||
"""生成并打印二维码
|
||||
@@ -22,10 +26,9 @@ def make_and_print_qr(url):
|
||||
1. 在终端打印二维码的ASCII图形
|
||||
2. 同时提供在线二维码生成链接作为备选
|
||||
"""
|
||||
print_green("请扫描下方二维码登录")
|
||||
print_green('请扫描下方二维码登录')
|
||||
qr = qrcode.QRCode()
|
||||
qr.add_data(url)
|
||||
qr.make()
|
||||
qr.print_ascii(invert=True)
|
||||
print_green(f"也可以访问下方链接获取二维码:\nhttps://api.qrserver.com/v1/create-qr-code/?data={url}")
|
||||
|
||||
print_green(f'也可以访问下方链接获取二维码:\nhttps://api.qrserver.com/v1/create-qr-code/?data={url}')
|
||||
|
||||
@@ -57,7 +57,7 @@ class WecomClient:
|
||||
if 'access_token' in data:
|
||||
return data['access_token']
|
||||
else:
|
||||
await self.logger.error(f"获取accesstoken失败:{response.json()}")
|
||||
await self.logger.error(f'获取accesstoken失败:{response.json()}')
|
||||
raise Exception(f'未获取access token: {data}')
|
||||
|
||||
async def get_users(self):
|
||||
@@ -129,7 +129,7 @@ class WecomClient:
|
||||
response = await client.post(url, json=params)
|
||||
data = response.json()
|
||||
except Exception as e:
|
||||
await self.logger.error(f"发送图片失败:{data}")
|
||||
await self.logger.error(f'发送图片失败:{data}')
|
||||
raise Exception('Failed to send image: ' + str(e))
|
||||
|
||||
# 企业微信错误码40014和42001,代表accesstoken问题
|
||||
@@ -164,7 +164,7 @@ class WecomClient:
|
||||
self.access_token = await self.get_access_token(self.secret)
|
||||
return await self.send_private_msg(user_id, agent_id, content)
|
||||
if data['errcode'] != 0:
|
||||
await self.logger.error(f"发送消息失败:{data}")
|
||||
await self.logger.error(f'发送消息失败:{data}')
|
||||
raise Exception('Failed to send message: ' + str(data))
|
||||
|
||||
async def handle_callback_request(self):
|
||||
@@ -181,7 +181,7 @@ class WecomClient:
|
||||
echostr = request.args.get('echostr')
|
||||
ret, reply_echo_str = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
|
||||
if ret != 0:
|
||||
await self.logger.error("验证失败")
|
||||
await self.logger.error('验证失败')
|
||||
raise Exception(f'验证失败,错误码: {ret}')
|
||||
return reply_echo_str
|
||||
|
||||
@@ -189,10 +189,9 @@ class WecomClient:
|
||||
encrypt_msg = await request.data
|
||||
ret, xml_msg = wxcpt.DecryptMsg(encrypt_msg, msg_signature, timestamp, nonce)
|
||||
if ret != 0:
|
||||
await self.logger.error("消息解密失败")
|
||||
await self.logger.error('消息解密失败')
|
||||
raise Exception(f'消息解密失败,错误码: {ret}')
|
||||
|
||||
|
||||
# 解析消息并处理
|
||||
message_data = await self.get_message(xml_msg)
|
||||
if message_data:
|
||||
@@ -202,7 +201,7 @@ class WecomClient:
|
||||
|
||||
return 'success'
|
||||
except Exception as e:
|
||||
await self.logger.error(f"Error in handle_callback_request: {traceback.format_exc()}")
|
||||
await self.logger.error(f'Error in handle_callback_request: {traceback.format_exc()}')
|
||||
return f'Error processing request: {str(e)}', 400
|
||||
|
||||
async def run_task(self, host: str, port: int, *args, **kwargs):
|
||||
@@ -301,7 +300,7 @@ class WecomClient:
|
||||
except binascii.Error as e:
|
||||
raise ValueError(f'Invalid base64 string: {str(e)}')
|
||||
else:
|
||||
await self.logger.error("Image对象出错")
|
||||
await self.logger.error('Image对象出错')
|
||||
raise ValueError('image对象出错')
|
||||
|
||||
# 设置 multipart/form-data 格式的文件
|
||||
@@ -325,7 +324,7 @@ class WecomClient:
|
||||
self.access_token = await self.get_access_token(self.secret)
|
||||
media_id = await self.upload_to_work(image)
|
||||
if data.get('errcode', 0) != 0:
|
||||
await self.logger.error(f"上传图片失败:{data}")
|
||||
await self.logger.error(f'上传图片失败:{data}')
|
||||
raise Exception('failed to upload file')
|
||||
|
||||
media_id = data.get('media_id')
|
||||
|
||||
@@ -187,7 +187,7 @@ class WecomCSClient:
|
||||
self.access_token = await self.get_access_token(self.secret)
|
||||
return await self.send_text_msg(open_kfid, external_userid, msgid, content)
|
||||
if data['errcode'] != 0:
|
||||
await self.logger.error(f"发送消息失败:{data}")
|
||||
await self.logger.error(f'发送消息失败:{data}')
|
||||
raise Exception('Failed to send message')
|
||||
return data
|
||||
|
||||
@@ -227,7 +227,7 @@ class WecomCSClient:
|
||||
return 'success'
|
||||
except Exception as e:
|
||||
if self.logger:
|
||||
await self.logger.error(f"Error in handle_callback_request: {traceback.format_exc()}")
|
||||
await self.logger.error(f'Error in handle_callback_request: {traceback.format_exc()}')
|
||||
else:
|
||||
traceback.print_exc()
|
||||
return f'Error processing request: {str(e)}', 400
|
||||
|
||||
@@ -13,7 +13,9 @@ class PipelinesRouterGroup(group.RouterGroup):
|
||||
if quart.request.method == 'GET':
|
||||
sort_by = quart.request.args.get('sort_by', 'created_at')
|
||||
sort_order = quart.request.args.get('sort_order', 'DESC')
|
||||
return self.success(data={'pipelines': await self.ap.pipeline_service.get_pipelines(sort_by, sort_order)})
|
||||
return self.success(
|
||||
data={'pipelines': await self.ap.pipeline_service.get_pipelines(sort_by, sort_order)}
|
||||
)
|
||||
elif quart.request.method == 'POST':
|
||||
json_data = await quart.request.json
|
||||
|
||||
|
||||
@@ -78,7 +78,9 @@ class KnowledgeService:
|
||||
runtime_kb = await self.ap.rag_mgr.get_knowledge_base_by_uuid(kb_uuid)
|
||||
if runtime_kb is None:
|
||||
raise Exception('Knowledge base not found')
|
||||
return [result.model_dump() for result in await runtime_kb.retrieve(query,runtime_kb.knowledge_base_entity.top_k)]
|
||||
return [
|
||||
result.model_dump() for result in await runtime_kb.retrieve(query, runtime_kb.knowledge_base_entity.top_k)
|
||||
]
|
||||
|
||||
async def get_files_by_knowledge_base(self, kb_uuid: str) -> list[dict]:
|
||||
"""获取知识库文件"""
|
||||
|
||||
@@ -21,9 +21,11 @@ from ..types import message as platform_message
|
||||
from ..types import events as platform_events
|
||||
from ..types import entities as platform_entities
|
||||
|
||||
|
||||
# 语音功能相关异常定义
|
||||
class VoiceConnectionError(Exception):
|
||||
"""语音连接基础异常"""
|
||||
|
||||
def __init__(self, message: str, error_code: str = None, guild_id: int = None):
|
||||
super().__init__(message)
|
||||
self.error_code = error_code
|
||||
@@ -33,8 +35,9 @@ class VoiceConnectionError(Exception):
|
||||
|
||||
class VoicePermissionError(VoiceConnectionError):
|
||||
"""语音权限异常"""
|
||||
|
||||
def __init__(self, message: str, missing_permissions: list = None, user_id: int = None, channel_id: int = None):
|
||||
super().__init__(message, "PERMISSION_ERROR")
|
||||
super().__init__(message, 'PERMISSION_ERROR')
|
||||
self.missing_permissions = missing_permissions or []
|
||||
self.user_id = user_id
|
||||
self.channel_id = channel_id
|
||||
@@ -42,20 +45,22 @@ class VoicePermissionError(VoiceConnectionError):
|
||||
|
||||
class VoiceNetworkError(VoiceConnectionError):
|
||||
"""语音网络异常"""
|
||||
|
||||
def __init__(self, message: str, retry_count: int = 0):
|
||||
super().__init__(message, "NETWORK_ERROR")
|
||||
super().__init__(message, 'NETWORK_ERROR')
|
||||
self.retry_count = retry_count
|
||||
self.last_attempt = datetime.datetime.now()
|
||||
|
||||
|
||||
class VoiceConnectionStatus(Enum):
|
||||
"""语音连接状态枚举"""
|
||||
IDLE = "idle"
|
||||
CONNECTING = "connecting"
|
||||
CONNECTED = "connected"
|
||||
PLAYING = "playing"
|
||||
RECONNECTING = "reconnecting"
|
||||
FAILED = "failed"
|
||||
|
||||
IDLE = 'idle'
|
||||
CONNECTING = 'connecting'
|
||||
CONNECTED = 'connected'
|
||||
PLAYING = 'playing'
|
||||
RECONNECTING = 'reconnecting'
|
||||
FAILED = 'failed'
|
||||
|
||||
|
||||
class VoiceConnectionInfo:
|
||||
@@ -83,14 +88,14 @@ class VoiceConnectionInfo:
|
||||
"""
|
||||
self.guild_id = guild_id
|
||||
self.channel_id = channel_id
|
||||
self.channel_name = channel_name or f"Channel-{channel_id}"
|
||||
self.channel_name = channel_name or f'Channel-{channel_id}'
|
||||
self.connected = False
|
||||
self.connection_time: datetime.datetime = None
|
||||
self.last_activity = datetime.datetime.now()
|
||||
self.status = VoiceConnectionStatus.IDLE
|
||||
self.user_count = 0
|
||||
self.latency = 0.0
|
||||
self.connection_health = "unknown"
|
||||
self.connection_health = 'unknown'
|
||||
self.voice_client = None
|
||||
|
||||
def update_status(self, status: VoiceConnectionStatus):
|
||||
@@ -124,16 +129,16 @@ class VoiceConnectionInfo:
|
||||
dict: 连接信息的字典表示
|
||||
"""
|
||||
return {
|
||||
"guild_id": self.guild_id,
|
||||
"channel_id": self.channel_id,
|
||||
"channel_name": self.channel_name,
|
||||
"connected": self.connected,
|
||||
"connection_time": self.connection_time.isoformat() if self.connection_time else None,
|
||||
"last_activity": self.last_activity.isoformat(),
|
||||
"status": self.status.value,
|
||||
"user_count": self.user_count,
|
||||
"latency": self.latency,
|
||||
"connection_health": self.connection_health
|
||||
'guild_id': self.guild_id,
|
||||
'channel_id': self.channel_id,
|
||||
'channel_name': self.channel_name,
|
||||
'connected': self.connected,
|
||||
'connection_time': self.connection_time.isoformat() if self.connection_time else None,
|
||||
'last_activity': self.last_activity.isoformat(),
|
||||
'status': self.status.value,
|
||||
'user_count': self.user_count,
|
||||
'latency': self.latency,
|
||||
'connection_health': self.connection_health,
|
||||
}
|
||||
|
||||
|
||||
@@ -166,8 +171,7 @@ class VoiceConnectionManager:
|
||||
self._cleanup_task = None
|
||||
self._monitoring_enabled = True
|
||||
|
||||
async def join_voice_channel(self, guild_id: int, channel_id: int,
|
||||
user_id: int = None) -> discord.VoiceClient:
|
||||
async def join_voice_channel(self, guild_id: int, channel_id: int, user_id: int = None) -> discord.VoiceClient:
|
||||
"""
|
||||
加入语音频道
|
||||
|
||||
@@ -194,19 +198,11 @@ class VoiceConnectionManager:
|
||||
# 获取服务器和频道对象
|
||||
guild = self.bot.get_guild(guild_id)
|
||||
if not guild:
|
||||
raise VoiceConnectionError(
|
||||
f"无法找到服务器 {guild_id}",
|
||||
"GUILD_NOT_FOUND",
|
||||
guild_id
|
||||
)
|
||||
raise VoiceConnectionError(f'无法找到服务器 {guild_id}', 'GUILD_NOT_FOUND', guild_id)
|
||||
|
||||
channel = guild.get_channel(channel_id)
|
||||
if not channel or not isinstance(channel, discord.VoiceChannel):
|
||||
raise VoiceConnectionError(
|
||||
f"无法找到语音频道 {channel_id}",
|
||||
"CHANNEL_NOT_FOUND",
|
||||
guild_id
|
||||
)
|
||||
raise VoiceConnectionError(f'无法找到语音频道 {channel_id}', 'CHANNEL_NOT_FOUND', guild_id)
|
||||
|
||||
# 验证用户是否在语音频道中(如果提供了用户ID)
|
||||
if user_id:
|
||||
@@ -221,7 +217,7 @@ class VoiceConnectionManager:
|
||||
if existing_conn.connected and existing_conn.voice_client:
|
||||
if existing_conn.channel_id == channel_id:
|
||||
# 已连接到相同频道,返回现有连接
|
||||
await self.logger.info(f"复用现有语音连接: {guild.name} -> {channel.name}")
|
||||
await self.logger.info(f'复用现有语音连接: {guild.name} -> {channel.name}')
|
||||
return existing_conn.voice_client
|
||||
else:
|
||||
# 连接到不同频道,先断开旧连接
|
||||
@@ -237,16 +233,16 @@ class VoiceConnectionManager:
|
||||
conn_info.user_count = len(channel.members)
|
||||
self.connections[guild_id] = conn_info
|
||||
|
||||
await self.logger.info(f"成功连接到语音频道: {guild.name} -> {channel.name}")
|
||||
await self.logger.info(f'成功连接到语音频道: {guild.name} -> {channel.name}')
|
||||
return voice_client
|
||||
|
||||
except discord.ClientException as e:
|
||||
raise VoiceNetworkError(f"Discord 客户端错误: {str(e)}")
|
||||
raise VoiceNetworkError(f'Discord 客户端错误: {str(e)}')
|
||||
except discord.opus.OpusNotLoaded as e:
|
||||
raise VoiceConnectionError(f"Opus 编码器未加载: {str(e)}", "OPUS_NOT_LOADED", guild_id)
|
||||
raise VoiceConnectionError(f'Opus 编码器未加载: {str(e)}', 'OPUS_NOT_LOADED', guild_id)
|
||||
except Exception as e:
|
||||
await self.logger.error(f"连接语音频道时发生未知错误: {str(e)}")
|
||||
raise VoiceConnectionError(f"连接失败: {str(e)}", "UNKNOWN_ERROR", guild_id)
|
||||
await self.logger.error(f'连接语音频道时发生未知错误: {str(e)}')
|
||||
raise VoiceConnectionError(f'连接失败: {str(e)}', 'UNKNOWN_ERROR', guild_id)
|
||||
|
||||
async def leave_voice_channel(self, guild_id: int) -> bool:
|
||||
"""
|
||||
@@ -298,11 +294,11 @@ class VoiceConnectionManager:
|
||||
conn_info.update_status(VoiceConnectionStatus.IDLE)
|
||||
del self.connections[guild_id]
|
||||
|
||||
await self.logger.info(f"已断开语音连接: Guild {guild_id}")
|
||||
await self.logger.info(f'已断开语音连接: Guild {guild_id}')
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
await self.logger.error(f"断开语音连接时发生错误: {str(e)}")
|
||||
await self.logger.error(f'断开语音连接时发生错误: {str(e)}')
|
||||
# 即使出错也要清理连接记录
|
||||
conn_info.update_status(VoiceConnectionStatus.FAILED)
|
||||
if guild_id in self.connections:
|
||||
@@ -382,7 +378,7 @@ class VoiceConnectionManager:
|
||||
# 更新实时信息
|
||||
if conn_info.voice_client and conn_info.voice_client.is_connected():
|
||||
conn_info.latency = conn_info.voice_client.latency * 1000 # 转换为毫秒
|
||||
conn_info.connection_health = "good" if conn_info.latency < 100 else "poor"
|
||||
conn_info.connection_health = 'good' if conn_info.latency < 100 else 'poor'
|
||||
|
||||
# 更新频道用户数
|
||||
guild = self.bot.get_guild(guild_id)
|
||||
@@ -436,36 +432,32 @@ class VoiceConnectionManager:
|
||||
# 获取用户信息
|
||||
users = []
|
||||
for member in channel.members:
|
||||
users.append({
|
||||
"id": member.id,
|
||||
"name": member.display_name,
|
||||
"status": str(member.status),
|
||||
"is_bot": member.bot
|
||||
})
|
||||
users.append(
|
||||
{'id': member.id, 'name': member.display_name, 'status': str(member.status), 'is_bot': member.bot}
|
||||
)
|
||||
|
||||
# 获取权限信息
|
||||
bot_member = guild.me
|
||||
permissions = channel.permissions_for(bot_member)
|
||||
|
||||
return {
|
||||
"channel_id": channel_id,
|
||||
"channel_name": channel.name,
|
||||
"guild_id": guild_id,
|
||||
"guild_name": guild.name,
|
||||
"user_limit": channel.user_limit,
|
||||
"current_users": users,
|
||||
"user_count": len(users),
|
||||
"bitrate": channel.bitrate,
|
||||
"permissions": {
|
||||
"connect": permissions.connect,
|
||||
"speak": permissions.speak,
|
||||
"use_voice_activation": permissions.use_voice_activation,
|
||||
"priority_speaker": permissions.priority_speaker
|
||||
}
|
||||
'channel_id': channel_id,
|
||||
'channel_name': channel.name,
|
||||
'guild_id': guild_id,
|
||||
'guild_name': guild.name,
|
||||
'user_limit': channel.user_limit,
|
||||
'current_users': users,
|
||||
'user_count': len(users),
|
||||
'bitrate': channel.bitrate,
|
||||
'permissions': {
|
||||
'connect': permissions.connect,
|
||||
'speak': permissions.speak,
|
||||
'use_voice_activation': permissions.use_voice_activation,
|
||||
'priority_speaker': permissions.priority_speaker,
|
||||
},
|
||||
}
|
||||
|
||||
async def _validate_user_in_channel(self, guild: discord.Guild,
|
||||
channel: discord.VoiceChannel, user_id: int):
|
||||
async def _validate_user_in_channel(self, guild: discord.Guild, channel: discord.VoiceChannel, user_id: int):
|
||||
"""
|
||||
验证用户是否在语音频道中
|
||||
|
||||
@@ -481,19 +473,14 @@ class VoiceConnectionManager:
|
||||
"""
|
||||
member = guild.get_member(user_id)
|
||||
if not member:
|
||||
raise VoicePermissionError(
|
||||
f"无法找到用户 {user_id}",
|
||||
["member_not_found"],
|
||||
user_id,
|
||||
channel.id
|
||||
)
|
||||
raise VoicePermissionError(f'无法找到用户 {user_id}', ['member_not_found'], user_id, channel.id)
|
||||
|
||||
if not member.voice or member.voice.channel != channel:
|
||||
raise VoicePermissionError(
|
||||
f"用户 {member.display_name} 不在语音频道 {channel.name} 中",
|
||||
["user_not_in_channel"],
|
||||
f'用户 {member.display_name} 不在语音频道 {channel.name} 中',
|
||||
['user_not_in_channel'],
|
||||
user_id,
|
||||
channel.id
|
||||
channel.id,
|
||||
)
|
||||
|
||||
async def _validate_bot_permissions(self, channel: discord.VoiceChannel):
|
||||
@@ -514,15 +501,15 @@ class VoiceConnectionManager:
|
||||
missing_permissions = []
|
||||
|
||||
if not permissions.connect:
|
||||
missing_permissions.append("connect")
|
||||
missing_permissions.append('connect')
|
||||
if not permissions.speak:
|
||||
missing_permissions.append("speak")
|
||||
missing_permissions.append('speak')
|
||||
|
||||
if missing_permissions:
|
||||
raise VoicePermissionError(
|
||||
f"机器人在频道 {channel.name} 中缺少权限: {', '.join(missing_permissions)}",
|
||||
f'机器人在频道 {channel.name} 中缺少权限: {", ".join(missing_permissions)}',
|
||||
missing_permissions,
|
||||
channel_id=channel.id
|
||||
channel_id=channel.id,
|
||||
)
|
||||
|
||||
async def cleanup_inactive_connections(self):
|
||||
@@ -543,7 +530,7 @@ class VoiceConnectionManager:
|
||||
await self._disconnect_internal(guild_id)
|
||||
|
||||
if cleanup_guilds:
|
||||
await self.logger.info(f"清理了 {len(cleanup_guilds)} 个无效的语音连接")
|
||||
await self.logger.info(f'清理了 {len(cleanup_guilds)} 个无效的语音连接')
|
||||
|
||||
async def start_monitoring(self):
|
||||
"""
|
||||
@@ -840,8 +827,7 @@ class DiscordAdapter(adapter.MessagePlatformAdapter):
|
||||
self.bot = MyClient(intents=intents, **args)
|
||||
|
||||
# Voice functionality methods
|
||||
async def join_voice_channel(self, guild_id: int, channel_id: int,
|
||||
user_id: int = None) -> discord.VoiceClient:
|
||||
async def join_voice_channel(self, guild_id: int, channel_id: int, user_id: int = None) -> discord.VoiceClient:
|
||||
"""
|
||||
加入语音频道
|
||||
|
||||
@@ -865,7 +851,7 @@ class DiscordAdapter(adapter.MessagePlatformAdapter):
|
||||
VoiceConnectionError: 其他连接错误
|
||||
"""
|
||||
if not self.voice_manager:
|
||||
raise VoiceConnectionError("语音管理器未初始化", "MANAGER_NOT_READY")
|
||||
raise VoiceConnectionError('语音管理器未初始化', 'MANAGER_NOT_READY')
|
||||
|
||||
return await self.voice_manager.join_voice_channel(guild_id, channel_id, user_id)
|
||||
|
||||
@@ -1079,7 +1065,7 @@ class DiscordAdapter(adapter.MessagePlatformAdapter):
|
||||
self.voice_manager = VoiceConnectionManager(self.bot, self.logger)
|
||||
await self.voice_manager.start_monitoring()
|
||||
|
||||
await self.logger.info("Discord 适配器语音功能已启用")
|
||||
await self.logger.info('Discord 适配器语音功能已启用')
|
||||
await self.bot.start(self.config['token'], reconnect=True)
|
||||
|
||||
async def kill(self) -> bool:
|
||||
@@ -1095,4 +1081,3 @@ class DiscordAdapter(adapter.MessagePlatformAdapter):
|
||||
|
||||
await self.bot.close()
|
||||
return True
|
||||
|
||||
|
||||
@@ -501,7 +501,7 @@ class OfficialAdapter(adapter_model.MessagePlatformAdapter):
|
||||
for event_handler in event_handler_mapping[event_type]:
|
||||
setattr(self.bot, event_handler, wrapper)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error in qqbotpy callback: {traceback.format_exc()}")
|
||||
self.logger.error(f'Error in qqbotpy callback: {traceback.format_exc()}')
|
||||
raise e
|
||||
|
||||
def unregister_listener(
|
||||
|
||||
@@ -29,10 +29,9 @@ import logging
|
||||
|
||||
|
||||
class WeChatPadMessageConverter(adapter.MessageConverter):
|
||||
|
||||
def __init__(self, config: dict, logger: logging.Logger):
|
||||
self.config = config
|
||||
self.bot = WeChatPadClient(self.config["wechatpad_url"],self.config["token"])
|
||||
self.bot = WeChatPadClient(self.config['wechatpad_url'], self.config['token'])
|
||||
self.logger = logger
|
||||
|
||||
@staticmethod
|
||||
@@ -41,9 +40,9 @@ class WeChatPadMessageConverter(adapter.MessageConverter):
|
||||
|
||||
for component in message_chain:
|
||||
if isinstance(component, platform_message.AtAll):
|
||||
content_list.append({"type": "at", "target": "all"})
|
||||
content_list.append({'type': 'at', 'target': 'all'})
|
||||
elif isinstance(component, platform_message.At):
|
||||
content_list.append({"type": "at", "target": component.target})
|
||||
content_list.append({'type': 'at', 'target': component.target})
|
||||
elif isinstance(component, platform_message.Plain):
|
||||
content_list.append({'type': 'text', 'content': component.text})
|
||||
elif isinstance(component, platform_message.Image):
|
||||
@@ -77,9 +76,9 @@ class WeChatPadMessageConverter(adapter.MessageConverter):
|
||||
return content_list
|
||||
|
||||
async def target2yiri(
|
||||
self,
|
||||
message: dict,
|
||||
bot_account_id: str,
|
||||
self,
|
||||
message: dict,
|
||||
bot_account_id: str,
|
||||
) -> platform_message.MessageChain:
|
||||
"""外部消息转平台消息"""
|
||||
# 数据预处理
|
||||
@@ -92,8 +91,8 @@ class WeChatPadMessageConverter(adapter.MessageConverter):
|
||||
if is_group_message:
|
||||
ats_bot = self._ats_bot(message, bot_account_id)
|
||||
|
||||
self.logger.info(f"ats_bot: {ats_bot}; bot_account_id: {bot_account_id}; bot_wxid: {bot_wxid}")
|
||||
if "@所有人" in content:
|
||||
self.logger.info(f'ats_bot: {ats_bot}; bot_account_id: {bot_account_id}; bot_wxid: {bot_wxid}')
|
||||
if '@所有人' in content:
|
||||
message_list.append(platform_message.AtAll())
|
||||
if ats_bot:
|
||||
message_list.append(platform_message.At(target=bot_account_id))
|
||||
@@ -421,12 +420,12 @@ class WeChatPadMessageConverter(adapter.MessageConverter):
|
||||
msg_source = message.get('msg_source', '') or ''
|
||||
if len(msg_source) > 0:
|
||||
msg_source_data = ET.fromstring(msg_source)
|
||||
at_user_list = msg_source_data.findtext("atuserlist") or ""
|
||||
at_user_list = msg_source_data.findtext('atuserlist') or ''
|
||||
if at_user_list:
|
||||
# atuserlist格式通常是逗号分隔的用户ID列表
|
||||
at_targets = [user_id.strip() for user_id in at_user_list.split(',') if user_id.strip()]
|
||||
except Exception as e:
|
||||
self.logger.error(f"_extract_at_targets got except: {e}")
|
||||
self.logger.error(f'_extract_at_targets got except: {e}')
|
||||
return at_targets
|
||||
|
||||
# 提取一下content前面的sender_id, 和去掉前缀的内容
|
||||
@@ -452,7 +451,6 @@ class WeChatPadMessageConverter(adapter.MessageConverter):
|
||||
|
||||
|
||||
class WeChatPadEventConverter(adapter.EventConverter):
|
||||
|
||||
def __init__(self, config: dict, logger: logging.Logger):
|
||||
self.config = config
|
||||
self.message_converter = WeChatPadMessageConverter(config, logger)
|
||||
@@ -463,11 +461,10 @@ class WeChatPadEventConverter(adapter.EventConverter):
|
||||
pass
|
||||
|
||||
async def target2yiri(
|
||||
self,
|
||||
event: dict,
|
||||
bot_account_id: str,
|
||||
self,
|
||||
event: dict,
|
||||
bot_account_id: str,
|
||||
) -> platform_events.MessageEvent:
|
||||
|
||||
# 排除公众号以及微信团队消息
|
||||
if (
|
||||
event['from_user_name']['str'].startswith('gh_')
|
||||
@@ -579,26 +576,22 @@ class WeChatPadAdapter(adapter.MessagePlatformAdapter):
|
||||
for msg in content_list:
|
||||
# 文本消息处理@
|
||||
if msg['type'] == 'text' and at_targets:
|
||||
if "all" in at_targets:
|
||||
if 'all' in at_targets:
|
||||
msg['content'] = f'@所有人 {msg["content"]}'
|
||||
else:
|
||||
at_nick_name_list = []
|
||||
for member in member_info:
|
||||
if member["user_name"] in at_targets:
|
||||
if member['user_name'] in at_targets:
|
||||
at_nick_name_list.append(f'@{member["nick_name"]}')
|
||||
msg['content'] = f'{" ".join(at_nick_name_list)} {msg["content"]}'
|
||||
|
||||
# 统一消息派发
|
||||
handler_map = {
|
||||
'text': lambda msg: self.bot.send_text_message(
|
||||
to_wxid=target_id,
|
||||
message=msg['content'],
|
||||
ats= ["notify@all"] if "all" in at_targets else at_targets
|
||||
to_wxid=target_id, message=msg['content'], ats=['notify@all'] if 'all' in at_targets else at_targets
|
||||
),
|
||||
'image': lambda msg: self.bot.send_image_message(
|
||||
to_wxid=target_id,
|
||||
img_url=msg["image"],
|
||||
ats = ["notify@all"] if "all" in at_targets else at_targets
|
||||
to_wxid=target_id, img_url=msg['image'], ats=['notify@all'] if 'all' in at_targets else at_targets
|
||||
),
|
||||
'WeChatEmoji': lambda msg: self.bot.send_emoji_message(
|
||||
to_wxid=target_id, emoji_md5=msg['emoji_md5'], emoji_size=msg['emoji_size']
|
||||
|
||||
@@ -812,12 +812,14 @@ class File(MessageComponent):
|
||||
def __str__(self):
|
||||
return f'[文件]{self.name}'
|
||||
|
||||
|
||||
class Face(MessageComponent):
|
||||
"""系统表情
|
||||
此处将超级表情骰子/划拳,一同归类于face
|
||||
当face_type为rps(划拳)时 face_id 对应的是手势
|
||||
当face_type为dice(骰子)时 face_id 对应的是点数
|
||||
"""
|
||||
|
||||
type: str = 'Face'
|
||||
"""表情类型"""
|
||||
face_type: str = 'face'
|
||||
@@ -834,15 +836,15 @@ class Face(MessageComponent):
|
||||
elif self.face_type == 'rps':
|
||||
return f'[表情]{self.face_name}({self.rps_data(self.face_id)})'
|
||||
|
||||
|
||||
def rps_data(self,face_id):
|
||||
rps_dict ={
|
||||
1 : "布",
|
||||
2 : "剪刀",
|
||||
3 : "石头",
|
||||
def rps_data(self, face_id):
|
||||
rps_dict = {
|
||||
1: '布',
|
||||
2: '剪刀',
|
||||
3: '石头',
|
||||
}
|
||||
return rps_dict[face_id]
|
||||
|
||||
|
||||
# ================ 个人微信专用组件 ================
|
||||
|
||||
|
||||
@@ -971,5 +973,6 @@ class WeChatFile(MessageComponent):
|
||||
"""文件地址"""
|
||||
file_base64: str = ''
|
||||
"""base64"""
|
||||
|
||||
def __str__(self):
|
||||
return f'[文件]{self.file_name}'
|
||||
@@ -56,7 +56,7 @@ class LocalAgentRunner(runner.RequestRunner):
|
||||
self.ap.logger.warning(f'Knowledge base {kb_uuid} not found')
|
||||
raise ValueError(f'Knowledge base {kb_uuid} not found')
|
||||
|
||||
result = await kb.retrieve(user_message_text,kb.knowledge_base_entity.top_k)
|
||||
result = await kb.retrieve(user_message_text, kb.knowledge_base_entity.top_k)
|
||||
|
||||
final_user_message_text = ''
|
||||
|
||||
|
||||
@@ -204,9 +204,9 @@ async def get_slack_image_to_base64(pic_url: str, bot_token: str):
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(pic_url, headers=headers) as resp:
|
||||
mime_type = resp.headers.get("Content-Type", "application/octet-stream")
|
||||
mime_type = resp.headers.get('Content-Type', 'application/octet-stream')
|
||||
file_bytes = await resp.read()
|
||||
base64_str = base64.b64encode(file_bytes).decode("utf-8")
|
||||
return f"data:{mime_type};base64,{base64_str}"
|
||||
base64_str = base64.b64encode(file_bytes).decode('utf-8')
|
||||
return f'data:{mime_type};base64,{base64_str}'
|
||||
except Exception as e:
|
||||
raise (e)
|
||||
@@ -32,7 +32,7 @@ def import_dir(path: str):
|
||||
rel_path = full_path.replace(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), '')
|
||||
rel_path = rel_path[1:]
|
||||
rel_path = rel_path.replace('/', '.')[:-3]
|
||||
rel_path = rel_path.replace("\\",".")
|
||||
rel_path = rel_path.replace('\\', '.')
|
||||
importlib.import_module(rel_path)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user