Archived
1
0
Fork 0
This commit is contained in:
yzhh 2023-04-05 12:33:29 +08:00
parent 2eb7768b8d
commit 4e25b5293e
9 changed files with 62 additions and 48 deletions

View file

@ -8,16 +8,19 @@ config_path = abspath('./config/' + config_filename)
class CFG: class CFG:
def __init__(self):
self.cp = ConfigParser()
self.cp.read(config_path)
def config(self, q): def config(self, q):
cp = ConfigParser() section = self.cp.sections()
cp.read(config_path)
try:
section = cp.sections()
if len(section) == 0: if len(section) == 0:
raise ConfigFileNotFound(config_path) from None raise ConfigFileNotFound(config_path) from None
section = section[0] value = self.cp.get('secret', q, fallback=False)
value = cp.get(section, q) if not value:
except Exception: value = self.cp.get('cfg', q, fallback=False)
if not value:
return False return False
if value.upper() == 'TRUE': if value.upper() == 'TRUE':
return True return True
@ -27,5 +30,5 @@ class CFG:
Config = CFG().config Config = CFG().config
CachePath = Config('cache_path') CachePath = abspath(Config('cache_path'))
DBPath = Config('db_path') DBPath = abspath(Config('db_path'))

View file

@ -1,26 +1,32 @@
[secret]
db_path = mysql+pymysql://
Check_accessKeyId =
Check_accessKeySecret =
web_render =
botarcapi_url =
botarcapi_agent =
dc_token =
tg_token =
openai_api_key =
nl2c_model =
[cfg] [cfg]
debug = False debug = False
cache_path = ./cache/ cache_path = ./cache/
db_path = mysql+pymysql://
db_cache = False db_cache = False
issue_url = https://github.com/Teahouse-Studios/bot/issues/new/choose
bug_report_url = https://s.wd-ljt.com/botreportbug
wiki_whitelist_url = https://s.wd-ljt.com/botwhitelist
qq_msg_logging_to_db = True qq_msg_logging_to_db = True
qq_host = 127.0.0.1:11451 qq_host = 127.0.0.1:11451
qq_account = 2052142661 qq_account = 2052142661
dc_token =
base_superuser = QQ|2596322644 base_superuser = QQ|2596322644
Check_accessKeyId =
Check_accessKeySecret =
qq_enable_dirty_check = True qq_enable_dirty_check = True
qq_enable_urlmanager = True qq_enable_urlmanager = True
web_render =
web_render_local = web_render_local =
botarcapi_url =
botarcapi_agent =
tg_token =
slower_schedule = False slower_schedule = False
enable_tos = False enable_tos = False
enable_analytics = True enable_analytics = True
allow_request_private_ip = False allow_request_private_ip = False
enable_eval = True enable_eval = True
openai_api_key =
nl2c_model =

View file

@ -9,7 +9,7 @@ import filetype
from PIL import Image as PImage from PIL import Image as PImage
from tenacity import retry, stop_after_attempt from tenacity import retry, stop_after_attempt
from config import CachePath from config import CachePath, Config
from core.types.message.internal import Plain as P, Image as I, Voice as V, Embed as E, EmbedField as EF, \ from core.types.message.internal import Plain as P, Image as I, Voice as V, Embed as E, EmbedField as EF, \
Url as U, ErrorMessage as EMsg Url as U, ErrorMessage as EMsg
@ -59,8 +59,7 @@ class ErrorMessage(EMsg):
for l in locale_str: for l in locale_str:
error_message = error_message.replace(f'{{{l}}}', locale.t(l)) error_message = error_message.replace(f'{{{l}}}', locale.t(l))
self.error_message = locale.t('error.prompt', error_msg=error_message) + \ self.error_message = locale.t('error.prompt', error_msg=error_message) + \
str(Url( str(Url(Config('bug_report_url')))
'https://s.wd-ljt.com/botreportbug'))
def __str__(self): def __str__(self):
return self.error_message return self.error_message

View file

