Skip to content

Commit

Permalink
Merge pull request #60 from JustOneSummer/master
Browse files Browse the repository at this point in the history
解决异步阻塞的问题
  • Loading branch information
benx1n authored Sep 3, 2024
2 parents 3333feb + 91ff685 commit fab3ef2
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 21 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,6 @@ echarts.js
src/plugins/hikari_bot/game/ocr_data.json
src/plugins/hikari_bot/game/account_data
src/plugins/hikari_bot/game/listen_config.json
.idea/
minimap_renderer_temp/
poetry.lock
25 changes: 16 additions & 9 deletions src/plugins/hikari_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
GroupMessageEvent,
Message,
MessageEvent,
MessageSegment,
NoticeEvent,
MessageSegment,
PrivateMessageEvent,
)
from nonebot.log import logger
Expand All @@ -30,7 +30,7 @@
from nonebot_plugin_guild_patch import GuildMessageEvent

from .data_source import dir_path, nb2_file, template_path
from .game.minimap_renderer import get_rep
from .game.minimap_renderer import get_rep, get_file
from .game.ocr import (
downlod_OcrResult,
get_Random_Ocr_Pic,
Expand Down Expand Up @@ -79,8 +79,7 @@ async def main(bot: Bot, ev: MessageEvent, matchmsg: Message = CommandArg()): #
try:
server_type = None
if isinstance(ev, PrivateMessageEvent) and (
driver.config.private or str(ev.user_id) in driver.config.superusers
): # 私聊事件,superusers默认不受影响
driver.config.private or str(ev.user_id) in driver.config.superusers): # 私聊事件,superusers默认不受影响
server_type = 'QQ'
elif isinstance(ev, GroupMessageEvent) and driver.config.group and ev.group_id not in driver.config.ban_group_list: # 群聊事件
server_type = 'QQ'
Expand Down Expand Up @@ -187,14 +186,22 @@ async def GROUP_FILE_listen(bot: Bot, ev: NoticeEvent):
noticeType = str(ev.notice_type)
if not noticeType == 'group_upload':
return
if not str(ev.file.name).endswith('.wowsreplay'):
if not str(ev).__contains__('.wowsreplay'):
return
base64_file = await bot.get_image(file=ev.file.id)
# 调用接口转换
await get_rep(base64_file['base64'], bot, ev)
#
if str(ev).__contains__("'url':"):
base64_file = get_file(ev.file.url)
await get_rep(base64_file, bot, ev)
else:
base64_file = await bot.get_image(file=ev.file.id)
if not str(base64_file).__contains__("'base64':"):
await get_rep(base64_file['url'], bot, ev)
else:
# 带编码格式处理
await get_rep(base64_file['base64'], bot, ev)
except Exception:
logger.error(traceback.format_exc())
await bot.send(ev, MessageSegment.text('请求minimap_renderer服务异常'))
await bot.send(ev, MessageSegment.text("请求minimap_renderer服务异常"))
return


Expand Down
57 changes: 45 additions & 12 deletions src/plugins/hikari_bot/game/minimap_renderer.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,70 @@
import asyncio
import base64
import hashlib
import os

import requests
from nonebot import get_driver
from nonebot.adapters.onebot.v11 import Bot, MessageSegment, NoticeEvent
from nonebot.adapters.onebot.v11 import Bot, MessageSegment, NoticeEvent, Message
from requests.auth import HTTPBasicAuth
from concurrent.futures import ThreadPoolExecutor

driver = get_driver()
minimap_renderer_temp = "minimap_renderer_temp"
executor = ThreadPoolExecutor()


async def get_rep(wows_rep_file_base64: str, bot: Bot, ev: NoticeEvent):
file_hex = hashlib.sha256(wows_rep_file_base64.encode('utf-8')).hexdigest()
file_bytes = base64.b64decode(wows_rep_file_base64)

file_path_temp = os.getcwd() + os.sep + minimap_renderer_temp + os.sep + file_hex
wowsrepla_file = file_path_temp + ".wowsreplay"
if not os.path.exists(wowsrepla_file):
if wows_rep_file_base64.__contains__(".wowsreplay"):
wowsrepla_file = wows_rep_file_base64
else:
file_hex = hashlib.sha256(wows_rep_file_base64.encode('utf-8')).hexdigest()
file_bytes = base64.b64decode(wows_rep_file_base64)
file_path_temp = os.getcwd() + os.sep + minimap_renderer_temp + os.sep + file_hex
f_d = os.getcwd() + os.sep + minimap_renderer_temp
if not os.path.exists(f_d):
os.makedirs(f_d)
wowsrepla_file = file_path_temp + ".wowsreplay"
with open(wowsrepla_file, 'wb') as f:
f.write(file_bytes)
await bot.send(ev, MessageSegment.text("正在处理replays文件.预计耗时1分钟"))
f.close()
if not os.path.exists(wowsrepla_file):
await bot.send(ev, MessageSegment.text("文件不存在,ll和nc 部署的请检查服务是否在一个服务器上,否则请开启base64功能"))
else:
await bot.send(ev, MessageSegment.text("正在处理replays文件.预计耗时1分钟"))
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(executor, lambda: upload_http(wowsrepla_file))
if result is None:
await bot.send(ev, MessageSegment.text("生成视频文件异常!请检查 minimap_renderer 是否要更新."))
else:
await send_video(bot, ev, result)


def upload_http(wowsrepla_file: str):
upload_url = driver.config.minimap_renderer_url + "/upload_replays_video_url"
with open(wowsrepla_file, 'rb') as file:
files = {'file': file}
response = requests.post(upload_url, files=files, auth=HTTPBasicAuth(driver.config.minimap_renderer_user_name, driver.config.minimap_renderer_password), timeout=600)
if response.status_code == 200:
await send_video(bot, ev, response.text)
else:
await bot.send(ev, MessageSegment.text("生成视频文件异常!请检查 minimap_renderer 是否要更新."))
return response.text
return None


async def send_video(bot: Bot, ev: NoticeEvent, url: str):
# 构造视频文件消息
data = str(driver.config.minimap_renderer_url + "/video_url?file_name=" + url.replace("\"", ""))
await bot.send(ev, MessageSegment.video(data))
await bot.send_group_msg(group_id=int(ev.group_id), message=Message(MessageSegment.video(data)))


def get_file(url: str):
response = requests.get(url)
# 确保请求成功
if response.status_code == 200:
# 获取文件内容
file_content = response.content

# 对文件内容进行 Base64 编码
encoded_content = base64.b64encode(file_content)

# 将编码后的内容转换为字符串
return encoded_content.decode('utf-8')

0 comments on commit fab3ef2

Please sign in to comment.