fix
This commit is contained in:
parent
06d82299ae
commit
024f961d01
9 changed files with 18 additions and 175 deletions
|
@ -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 = []
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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='<term> {{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['<term>'] + '&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["<term>"]}'''])
|
|
@ -1,4 +0,0 @@
|
|||
{
|
||||
"dictionary.help": "Query terms in the Collins Dictionary.",
|
||||
"dictionary.help.desc": "Query Collins Dictionary."
|
||||
}
|
|
@ -1,4 +0,0 @@
|
|||
{
|
||||
"dictionary.help": "在柯林斯词典中查询单词。",
|
||||
"dictionary.help.desc": "查询柯林斯词典。"
|
||||
}
|
|
@ -1,4 +0,0 @@
|
|||
{
|
||||
"dictionary.help": "在柯林斯詞典中查詢單詞。",
|
||||
"dictionary.help.desc": "查詢柯林斯詞典。"
|
||||
}
|
|
@ -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('<!DOCTYPE html>\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'<html {" ".join(fl)}>')
|
||||
|
||||
open_file.write('<head>\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('</head>')
|
||||
|
||||
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'<body class="{" ".join(x.get("class"))}">')
|
||||
|
||||
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('<div id="main_content" class="he dc page">')
|
||||
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('<div class="simple basic">')
|
||||
content = soup.select_one('.basic')
|
||||
else:
|
||||
return False
|
||||
open_file.write(str(content))
|
||||
w = 1000
|
||||
open_file.write('</div></body>')
|
||||
open_file.write('</html>')
|
||||
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
|
|
@ -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'))
|
Reference in a new issue