Skip to content

Commit

Permalink
Merge branch 'Teahouse-Studios:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
ZoruaFox authored Jan 12, 2025
2 parents 3221b5c + 039b0d8 commit e34025c
Show file tree
Hide file tree
Showing 10 changed files with 51 additions and 45 deletions.
3 changes: 2 additions & 1 deletion bots/aiocqhttp/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ async def message_handler(event: Event):
if event.message[0]["type"] == "at":
if event.message[0]["data"]["qq"] == str(qq_account):
event.message = event.message[1:]
if not event.message:
if not event.message or \
event.message[0]["type"] == "text" and event.message[0]["data"]["text"] == ' ':
event.message = [{"type": "text", "data": {"text": f"{command_prefix[0]}help"}}]
prefix = command_prefix
else:
Expand Down
8 changes: 4 additions & 4 deletions bots/web/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import sys
import time
from multiprocessing import Process
import uvicorn

sys.path.append(os.getcwd())

Expand All @@ -20,9 +21,8 @@


def run_fastapi():
import uvicorn
from bots.web.api import app as fastapi_app
while True:
from bots.web.api import app as fastapi_app # noqa: E402
Info.client_name = client_name
uvicorn.run(fastapi_app, port=API_PORT, log_level="info")
Logger.error("API Server crashed, is the port occupied?")
Expand All @@ -31,8 +31,8 @@ def run_fastapi():


def run_flask():
if os.path.exists(webui_path):
from bots.web.webui import app as flask_app, generate_config
from bots.web.webui import generate_config, app as flask_app # noqa: E402
if os.path.exists(os.path.join(webui_path, "index.html")):
generate_config()
Logger.info(f"Visit AkariBot WebUI: http://127.0.0.1:{WEBUI_PORT}")
flask_app.run(port=WEBUI_PORT)
Expand Down
9 changes: 4 additions & 5 deletions bots/web/webui.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import os
import sys
import time
from flask import Flask, redirect, send_from_directory, url_for
from urllib.parse import urlparse

Expand All @@ -14,11 +13,11 @@
from core.logger import Logger # noqa: E402


if os.path.exists(webui_path):
if os.path.exists(os.path.join(webui_path, "index.html")):

def generate_config():
webui_config_path = os.path.join(webui_path, "config.json")
if os.path.exists(webui_config_path):
if os.path.exists(webui_path):
with open(webui_config_path, "wb") as f:
f.write(json.dumps({"api_url": f"http://127.0.0.1:{API_PORT}"}))

Expand All @@ -41,7 +40,6 @@ def static_files(path):
@app.route("/api/<path:path>")
def api_redirect(path=None):
if path:
from urllib.parse import urlparse
parsed_path = urlparse(path)
if not parsed_path.netloc and not parsed_path.scheme:
return redirect(f"http://127.0.0.1:{API_PORT}/api/{path}")
Expand All @@ -50,7 +48,8 @@ def api_redirect(path=None):
else:
return redirect(f"http://127.0.0.1:{API_PORT}/api")

if __name__ == "__main__" and Config("enable", True, table_name="bot_web") and os.path.exists(webui_path):
if __name__ == "__main__" and Config("enable", True, table_name="bot_web") and \
os.path.exists(os.path.join(webui_path, "index.html")):
generate_config()
Logger.info(f"Visit AkariBot WebUI: http://127.0.0.1:{WEBUI_PORT}")
app.run(port=WEBUI_PORT)
Expand Down
2 changes: 1 addition & 1 deletion core/builtins/message/elements.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ def assign(
)
):
error_message += "\n" + locale.t(
"error.prompt.address", url=str(report_url)
"error.prompt.address", url=str(report_url.url)
)

return deepcopy(cls(error_message))
Expand Down
6 changes: 4 additions & 2 deletions core/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,9 @@ def regex(
available_for: Union[str, list, tuple] = "*",
exclude_from: Union[str, list, tuple] = "",
load: bool = True,
show_typing: bool = True,
logging: bool = True,
show_typing: bool = True,
text_only: bool = True,
):
def decorator(function):
ModulesManager.bind_to_module(
Expand All @@ -89,8 +90,9 @@ def decorator(function):
available_for=available_for,
exclude_from=exclude_from,
load=load,
show_typing=show_typing,
logging=logging,
show_typing=show_typing,
text_only=text_only,
),
)
return function
Expand Down
2 changes: 1 addition & 1 deletion core/parser/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,7 @@ async def execute_submodule(msg: Bot.MessageSession, command_first_word):
try:
matched = False
matched_hash = 0
trigger_msg = msg.as_display(msg.trigger_msg)
trigger_msg = msg.as_display(text_only=rfunc.text_only)
if rfunc.mode.upper() in ['M', 'MATCH']:
msg.matched_msg = re.match(rfunc.pattern, trigger_msg, flags=rfunc.flags)
if msg.matched_msg:
Expand Down
3 changes: 2 additions & 1 deletion core/types/module/component_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ class RegexMeta(ModuleMeta):
exclude_from: list = field(default=[], converter=convert2lst)
flags: re.RegexFlag = 0
load: bool = True
show_typing: bool = True
logging: bool = True
show_typing: bool = True
text_only: bool = True


