Archived
1
0
Fork 0
This commit is contained in:
yzhh 2024-01-11 21:24:07 +08:00
parent 1660118cc6
commit 92905d4f04
11 changed files with 89 additions and 36 deletions

View file

@ -84,10 +84,10 @@ class FormattedTime:
else: else:
ftime_template.append(msg.locale.t("time.time.nosec.format")) ftime_template.append(msg.locale.t("time.time.nosec.format"))
if self.timezone: if self.timezone:
if self._tz_offset == "+0": if msg._tz_offset == "+0":
ftime_template.append("(UTC)") ftime_template.append("(UTC)")
else: else:
ftime_template.append(f"(UTC{self._tz_offset})") ftime_template.append(f"(UTC{msg._tz_offset})")
else: else:
ftime_template.append('%Y-%m-%d %H:%M:%S') ftime_template.append('%Y-%m-%d %H:%M:%S')
if not msg: if not msg:
@ -102,8 +102,15 @@ class FormattedTime:
return f'FormattedTime(time={self.timestamp})' return f'FormattedTime(time={self.timestamp})'
def to_dict(self): def to_dict(self):
return {'type': 'formatted_time', 'data': {'timestamp': self.timestamp, 'date': self.date, 'iso': self.iso, return {
'time': self.time, 'seconds': self.seconds, 'timezone': self.timezone}} 'type': 'formatted_time',
'data': {
'timestamp': self.timestamp,
'date': self.date,
'iso': self.iso,
'time': self.time,
'seconds': self.seconds,
'timezone': self.timezone}}
class I18NContext: class I18NContext:

View file

@ -14,7 +14,7 @@ bot = Bot.FetchTarget
ca = module('__check_abuse__', required_superuser=True, developers=['OasisAkari']) ca = module('__check_abuse__', required_superuser=True, developers=['OasisAkari'])
@ca.handle(DateTrigger(datetime.now() + timedelta(seconds=10))) @ca.handle(DateTrigger(datetime.now() + timedelta(seconds=20)))
async def _(): async def _():
if bot.name not in ['QQ', 'TEST']: if bot.name not in ['QQ', 'TEST']:
return return

View file

@ -6,6 +6,7 @@ from core.component import module
from core.scheduler import DateTrigger from core.scheduler import DateTrigger
from core.logger import Logger from core.logger import Logger
from core.utils.image_table import image_table_render, ImageTable from core.utils.image_table import image_table_render, ImageTable
from database import BotDBUtil
from modules.wiki.utils.bot import BotAccount, LoginFailed from modules.wiki.utils.bot import BotAccount, LoginFailed
from modules.wiki.utils.dbutils import Audit from modules.wiki.utils.dbutils import Audit
from modules.wiki.utils.wikilib import WikiLib from modules.wiki.utils.wikilib import WikiLib
@ -131,13 +132,13 @@ async def _(msg: Bot.MessageSession):
check = await WikiLib(api_link).check_wiki_available() check = await WikiLib(api_link).check_wiki_available()
if check.available: if check.available:
try: try:
await BotAccount._login(api_link, account, password) login = await BotAccount._login(check.value.api, account, password)
BotAccountDB.add(check.value.api, account, password)
BotAccount.cookies[check.value.api] = login
await msg.finish('Login success')
except LoginFailed as e: except LoginFailed as e:
Logger.error(f'Login failed: {e}') Logger.error(f'Login failed: {e}')
await msg.finish(f'Login failed: {e}') await msg.finish(f'Login failed: {e}')
else:
await msg.finish('Login success')
BotAccountDB.add(api_link, account, password)
else: else:
result = msg.locale.t('wiki.message.error.query') + \ result = msg.locale.t('wiki.message.error.query') + \
('\n' + msg.locale.t('wiki.message.error.info') + check.message if check.message != '' else '') ('\n' + msg.locale.t('wiki.message.error.info') + check.message if check.message != '' else '')
@ -148,10 +149,23 @@ async def _(msg: Bot.MessageSession):
async def _(msg: Bot.MessageSession): async def _(msg: Bot.MessageSession):
api_link = msg.parsed_msg['<apiLink>'] api_link = msg.parsed_msg['<apiLink>']
BotAccountDB.remove(api_link) BotAccountDB.remove(api_link)
await msg.finish('Done') await msg.finish(msg.locale.t("success"))
@aud.handle(DateTrigger(datetime.now() + timedelta(seconds=10))) @aud.handle('bot use')
async def login_bots(): async def _(msg: Bot.MessageSession):
Logger.info('Start login wiki bot account...') target_data = BotDBUtil.TargetInfo(msg)
await BotAccount.login() target_data.edit_option('use_bot_account', True)
await msg.finish(msg.locale.t("success"))
@aud.handle('bot unuse')
async def _(msg: Bot.MessageSession):
target_data = BotDBUtil.TargetInfo(msg)
target_data.edit_option('use_bot_account', False)
await msg.finish(msg.locale.t("success"))
@aud.hook('login_wiki_bots')
async def mcbv_jira_rss(fetch: Bot.FetchTarget, ctx: Bot.ModuleHookContext):
BotAccount.cookies.update(ctx.args['cookies'])

