Archived
1
0
Fork 0
This commit is contained in:
多羅狼 2024-01-27 14:10:01 +08:00 committed by GitHub
parent 06d82299ae
commit 024f961d01
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 18 additions and 175 deletions

View file

@ -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 = []

View file

@ -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()

View file

@ -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

View file

@ -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>"]}'''])

View file

@ -1,4 +0,0 @@
{
"dictionary.help": "Query terms in the Collins Dictionary.",
"dictionary.help.desc": "Query Collins Dictionary."
}

View file

@ -1,4 +0,0 @@
{
"dictionary.help": "在柯林斯词典中查询单词。",
"dictionary.help.desc": "查询柯林斯词典。"
}

View file

@ -1,4 +0,0 @@
{
"dictionary.help": "在柯林斯詞典中查詢單詞。",
"dictionary.help.desc": "查詢柯林斯詞典。"
}

View file

@ -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

View file

@ -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'))