@define
Expand Down
3 changes: 2 additions & 1 deletion modules/bilibili/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,10 @@ async def _(msg: Bot.MessageSession):
await get_video_info(msg, query)


@bili.regex(r"\b(?:http[s]?://)?(?:bili(?:22|33|2233)\.cn|b23\.tv)/([A-Za-z0-9]{7})(?:/.*?|)\b",
@bili.regex(r"(?:http[s]?://)?(?:bili(?:22|33|2233)\.cn|b23\.tv)/([A-Za-z0-9]{7})(?:/.*?|)",
mode="A",
desc="{bilibili.help.regex.url}",
text_only=False,
)
async def _(msg: Bot.MessageSession):
matched = msg.matched_msg[:5]
Expand Down
10 changes: 9 additions & 1 deletion modules/core/su_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,15 @@ async def _(msg: Bot.MessageSession):
echo = module('echo', required_superuser=True, base=True, doc=True)


@echo.command('<display_msg>')
@echo.command()
async def _(msg: Bot.MessageSession):
dis = await msg.wait_next_message()
if dis:
dis = dis.as_display()
await msg.finish(dis, enable_parse_message=False)


@echo.command('[<display_msg>]')
async def _(msg: Bot.MessageSession, dis: Param("<display_msg>", str)):
await msg.finish(dis, enable_parse_message=False)

Expand Down
50 changes: 22 additions & 28 deletions modules/mcserver/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,25 @@
async def query_java_server(
msg: Bot.MessageSession, address: str, raw: bool = False, showplayer: bool = False
) -> str:
match_object = re.match(r"(.*)[\s:](\d*)", address, re.M | re.I)
serip = match_object.group(1) if match_object else address
port = match_object.group(2)if match_object else 25565
servers = []
query_msg = []

try:
server = JavaServer.lookup(f"{serip}:{port}")
server = JavaServer.lookup(address)
status = await server.async_status()
Logger.debug(str(status))
servers.append("[JE]")
query_msg.append("[JE]")

description = status.description
if isinstance(description, str):
servers.append(description)
query_msg.append(description)
elif isinstance(description, dict):
servers.append(description.get("text", ""))
servers.append(
query_msg.append(description.get("text", ""))
query_msg.append(
"".join(extra.get("text", "") for extra in description.get("extra", []))
)

onlinesplayer = f"{msg.locale.t('server.message.player')}{status.players.online} / {status.players.max}"
servers.append(onlinesplayer)
query_msg.append(onlinesplayer)

if showplayer:
playerlist = (
Expand All @@ -43,55 +40,52 @@ async def query_java_server(
players_text = (
"\n".join(playerlist) if playerlist else msg.locale.t("message.none")
)
servers.append(
query_msg.append(
msg.locale.t("server.message.player.current") + "\n" + players_text
)

if hasattr(status, "version") and hasattr(status.version, "name"):
servers.append(msg.locale.t("server.message.version") + status.version.name)
query_msg.append(msg.locale.t("server.message.version") + status.version.name)

servers.append(f"{serip}:{port}")
query_msg.append(address)

except Exception:
if Config("debug", False):
Logger.error(traceback.format_exc())
return ""

if raw:
return "\n".join(servers)
return re.sub(r"§\w", "", "\n".join(servers))
return "\n".join(query_msg)
return re.sub(r"§\w", "", "\n".join(query_msg))


async def query_bedrock_server(msg, address, raw=False):
match_object = re.match(r"(.*)[\s:](\d*)", address, re.M | re.I)
serip = match_object.group(1) if match_object else address
port = match_object.group(2) if match_object else 19132
servers = []
query_msg = []

try:
server = BedrockServer.lookup(f"{serip}:{port}")
server = BedrockServer.lookup(address)
status = await server.async_status()
Logger.debug(str(status))
servers.append("[BE]")
servers.append(status.motd.raw)
query_msg.append("[BE]")
query_msg.append(status.motd.raw)

player_count = f"{msg.locale.t('server.message.player')}{status.players_online} / {status.players_max}"
servers.append(player_count)
query_msg.append(player_count)

if hasattr(status, "version") and hasattr(status.version, "name"):
servers.append(msg.locale.t("server.message.version") + status.version.name)
query_msg.append(msg.locale.t("server.message.version") + status.version.name)

if hasattr(status, "gamemode"):
game_mode = msg.locale.t("server.message.gamemode") + status.gamemode
servers.append(game_mode)
query_msg.append(game_mode)

servers.append(f"{serip}:{port}")
query_msg.append(address)

except Exception:
if Config("debug", False):
Logger.error(traceback.format_exc())
return ""

if raw:
return "\n".join(servers)
return re.sub(r"§\w", "", "\n".join(servers))
return "\n".join(query_msg)
return re.sub(r"§\w", "", "\n".join(query_msg))

0 comments on commit e34025c

Please sign in to comment.