Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upstream #123

Merged
merged 54 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
c8074c8
Create main.yml
DoroWolf Dec 3, 2024
448dd0f
Rename main.yml to sync_ab_to_abc.yml
DoroWolf Dec 3, 2024
c7f4d9a
Rename sync_ab_to_abc.yml to sync-ab-to-abc.yml
DoroWolf Dec 3, 2024
de9d5da
Delete .github/workflows/binary-build.yml
DoroWolf Dec 3, 2024
5dc0ee0
revert
DoroWolf Dec 3, 2024
b52bbaf
Delete .github/workflows/sync-ab-to-abc.yml
DoroWolf Dec 3, 2024
4f97bfb
update
DoroWolf Dec 4, 2024
3249abf
u
DoroWolf Dec 4, 2024
4bec9bd
u
DoroWolf Dec 5, 2024
ea94d1d
u
DoroWolf Dec 5, 2024
db3f75b
Update mapping.py
DoroWolf Dec 5, 2024
810f840
u
OasisAkari Dec 5, 2024
ab39adc
u
OasisAkari Dec 5, 2024
a114620
u
OasisAkari Dec 5, 2024
b03bcc6
1111
OasisAkari Dec 5, 2024
1bf027d
move2cache
DoroWolf Dec 5, 2024
04a0efd
Merge branch 'master' of https://github.com/Teahouse-Studios/akari-bot
DoroWolf Dec 5, 2024
0e1d094
fix
DoroWolf Dec 5, 2024
ae420a2
fix
DoroWolf Dec 5, 2024
bd6825f
u
OasisAkari Dec 5, 2024
7dbc7f4
update
DoroWolf Dec 5, 2024
169116a
Merge branch 'master' of https://github.com/Teahouse-Studios/akari-bot
DoroWolf Dec 5, 2024
eb0a6dc
Update wikilib.py
DoroWolf Dec 5, 2024
ed024b7
Update wikilib.py
DoroWolf Dec 6, 2024
ad9f41a
Update web_render.py
OasisAkari Dec 6, 2024
412ae00
fix wordle
DoroWolf Dec 7, 2024
2f88492
u
DoroWolf Dec 7, 2024
09bab96
fix wordle
DoroWolf Dec 7, 2024
c423afa
Merge branch 'master' of https://github.com/Teahouse-Studios/akari-bot
DoroWolf Dec 7, 2024
09d3010
add documents
DoroWolf Dec 7, 2024
3a34b6a
add documents
DoroWolf Dec 7, 2024
fa8dddf
Update web_render.py
DoroWolf Dec 7, 2024
2ac9578
Update __init__.py
OasisAkari Dec 7, 2024
220441f
Update __init__.py
OasisAkari Dec 7, 2024
ad59def
u
OasisAkari Dec 8, 2024
9f0df4d
u
OasisAkari Dec 8, 2024
b600f8f
Update message.py
OasisAkari Dec 8, 2024
b2e7c98
Update message.py
OasisAkari Dec 8, 2024
cc84bd1
update
DoroWolf Dec 8, 2024
c41d2a3
Merge branch 'master' of https://github.com/Teahouse-Studios/akari-bot
DoroWolf Dec 8, 2024
b9b4c18
update
DoroWolf Dec 8, 2024
cd2b33f
Update bot.py
OasisAkari Dec 8, 2024
4a64562
Update bot.py
OasisAkari Dec 8, 2024
0f5a6a4
U
OasisAkari Dec 8, 2024
72ac16b
U
OasisAkari Dec 8, 2024
c519e10
Update bot.py
OasisAkari Dec 8, 2024
25dc602
update
DoroWolf Dec 8, 2024
c4e0430
add qqbot group recall
DoroWolf Dec 8, 2024
8ba58de
u
OasisAkari Dec 8, 2024
be61e34
u
OasisAkari Dec 8, 2024
f2b26d5
Merge branch 'master' of https://github.com/Teahouse-Studios/akari-bot
OasisAkari Dec 8, 2024
4ec9bc1
Update image_table.py
OasisAkari Dec 9, 2024
353823f
Update image_table.py
OasisAkari Dec 9, 2024
79b8f4b
Merge branch 'master' into upstream
DoroWolf Dec 12, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ test*
cache/*
assets/arc.apk
assets/arcaea
assets/cytoid-avatar/
assets/cytoid-cover/
assets/maimai*
!assets/maimai/mai_utage_info.json
!assets/maimai/mai_grade_info.json
Expand Down
135 changes: 80 additions & 55 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,11 @@
from datetime import datetime
from time import sleep

import core.scripts.config_generate # noqa
from core.config import Config, CFGManager
from core.constants.default import base_superuser_default
from core.constants.path import cache_path
from core.database import BotDBUtil, session, DBVersion
from core.logger import Logger
from core.utils.info import Info
from loguru import logger as loggerFallback


ascii_art = r'''
._. _ .____ ._.
_ _ ____ _
/\ | | (_) | _ \ | |
/ \ | | ____ _ _ __ _ | |_) | ___ | |_
/ /\ \ | |/ / _` | '__| | | _ < / _ \| __|
Expand Down Expand Up @@ -49,20 +44,65 @@ class RestartBot(Exception):


failed_to_start_attempts = {}
disabled_bots = []
processes = []


def init_bot():
import core.scripts.config_generate # noqa
from core.config import Config, CFGManager # noqa
from core.constants.default import base_superuser_default # noqa
from core.database import BotDBUtil, session, DBVersion # noqa
from core.logger import Logger # noqa

query_dbver = session.query(DBVersion).first()
if not query_dbver:
session.add_all([DBVersion(value=str(BotDBUtil.database_version))])
session.commit()
query_dbver = session.query(DBVersion).first()
if (current_ver := int(query_dbver.value)) < (target_ver := BotDBUtil.database_version):
Logger.info(f'Updating database from {current_ver} to {target_ver}...')
from core.database.update import update_database

update_database()
Logger.info('Database updated successfully!')
print(ascii_art)
base_superuser = Config('base_superuser', base_superuser_default, cfg_type=(str, list))
if base_superuser:
if isinstance(base_superuser, str):
base_superuser = [base_superuser]
for bu in base_superuser:
BotDBUtil.SenderInfo(bu).init()
BotDBUtil.SenderInfo(bu).edit('isSuperUser', True)
print(ascii_art)
else:
Logger.warning("The base superuser was not found, please setup it in the config file.")

disabled_bots.clear()
for t in CFGManager.values:
if t.startswith('bot_') and not t.endswith('_secret'):
if 'enable' in CFGManager.values[t][t]:
if not CFGManager.values[t][t]['enable']:
disabled_bots.append(t[4:])


def multiprocess_run_until_complete(func):
p = multiprocessing.Process(
target=func,)
p.start()

while True:
if not p.is_alive():
break
sleep(1)
p.terminate()
p.join()
p.close()


def go(bot_name: str = None, subprocess: bool = False, binary_mode: bool = False):
from core.logger import Logger # noqa
from core.utils.info import Info # noqa

Logger.info(f"[{bot_name}] Here we go!")
Info.subprocess = subprocess
Info.binary_mode = binary_mode
Expand All @@ -76,41 +116,34 @@ def go(bot_name: str = None, subprocess: bool = False, binary_mode: bool = False
sys.exit(1)


disabled_bots = []
processes = []

for t in CFGManager.values:
if t.startswith('bot_') and not t.endswith('_secret'):
if 'enable' in CFGManager.values[t][t]:
if not CFGManager.values[t][t]['enable']:
disabled_bots.append(t[4:])


def restart_process(bot_name: str):
if bot_name not in failed_to_start_attempts or datetime.now(
).timestamp() - failed_to_start_attempts[bot_name]['timestamp'] > 60:
failed_to_start_attempts[bot_name] = {}
failed_to_start_attempts[bot_name]['count'] = 0
def run_bot():
from core.constants.path import cache_path # noqa
from core.config import Config # noqa
from core.logger import Logger # noqa

def restart_process(bot_name: str):
if bot_name not in failed_to_start_attempts or datetime.now(
).timestamp() - failed_to_start_attempts[bot_name]['timestamp'] > 60:
failed_to_start_attempts[bot_name] = {}
failed_to_start_attempts[bot_name]['count'] = 0
failed_to_start_attempts[bot_name]['timestamp'] = datetime.now().timestamp()
failed_to_start_attempts[bot_name]['count'] += 1
failed_to_start_attempts[bot_name]['timestamp'] = datetime.now().timestamp()
failed_to_start_attempts[bot_name]['count'] += 1
failed_to_start_attempts[bot_name]['timestamp'] = datetime.now().timestamp()
if failed_to_start_attempts[bot_name]['count'] >= 3:
Logger.error(f'Bot {bot_name} failed to start 3 times, abort to restart, please check the log.')
return

Logger.warning(f'Restarting bot {bot_name}...')
p = multiprocessing.Process(
target=go,
args=(
bot_name,
True,
bool(not sys.argv[0].endswith('.py'))),
name=bot_name)
p.start()
processes.append(p)
if failed_to_start_attempts[bot_name]['count'] >= 3:
Logger.error(f'Bot {bot_name} failed to start 3 times, abort to restart, please check the log.')
return

Logger.warning(f'Restarting bot {bot_name}...')
p = multiprocessing.Process(
target=go,
args=(
bot_name,
True,
bool(not sys.argv[0].endswith('.py'))),
name=bot_name)
p.start()
processes.append(p)

def run_bot():
if os.path.exists(cache_path):
shutil.rmtree(cache_path)
os.makedirs(cache_path, exist_ok=True)
Expand Down Expand Up @@ -153,45 +186,37 @@ def run_bot():
processes.remove(p)
p.terminate()
p.join()
p.close()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

检查 p.close() 的调用位置

第 189 行的 p.close() 调用可能位于错误的位置。确保在正确的位置调用 p.close(),以便在任何情况下都能正确释放子进程资源。

restart_process(p.name)
break

if not processes:
break
sleep(1)
Logger.critical('All bots exited unexpectedly, please check the output.')


if __name__ == '__main__':
query_dbver = session.query(DBVersion).first()
if not query_dbver:
session.add_all([DBVersion(value=str(BotDBUtil.database_version))])
session.commit()
query_dbver = session.query(DBVersion).first()
if (current_ver := int(query_dbver.value)) < (target_ver := BotDBUtil.database_version):
Logger.info(f'Updating database from {current_ver} to {target_ver}...')
from core.database.update import update_database

update_database()
Logger.info('Database updated successfully!')
init_bot()
try:
while True:
try:
multiprocess_run_until_complete(init_bot)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

添加 init_bot 的异常处理

在第 203 行,调用了 multiprocess_run_until_complete(init_bot)。如果 init_bot 出现异常,可能导致程序崩溃。建议添加异常处理,捕获并处理可能的异常,提高程序的健壮性。

run_bot() # Process will block here so
Logger.critical('All bots exited unexpectedly, please check the output.')
break
except RestartBot:
for ps in processes:
ps.terminate()
ps.join()
ps.close()
processes.clear()
continue
except Exception:
Logger.critical('An error occurred, please check the output.')
loggerFallback.critical('An error occurred, please check the output.')
traceback.print_exc()
break
except (KeyboardInterrupt, SystemExit):
for ps in processes:
ps.terminate()
ps.join()
ps.close()
processes.clear()
17 changes: 11 additions & 6 deletions bots/qqbot/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,16 @@

class FinishedSession(FinishedSessionT):
async def delete(self):
if self.session.target.target_from == target_guild_prefix:
try:
from bots.qqbot.bot import client # noqa
try:
from bots.qqbot.bot import client # noqa
if self.session.target.target_from == target_guild_prefix:
for x in self.message_id:
await client.api.recall_message(channel_id=self.session.target.target_id.split('|')[-1], message_id=x, hidetip=True)
except Exception:
Logger.error(traceback.format_exc())
elif self.session.target.target_from == target_group_prefix:
for x in self.message_id:
await client.api.recall_group_message(group_openid=self.session.target.target_id.split('|')[-1], message_id=x)
except Exception:
Logger.error(traceback.format_exc())


class MessageSession(MessageSessionT):
Expand Down Expand Up @@ -226,6 +229,8 @@ async def delete(self):
except Exception:
Logger.error(traceback.format_exc())
return False
else:
return False

sendMessage = send_message
asDisplay = as_display
Expand Down Expand Up @@ -253,7 +258,7 @@ async def __aexit__(self, exc_type, exc_val, exc_tb):
class FetchedSession(Bot.FetchedSession):

async def send_direct_message(self, message_chain, disable_secret_check=False, enable_parse_message=True, enable_split_image=True):
from bots.qqbot.bot import client
from bots.qqbot.bot import client # noqa
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

解决可能的未定义变量问题

在第261行,从 bots.qqbot.bot 导入 client。但是根据静态分析提示,target_guild_prefixtarget_group_prefix 可能未定义或从星号导入。请确保这些变量已在当前作用域中正确定义,避免运行时错误。

if self.target.target_from == target_guild_prefix:
self.session.message = Message(api=client.api, event_id=None, data={
"channel_id": self.target.target_id.split('|')[-1]})
Expand Down
6 changes: 5 additions & 1 deletion core/builtins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Bot:
ModuleHookContext = ModuleHookContext
ExecutionLockList = ExecutionLockList
Info = Info
Temp = Temp

@staticmethod
async def send_message(target: Union[FetchedSession, MessageSession, str],
Expand All @@ -37,7 +38,10 @@ async def send_message(target: Union[FetchedSession, MessageSession, str],
if isinstance(msg, list):
msg = MessageChain(msg)
Logger.info(target.__dict__)
await target.send_direct_message(msg, disable_secret_check, enable_split_image)
await target.send_direct_message(message_chain=msg,
disable_secret_check=disable_secret_check,
enable_parse_message=enable_parse_message,
enable_split_image=enable_split_image)

@staticmethod
async def fetch_target(target: str):
Expand Down
Loading
Loading