From 024f961d0181dd85846266e32fa94cf34364488f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9A=E7=BE=85=E7=8B=BC?= Date: Sat, 27 Jan 2024 14:10:01 +0800 Subject: [PATCH] fix --- core/dirty_check.py | 3 +- modules/ask/__init__.py | 13 ++- modules/dice/dice.py | 2 +- modules/dictionary/__init__.py | 21 ----- modules/dictionary/locales/en_us.json | 4 - modules/dictionary/locales/zh_cn.json | 4 - modules/dictionary/locales/zh_tw.json | 4 - modules/dictionary/screenshot.py | 128 -------------------------- modules/summary/__init__.py | 14 +-- 9 files changed, 18 insertions(+), 175 deletions(-) delete mode 100644 modules/dictionary/__init__.py delete mode 100644 modules/dictionary/locales/en_us.json delete mode 100644 modules/dictionary/locales/zh_cn.json delete mode 100644 modules/dictionary/locales/zh_tw.json delete mode 100644 modules/dictionary/screenshot.py diff --git a/core/dirty_check.py b/core/dirty_check.py index ac792fc8..988e0ca8 100644 --- a/core/dirty_check.py +++ b/core/dirty_check.py @@ -52,11 +52,12 @@ async def check(*text) -> list: '''检查字符串是否合规 :param text: 字符串(List/Union)。 - :returns: 经过审核后的字符串。不合规部分会被替换为'<吃掉了>',全部不合规则是'<全部吃掉了>' + :returns: 经过审核后的字符串。不合规部分会被替换为'<吃掉了>',全部不合规则是'<全部吃掉了>'。 ''' access_key_id = Config("check_accessKeyId") access_key_secret = Config("check_accessKeySecret") text = list(text) + text = text[0] if len(text) == 1 and isinstance(text[0], list) else text # 检查是否为嵌套的消息链 if not access_key_id or not access_key_secret or not EnableDirtyWordCheck.status: Logger.warn('Dirty words filter was disabled, skip.') query_list = [] diff --git a/modules/ask/__init__.py b/modules/ask/__init__.py index 2991fc7b..e013f902 100644 --- a/modules/ask/__init__.py +++ b/modules/ask/__init__.py @@ -90,7 +90,7 @@ if Config('openai_api_key'): break elif run.status == 'failed': if run.last_error.code == 'rate_limit_exceeded': - Logger.warning(run.last_error.json()) + Logger.warn(run.last_error.json()) raise NoReportException(msg.locale.t('ask.message.rate_limit_exceeded')) raise RuntimeError(run.last_error.json()) await asyncio.sleep(4) @@ -133,11 +133,14 @@ if Config('openai_api_key'): if petal != 0: chain.append(Plain(msg.locale.t('petal.message.cost', count=petal))) + chain = await check(chain) - if chain != []: - for x in chain: - m = x['content'] - await msg.send_message(m) + cchain = [] + for blocks in chain: + block = blocks['content'] + cchain.append(block) + + await msg.send_message(cchain, disable_secret_check=True) if msg.target.target_from != 'TEST|Console' and not is_superuser: qc.reset() diff --git a/modules/dice/dice.py b/modules/dice/dice.py index 6e242ebd..59fe43a3 100644 --- a/modules/dice/dice.py +++ b/modules/dice/dice.py @@ -138,7 +138,7 @@ class Dice(DiceItemBase): return (int(dice_count), int(dice_type), int(advantage)) def Roll(self, msg, use_markdown=False): - if msg.target.sender_from in ['Discord|Client', 'Kook|User', 'Telegram|User']: + if msg.target.sender_from in ['Discord|Client', 'Kook|User']: use_markdown = True output = '' result = 0 diff --git a/modules/dictionary/__init__.py b/modules/dictionary/__init__.py deleted file mode 100644 index f6f57850..00000000 --- a/modules/dictionary/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -from core.builtins import Bot, Image, Plain -from core.component import module -from .screenshot import get_pic - -dict = module('dictionary', alias="dict", - desc='{dictionary.help.desc}', developers=['Dianliang233'], support_languages=['en_us']) - - -@dict.command(help_doc=' {{dictionary.help}}') -async def _(msg: Bot.MessageSession, term: str): - pic_collins = await get_pic( - 'https://www.collinsdictionary.com/dictionary/english/' + str(term).replace(' ', - '-').lower(), - 'collins') - # pic_yd = await get_pic('https://www.youdao.com/result?word=' + msg.parsed_msg[''] + '&lang=en', 'yd') - # if pic_collins or pic_yd: - if pic_collins: - # await msg.finish([Image(pic_collins), Image(pic_yd), - await msg.finish([Image(pic_collins), Plain( - f'https://www.collinsdictionary.com/dictionary/english/{term}')]) -# 有道:https://www.youdao.com/result?lang=en&word={msg.parsed_msg[""]}''']) diff --git a/modules/dictionary/locales/en_us.json b/modules/dictionary/locales/en_us.json deleted file mode 100644 index 54df6024..00000000 --- a/modules/dictionary/locales/en_us.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "dictionary.help": "Query terms in the Collins Dictionary.", - "dictionary.help.desc": "Query Collins Dictionary." -} diff --git a/modules/dictionary/locales/zh_cn.json b/modules/dictionary/locales/zh_cn.json deleted file mode 100644 index edf143a4..00000000 --- a/modules/dictionary/locales/zh_cn.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "dictionary.help": "在柯林斯词典中查询单词。", - "dictionary.help.desc": "查询柯林斯词典。" -} diff --git a/modules/dictionary/locales/zh_tw.json b/modules/dictionary/locales/zh_tw.json deleted file mode 100644 index 02dd559a..00000000 --- a/modules/dictionary/locales/zh_tw.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "dictionary.help": "在柯林斯詞典中查詢單詞。", - "dictionary.help.desc": "查詢柯林斯詞典。" -} diff --git a/modules/dictionary/screenshot.py b/modules/dictionary/screenshot.py deleted file mode 100644 index 256d5ef7..00000000 --- a/modules/dictionary/screenshot.py +++ /dev/null @@ -1,128 +0,0 @@ -import os -import re -import traceback -import uuid -from typing import Union -from urllib.parse import urljoin - -import aiohttp -import ujson as json -from bs4 import BeautifulSoup - -from config import CFG -from core.logger import Logger - -web_render = CFG.get_url('web_render') -web_render_local = CFG.get_url('web_render_local') - - -async def get_pic(link, source, use_local=True) -> Union[str, bool]: - if not web_render_local: - if not web_render: - Logger.warn('[Webrender] Webrender is not configured.') - return False - use_local = False - try: - Logger.info('Starting find section...') - try: - async with aiohttp.ClientSession() as session: - async with session.get((web_render_local if use_local else web_render) + 'source?url=' + link, - timeout=aiohttp.ClientTimeout(total=20)) as req: - html = await req.read() - except BaseException: - traceback.print_exc() - return False - soup = BeautifulSoup(html, 'html.parser') - pagename = uuid.uuid4() - url = os.path.abspath(f'./cache/{pagename}.html') - if os.path.exists(url): - os.remove(url) - Logger.info('Downloaded raw.') - open_file = open(url, 'a', encoding='utf-8') - - def join_url(base, target): - target = target.split(' ') - targetlist = [] - for x in target: - if x.find('/') != -1: - x = urljoin(base, x) - targetlist.append(x) - target = ' '.join(targetlist) - return target - - open_file.write('\n') - for x in soup.find_all('html'): - fl = [] - for f in x.attrs: - if isinstance(x.attrs[f], str): - fl.append(f'{f}="{x.attrs[f]}"') - elif isinstance(x.attrs[f], list): - fl.append(f'{f}="{" ".join(x.attrs[f])}"') - open_file.write(f'') - - open_file.write('\n') - for x in soup.find_all(rel='stylesheet'): - if x.has_attr('href'): - x.attrs['href'] = re.sub( - ';', '&', urljoin(link, x.get('href'))) - open_file.write(str(x)) - - for x in soup.find_all(): - if x.has_attr('href'): - x.attrs['href'] = re.sub( - ';', '&', urljoin(link, x.get('href'))) - open_file.write('') - - for x in soup.find_all('style'): - open_file.write(str(x)) - - for x in soup.find_all('body'): - if x.has_attr('class'): - open_file.write( - f'') - - for x in soup.find_all(['a', 'img', 'span']): - if x.has_attr('href'): - x.attrs['href'] = join_url(link, x.get('href')) - if x.has_attr('src'): - x.attrs['src'] = join_url(link, x.get('src')) - if x.has_attr('srcset'): - x.attrs['srcset'] = join_url(link, x.get('srcset')) - if x.has_attr('style'): - x.attrs['style'] = re.sub( - r'url\(/(.*)\)', 'url(' + link + '\\1)', x.get('style')) - if source == 'collins': - open_file.write('
') - content = soup.select_one( - '.dictionaries > .dictionary, .dictionaries.dictionary') - trash = content.select( - '.hwd_sound, .cobuild-logo, .pronIPASymbol, .title_frequency_container') - if trash: - for x in trash: - x.decompose() - elif source == 'yd': - open_file.write('
') - content = soup.select_one('.basic') - else: - return False - open_file.write(str(content)) - w = 1000 - open_file.write('
') - open_file.write('') - open_file.close() - read_file = open(url, 'r', encoding='utf-8') - html = {'content': read_file.read(), 'width': w} - Logger.info('Start rendering...') - picname = os.path.abspath(f'./cache/{pagename}.jpg') - if os.path.exists(picname): - os.remove(picname) - async with aiohttp.ClientSession() as session: - async with session.post((web_render_local if use_local else web_render), headers={ - 'Content-Type': 'application/json', - }, data=json.dumps(html)) as resp: - with open(picname, 'wb+') as jpg: - jpg.write(await resp.read()) - return picname - except Exception: - traceback.print_exc() - return False diff --git a/modules/summary/__init__.py b/modules/summary/__init__.py index b6f26f44..cb835a3f 100644 --- a/modules/summary/__init__.py +++ b/modules/summary/__init__.py @@ -84,14 +84,14 @@ async def _(msg: Bot.MessageSession): output = f"{output}\n{msg.locale.t('petal.message.cost', count=petal)}" await wait_msg.delete() - output = await check(output) - if output != '': - for x in output: - m = x['content'] - await msg.send_message(m) - if msg.target.target_from != 'TEST|Console' and not is_superuser: qc.reset() - await msg.finish(output, disable_secret_check=True) + + output = await check(output) + res = [] + for blocks in output: + block = blocks['content'] + res.append(block) + await msg.finish(res, disable_secret_check=True) else: await msg.finish(msg.locale.t('message.cooldown', time=int(c), cd_time='60')) \ No newline at end of file