View file

@ -39,6 +39,7 @@
"wiki.message.error.info": "详细信息:", "wiki.message.error.info": "详细信息:",
"wiki.message.error.query": "发生错误:无法查询此 Wiki。", "wiki.message.error.query": "发生错误:无法查询此 Wiki。",
"wiki.message.error.set": "发生错误:无法设置此 Wiki。", "wiki.message.error.set": "发生错误:无法设置此 Wiki。",
"wiki.message.error.fetch_log": "无法获取日志可能是本wiki设置了日志的查看权限。",
"wiki.message.error.unable_to_render_section": "(章节渲染失败,请联系开发者检查原因)", "wiki.message.error.unable_to_render_section": "(章节渲染失败,请联系开发者检查原因)",
"wiki.message.fandom.disable": "已关闭 Fandom 全局 Interwiki 查询。", "wiki.message.fandom.disable": "已关闭 Fandom 全局 Interwiki 查询。",
"wiki.message.fandom.enable": "已开启 Fandom 全局 Interwiki 查询。", "wiki.message.fandom.enable": "已开启 Fandom 全局 Interwiki 查询。",

View file

@ -14,8 +14,8 @@ rc_ = module('rc', developers=['OasisAkari'], recommend_modules='wiki')
@rc_.command(['{{wiki.help.rc}}', @rc_.command(['{{wiki.help.rc}}',
'legacy {{wiki.help.rc.legacy}}'], 'legacy {{wiki.help.rc.legacy}}'],
available_for=['QQ', 'QQ|Group']) available_for=['QQ', 'QQ|Group'])
async def rc_loader(msg: Bot.MessageSession): async def rc_loader(msg: Bot.MessageSession):
start_wiki = WikiTargetInfo(msg).get_start_wiki() start_wiki = WikiTargetInfo(msg).get_start_wiki()
if not start_wiki: if not start_wiki:
@ -35,7 +35,7 @@ async def rc_loader(msg: Bot.MessageSession):
@rc_.command('{{wiki.help.rc}}', @rc_.command('{{wiki.help.rc}}',
exclude_from=['QQ', 'QQ|Group']) exclude_from=['QQ', 'QQ|Group'])
async def rc_loader(msg: Bot.MessageSession): async def rc_loader(msg: Bot.MessageSession):
start_wiki = WikiTargetInfo(msg).get_start_wiki() start_wiki = WikiTargetInfo(msg).get_start_wiki()
if not start_wiki: if not start_wiki:
@ -48,7 +48,7 @@ a = module('ab', developers=['OasisAkari'], recommend_modules='wiki')
@a.command(['{{wiki.help.ab}}', @a.command(['{{wiki.help.ab}}',
'legacy {{wiki.help.ab.legacy}}'], 'legacy {{wiki.help.ab.legacy}}'],
available_for=['QQ', 'QQ|Group']) available_for=['QQ', 'QQ|Group'])
async def ab_loader(msg: Bot.MessageSession): async def ab_loader(msg: Bot.MessageSession):
start_wiki = WikiTargetInfo(msg).get_start_wiki() start_wiki = WikiTargetInfo(msg).get_start_wiki()
@ -64,8 +64,12 @@ async def ab_loader(msg: Bot.MessageSession):
traceback.print_exc() traceback.print_exc()
await msg.send_message(msg.locale.t('wiki.message.rollback')) await msg.send_message(msg.locale.t('wiki.message.rollback'))
if legacy: if legacy:
res = await ab(msg, start_wiki) try:
await msg.finish(res) res = await ab(msg, start_wiki)
await msg.finish(res)
except Exception:
traceback.print_exc()
await msg.send_message(msg.locale.t('wiki.message.error.fetch_log'))
@a.command('{{wiki.help.ab}}', @a.command('{{wiki.help.ab}}',
@ -74,8 +78,12 @@ async def ab_loader(msg: Bot.MessageSession):
start_wiki = WikiTargetInfo(msg).get_start_wiki() start_wiki = WikiTargetInfo(msg).get_start_wiki()
if not start_wiki: if not start_wiki:
await msg.finish(msg.locale.t('wiki.message.not_set')) await msg.finish(msg.locale.t('wiki.message.not_set'))
res = await ab(msg, start_wiki) try:
await msg.finish(res) res = await ab(msg, start_wiki)
await msg.finish(res)
except Exception:
traceback.print_exc()
await msg.send_message(msg.locale.t('wiki.message.error.fetch_log'))
n = module('newbie', developers=['OasisAkari'], recommend_modules='wiki') n = module('newbie', developers=['OasisAkari'], recommend_modules='wiki')
@ -86,5 +94,9 @@ async def newbie_loader(msg: Bot.MessageSession):
start_wiki = WikiTargetInfo(msg).get_start_wiki() start_wiki = WikiTargetInfo(msg).get_start_wiki()
if not start_wiki: if not start_wiki:
await msg.finish(msg.locale.t('wiki.message.not_set')) await msg.finish(msg.locale.t('wiki.message.not_set'))
res = await newbie(msg, start_wiki) try:
await msg.finish(res) res = await newbie(msg, start_wiki)
await msg.finish(res)
except Exception:
traceback.print_exc()
await msg.send_message(msg.locale.t('wiki.message.error.fetch_log'))

View file

@ -6,7 +6,8 @@ from modules.wiki.utils.wikilib import WikiLib
async def ab(msg: Bot.MessageSession, wiki_url): async def ab(msg: Bot.MessageSession, wiki_url):
wiki = WikiLib(wiki_url) wiki = WikiLib(wiki_url)
query = await wiki.get_json(action='query', list='abuselog', aflprop='user|title|action|result|filter|timestamp') query = await wiki.get_json(action='query', list='abuselog', aflprop='user|title|action|result|filter|timestamp',
_no_login=not msg.options.get("use_bot_account", False))
pageurl = wiki.wiki_info.articlepath.replace('$1', 'Special:AbuseLog') pageurl = wiki.wiki_info.articlepath.replace('$1', 'Special:AbuseLog')
d = [] d = []
for x in query['query']['abuselog'][:5]: for x in query['query']['abuselog'][:5]:

View file

@ -10,7 +10,7 @@ async def ab_qq(msg: MessageSession, wiki_url):
wiki = WikiLib(wiki_url) wiki = WikiLib(wiki_url)
qq_account = Config("qq_account") qq_account = Config("qq_account")
query = await wiki.get_json(action='query', list='abuselog', aflprop='user|title|action|result|filter|timestamp', query = await wiki.get_json(action='query', list='abuselog', aflprop='user|title|action|result|filter|timestamp',
afllimit=99) afllimit=99, _no_login=not msg.options.get("use_bot_account", False))
pageurl = wiki.wiki_info.articlepath.replace("$1", 'Special:AbuseLog') pageurl = wiki.wiki_info.articlepath.replace("$1", 'Special:AbuseLog')
nodelist = [{ nodelist = [{
"type": "node", "type": "node",

View file

@ -6,7 +6,8 @@ from modules.wiki.utils.wikilib import WikiLib
async def rc(msg: Bot.MessageSession, wiki_url): async def rc(msg: Bot.MessageSession, wiki_url):
wiki = WikiLib(wiki_url) wiki = WikiLib(wiki_url)
query = await wiki.get_json(action='query', list='recentchanges', rcprop='title|user|timestamp', rctype='edit') query = await wiki.get_json(action='query', list='recentchanges', rcprop='title|user|timestamp', rctype='edit',
_no_login=not msg.options.get("use_bot_account", False))
pageurl = wiki.wiki_info.articlepath.replace('$1', 'Special:RecentChanges') pageurl = wiki.wiki_info.articlepath.replace('$1', 'Special:RecentChanges')
d = [] d = []
for x in query['query']['recentchanges'][:10]: for x in query['query']['recentchanges'][:10]:

View file

@ -15,7 +15,8 @@ async def rc_qq(msg: MessageSession, wiki_url):
query = await wiki.get_json(action='query', list='recentchanges', query = await wiki.get_json(action='query', list='recentchanges',
rcprop='title|user|timestamp|loginfo|comment|redirect|flags|sizes|ids', rcprop='title|user|timestamp|loginfo|comment|redirect|flags|sizes|ids',
rclimit=99, rclimit=99,
rctype='edit|new|log' rctype='edit|new|log',
_no_login=not msg.options.get("use_bot_account", False)
) )
pageurl = wiki.wiki_info.articlepath pageurl = wiki.wiki_info.articlepath

View file

@ -155,7 +155,10 @@ class WikiLib:
self.headers = headers self.headers = headers
self.locale = Locale(locale) self.locale = Locale(locale)
async def get_json_from_api(self, api, **kwargs) -> dict: async def get_json_from_api(self, api, _no_login=False, **kwargs) -> dict:
cookies = None
if api in BotAccount.cookies and not _no_login:
cookies = BotAccount.cookies[api]
if api in redirect_list: if api in redirect_list:
api = redirect_list[api] api = redirect_list[api]
if kwargs: if kwargs:
@ -171,9 +174,7 @@ class WikiLib:
api = (web_render_local if use_local else web_render) + 'source?url=' + urllib.parse.quote(api) api = (web_render_local if use_local else web_render) + 'source?url=' + urllib.parse.quote(api)
request_local = True request_local = True
break break
cookies = None
if api in BotAccount.cookies:
cookies = BotAccount.cookies[api]
try: try:
return await get_url(api, status_code=200, headers=self.headers, fmt="json", request_private_ip=request_local, return await get_url(api, status_code=200, headers=self.headers, fmt="json", request_private_ip=request_local,
cookies=cookies) cookies=cookies)
@ -309,10 +310,10 @@ class WikiLib:
else: else:
raise InvalidWikiError(wiki_info.message if wiki_info.message != '' else '') raise InvalidWikiError(wiki_info.message if wiki_info.message != '' else '')
async def get_json(self, **kwargs) -> dict: async def get_json(self, _no_login=False, **kwargs) -> dict:
await self.fixup_wiki_info() await self.fixup_wiki_info()
api = self.wiki_info.api api = self.wiki_info.api
return await self.get_json_from_api(api, **kwargs) return await self.get_json_from_api(api, _no_login=_no_login, **kwargs)
@staticmethod @staticmethod
def parse_text(text): def parse_text(text):

15
schedulers/wiki_bot.py Normal file
View file

@ -0,0 +1,15 @@
from datetime import datetime, timedelta
from core.builtins import Bot
from core.logger import Logger
from core.queue import JobQueue
from core.scheduler import DateTrigger, Scheduler
from modules.wiki import BotAccount
@Scheduler.scheduled_job(DateTrigger(datetime.now() + timedelta(seconds=10)))
async def login_bots():
Logger.info('Start login wiki bot account...')
await BotAccount.login()
await JobQueue.trigger_hook_all('login_wiki_bots', cookies=BotAccount.cookies)
Logger.info('Login wiki bot account done')