@ -5,7 +5,7 @@ from datetime import datetime
from aiocqhttp.exceptions import ActionFailed from aiocqhttp.exceptions import ActionFailed
from config import Config from config import Config
from core.builtins import command_prefix, ExecutionLockList, ErrorMessage, MessageSession, MessageTaskManager from core.builtins import command_prefix, ExecutionLockList, ErrorMessage, MessageSession, MessageTaskManager, Url
from core.exceptions import AbuseWarning, FinishedException, InvalidCommandFormatError, InvalidHelpDocTypeError, \ from core.exceptions import AbuseWarning, FinishedException, InvalidCommandFormatError, InvalidHelpDocTypeError, \
WaitCancelException, NoReportException WaitCancelException, NoReportException
from core.loader import ModulesManager from core.loader import ModulesManager
@ -294,7 +294,8 @@ async def parser(msg: MessageSession, require_enable_modules: bool = True, prefi
except Exception as e: except Exception as e:
Logger.error(traceback.format_exc()) Logger.error(traceback.format_exc())
await msg.sendMessage(ErrorMessage(msg.locale.t('error.prompt.report', err_msg=str(e)))) await msg.sendMessage(msg.locale.t('error.prompt.report', err_msg=str(e)) +
Url(Config('bug_report_url')))
return msg return msg
if running_mention: if running_mention:
if display.find('小可') != -1: if display.find('小可') != -1:

View file

@ -1,3 +1,4 @@
from config import Config
from core.builtins import MessageSession from core.builtins import MessageSession
from database import BotDBUtil from database import BotDBUtil
@ -11,7 +12,7 @@ async def warn_target(msg: MessageSession, reason=None):
if current_warns < 5: if current_warns < 5:
warn_template.append(msg.locale.t('tos.warning.count', current_warns=current_warns)) warn_template.append(msg.locale.t('tos.warning.count', current_warns=current_warns))
if current_warns <= 2: if current_warns <= 2:
warn_template.append(msg.locale.t('tos.warning.appeal')) warn_template.append(msg.locale.t('tos.warning.appeal', issue_url=Config('issue_url')))
if current_warns == 5: if current_warns == 5:
warn_template.append(msg.locale.t('tos.warning.last')) warn_template.append(msg.locale.t('tos.warning.last'))
if current_warns > 5: if current_warns > 5:

View file

@ -55,27 +55,27 @@ async def load_secret():
section = cp.sections() section = cp.sections()
if len(section) == 0: if len(section) == 0:
raise ConfigFileNotFound(config_path) from None raise ConfigFileNotFound(config_path) from None
section = section[0] options = cp.options('secret')
options = cp.options(section)
for option in options: for option in options:
value = cp.get(section, option) value = cp.get('secret', option)
if value.upper() not in ['', 'TRUE', 'FALSE']: if value.upper() not in ['', 'TRUE', 'FALSE']:
Secret.add(value.upper()) Secret.add(value.upper())
try:
async def append_ip(): async def append_ip():
try:
Logger.info('Fetching IP information...')
ip = await get_url('https://api.ip.sb/geoip', timeout=10, fmt='json') ip = await get_url('https://api.ip.sb/geoip', timeout=10, fmt='json')
if ip: if ip:
Secret.add(ip['ip']) Secret.add(ip['ip'])
IP.country = ip['country'] IP.country = ip['country']
IP.address = ip['ip'] IP.address = ip['ip']
Logger.info('Fetching IP information...')
await asyncio.create_task(append_ip())
Logger.info('Successfully fetched IP information.') Logger.info('Successfully fetched IP information.')
except Exception: except Exception:
Logger.info('Failed to get IP information.') Logger.info('Failed to get IP information.')
Logger.error(traceback.format_exc()) Logger.error(traceback.format_exc())
asyncio.create_task(append_ip())
async def load_prompt(bot) -> None: async def load_prompt(bot) -> None:
author_cache = os.path.abspath(PrivateAssets.path + '/cache_restart_author') author_cache = os.path.abspath(PrivateAssets.path + '/cache_restart_author')

View file

@ -7,6 +7,8 @@ import ujson as json
from .text import remove_suffix from .text import remove_suffix
from config import Config
# Load all locale files into memory # Load all locale files into memory
@ -87,7 +89,7 @@ class Locale:
if string is not None: if string is not None:
return string # 2. 如果在 fallback 语言中本地化字符串存在,直接返回 return string # 2. 如果在 fallback 语言中本地化字符串存在,直接返回
if fallback_failed_prompt: if fallback_failed_prompt:
return f'{{{key}}}' + self.t("i18n.prompt.fallback.failed") return f'{{{key}}}' + self.t("i18n.prompt.fallback.failed", url=Config('bug_report_url'))
else: else:
return key return key
# 3. 如果在 fallback 语言中本地化字符串不存在,返回 key # 3. 如果在 fallback 语言中本地化字符串不存在,返回 key

View file

@ -1,7 +1,7 @@
{ {
"i18n.prompt.fallback.failed": "(如果你看到了这条奇怪的字符串,说明我们又搞错了什么东西!\n请将问题反馈至\nhttps://s.wd-ljt.com/botreportbug\n以便我们快速解决此问题。", "i18n.prompt.fallback.failed": "(如果你看到了这条奇怪的字符串,说明我们又搞错了什么东西!\n请将问题反馈至\n${url}\n以便我们快速解决此问题。",
"error.prompt": "发生错误:${error_msg}\n错误汇报地址", "error.prompt": "发生错误:${error_msg}\n错误汇报地址",
"error.prompt.report": "执行命令时发生错误,请报告机器人开发者:\n${err_msg}", "error.prompt.report": "执行命令时发生错误,请报告机器人开发者:\n${err_msg}\n错误汇报地址",
"error.prompt.noreport": "执行命令时发生错误:\n${err_msg}\n此问题并非机器人程序错误API 请求出错等),请勿将此消息报告给机器人开发者。", "error.prompt.noreport": "执行命令时发生错误:\n${err_msg}\n此问题并非机器人程序错误API 请求出错等),请勿将此消息报告给机器人开发者。",
"error.message.chain.invalid": "机器人尝试发送非法消息链,请联系机器人开发者解决问题。", "error.message.chain.invalid": "机器人尝试发送非法消息链,请联系机器人开发者解决问题。",
"error.message.chain.empty": "机器人尝试发送空消息链,请联系机器人开发者解决问题。", "error.message.chain.empty": "机器人尝试发送空消息链,请联系机器人开发者解决问题。",
@ -15,7 +15,7 @@
"tos.warning": "警告:\n根据服务条款你已违反我们的行为准则。", "tos.warning": "警告:\n根据服务条款你已违反我们的行为准则。",
"tos.reason": "具体原因:", "tos.reason": "具体原因:",
"tos.warning.count": "这是对你的第 ${current_warns} 次警告。如超过 5 次警告,我们将会把你的账户加入黑名单。", "tos.warning.count": "这是对你的第 ${current_warns} 次警告。如超过 5 次警告,我们将会把你的账户加入黑名单。",
"tos.warning.appeal": "如果你有任何异议,请至 https://github.com/Teahouse-Studios/bot/issues/new/choose 发起 Issue。", "tos.warning.appeal": "如果你有任何异议,请至 ${issue_url} 发起 Issue。",
"tos.warning.last": "这是对你的最后一次警告。", "tos.warning.last": "这是对你的最后一次警告。",
"parser.command.running.prompt": "当前有命令正在执行,请稍后再试。", "parser.command.running.prompt": "当前有命令正在执行,请稍后再试。",
"parser.command.running.prompt2": "先前的命令正在执行中。", "parser.command.running.prompt2": "先前的命令正在执行中。",

View file

@ -6,6 +6,8 @@ from modules.wiki.utils.dbutils import WikiTargetInfo
from modules.wiki.utils.wikilib import WikiLib from modules.wiki.utils.wikilib import WikiLib
from .wiki import wiki from .wiki import wiki
from config import Config
@wiki.handle('set <WikiUrl> {设置起始查询Wiki}', required_admin=True) @wiki.handle('set <WikiUrl> {设置起始查询Wiki}', required_admin=True)
async def set_start_wiki(msg: Bot.MessageSession): async def set_start_wiki(msg: Bot.MessageSession):
@ -17,9 +19,9 @@ async def set_start_wiki(msg: Bot.MessageSession):
if result: if result:
await msg.finish( await msg.finish(
f'成功添加起始Wiki{check.value.name}' + ('\n' + check.message if check.message != '' else '') + f'成功添加起始Wiki{check.value.name}' + ('\n' + check.message if check.message != '' else '') +
('\n注意此Wiki当前没有加入本机器人的白名单列表中查询此Wiki时将会对返回内容进行一些限制。\n' (('\n注意此Wiki当前没有加入本机器人的白名单列表中查询此Wiki时将会对返回内容进行一些限制。\n'
'如需取消限制,请在此处申请白名单:\n' '如需取消限制,请在此处申请白名单:\n' + Config("wiki_whitelist_url"))
'https://s.wd-ljt.com/botwhitelist' if not check.value.in_allowlist else '')) if not check.value.in_allowlist else ''))
else: else:
await msg.finish(f'错误:{check.value.name}处于黑名单中。') await msg.finish(f'错误:{check.value.name}处于黑名单中。')
else: else:
@ -39,9 +41,9 @@ async def _(msg: Bot.MessageSession):
result = target.config_interwikis(iw, check.value.api, let_it=True) result = target.config_interwikis(iw, check.value.api, let_it=True)
if result: if result:
await msg.finish(f'成功添加自定义Interwiki\n{iw} -> {check.value.name}' + await msg.finish(f'成功添加自定义Interwiki\n{iw} -> {check.value.name}' +
('\n注意此Wiki当前没有加入本机器人的白名单列表中查询此Wiki时将会对返回内容进行一些限制。\n' (('\n注意此Wiki当前没有加入本机器人的白名单列表中查询此Wiki时将会对返回内容进行一些限制。\n'
'如需取消限制,请在此处申请白名单:\n' '如需取消限制,请在此处申请白名单:\n' + Config("wiki_whitelist_url"))
'https://s.wd-ljt.com/botwhitelist' if not check.value.in_allowlist else '')) if not check.value.in_allowlist else ''))
else: else:
await msg.finish(f'错误:{check.value.name}处于黑名单中。') await msg.finish(f'错误:{check.value.name}处于黑名单中。')
else: else: