Skip to content

Commit

Permalink
update match_kecode & i18n_code
Browse files Browse the repository at this point in the history
  • Loading branch information
DoroWolf committed Jan 30, 2025
1 parent d8916b0 commit 160775e
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 44 deletions.
64 changes: 36 additions & 28 deletions core/builtins/message/chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@

from core.builtins.utils import Secret
from core.logger import Logger

from core.utils.http import url_pattern

from cattrs import structure, unstructure
Expand Down Expand Up @@ -178,24 +177,7 @@ def as_sendable(self, msg: MessageSession = None, embed: bool = True) -> list:
elif isinstance(x, PlainElement):
if x.text != "":
if msg:
pattern = r'\[i18n:([^\s,\]]+)(?:,([^\]]+))?\]'

def match_i18ncode(match):
key = html.unescape(match.group(1))
kwargs = {}

if match.group(2):
params = match.group(2).split(',')
for param in params:
if '=' in param:
k, v = param.split('=', 1)
kwargs[html.unescape(k.strip())] = html.unescape(v.strip())

t_value = msg.locale.t(key, **kwargs) # 翻译 key
return t_value if isinstance(t_value, str) else match.group(0)

x.text = re.sub(pattern, match_i18ncode, x.text)

x.text = match_i18ncode(msg, x.text)
value.append(x)
else:
value.append(
Expand Down Expand Up @@ -325,22 +307,22 @@ def match_kecode(text: str) -> List[Union[PlainElement, ImageElement, VoiceEleme
split_all = re.split(r"(\[Ke:.*?])", text)
split_all = [x for x in split_all if x]
elements = []
args = []
params = []

for e in split_all:
match = re.match(r"\[Ke:(.*?)(?:,(.*?))?]", e)
match = re.match(r'\[Ke:([^\s,\]]+)(?:,([^\]]+))?\]', e)
if not match:
if e != "":
elements.append(PlainElement.assign(e))
else:
element_type = match.group(1).lower()

if args:
args = re.split(r",|,.\s", match.group(2))
args = [x for x in args if x]
if match.group(2):
params = match.group(2).split(',')
params = [x for x in params if x]

if element_type == "plain":
for a in args:
for a in params:
ma = re.match(r"(.*?)=(.*)", a)
if ma:
if ma.group(1) == "text":
Expand All @@ -353,7 +335,7 @@ def match_kecode(text: str) -> List[Union[PlainElement, ImageElement, VoiceEleme
a = html.unescape(a)
elements.append(PlainElement.assign(a))
elif element_type == "image":
for a in args:
for a in params:
ma = re.match(r"(.*?)=(.*)", a)
if ma:
img = None
Expand All @@ -372,7 +354,7 @@ def match_kecode(text: str) -> List[Union[PlainElement, ImageElement, VoiceEleme
a = html.unescape(a)
elements.append(ImageElement.assign(a))
elif element_type == "voice":
for a in args:
for a in params:
ma = re.match(r"(.*?)=(.*)", a)
if ma:
if ma.group(1) == "path":
Expand All @@ -388,7 +370,7 @@ def match_kecode(text: str) -> List[Union[PlainElement, ImageElement, VoiceEleme
elif element_type == "i18n":
i18nkey = None
kwargs = {}
for a in args:
for a in params:
ma = re.match(r"(.*?)=(.*)", a)
if ma:
if ma.group(1) == "i18nkey":
Expand All @@ -401,4 +383,30 @@ def match_kecode(text: str) -> List[Union[PlainElement, ImageElement, VoiceEleme
return elements


def match_i18ncode(msg: MessageSession, text: str) -> str:
split_all = re.split(r"(\[I18N:.*?])", text)
split_all = [x for x in split_all if x]
msgs = []
kwargs = {}

for e in split_all:
match = re.match(r'\[I18N:([^\s,\]]+)(?:,([^\]]+))?\]', e)
if not match:
msgs.append(e)
else:
i18nkey = html.unescape(match.group(1))

if match.group(2):
params = match.group(2).split(',')
params = [x for x in params if x]
for a in params:
ma = re.match(r"(.*?)=(.*)", a)
if ma:
kwargs[html.unescape(ma.group(1))] = html.unescape(ma.group(2))
t_value = msg.locale.t(i18nkey, **kwargs)
msgs.append(t_value if isinstance(t_value, str) else match.group(0))

return "".join(msgs)


__all__ = ["MessageChain"]
8 changes: 4 additions & 4 deletions core/dirty_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,17 @@ def parse_data(result: dict, additional_text=None) -> Dict:
if "positions" in itemContext:
for pos in itemContext["positions"]:
filter_words_length = pos["endPos"] - pos["startPos"]
reason = f"[i18n:check.redacted,reason={itemDetail['label']}]"
reason = f"[I18N:check.redacted,reason={itemDetail['label']}]"
content = (content[: pos["startPos"] + _offset] +
reason + content[pos["endPos"] + _offset:])
if additional_text:
content += "\n" + additional_text + "\n"
_offset += len(reason) - filter_words_length
else:
content = f"[i18n:check.redacted,reason={itemDetail['label']}]"
content = f"[I18N:check.redacted,reason={itemDetail['label']}]"
status = False
else:
content = f"[i18n:check.redacted.all,reason={itemDetail['label']}]"
content = f"[I18N:check.redacted.all,reason={itemDetail['label']}]"

if additional_text:
content += "\n" + additional_text + "\n"
Expand Down Expand Up @@ -173,4 +173,4 @@ def rickroll() -> str:
"""
if Config("enable_rickroll", True) and Config("rickroll_msg", cfg_type=str):
return Config("rickroll_msg", cfg_type=str)
return "[i18n:error.message.chain.unsafe]"
return "[I18N:error.message.chain.unsafe]"
4 changes: 2 additions & 2 deletions core/parser/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,7 @@ async def execute_submodule(msg: Bot.MessageSession, command_first_word):
if not timeout and report_targets:
for target in report_targets:
if f := await Bot.FetchTarget.fetch_target(target):
await f.send_direct_message(f"[i18n:error.message.report,module={msg.trigger_msg}]\n{tb}".strip(), enable_parse_message=False, disable_secret_check=True)
await f.send_direct_message(f"[I18N:error.message.report,module={msg.trigger_msg}]\n{tb}".strip(), enable_parse_message=False, disable_secret_check=True)
if command_first_word in current_unloaded_modules:
await msg.send_message(
msg.locale.t('parser.module.unloaded', module=command_first_word))
Expand Down Expand Up @@ -652,7 +652,7 @@ async def execute_submodule(msg: Bot.MessageSession, command_first_word):
if not timeout and report_targets:
for target in report_targets:
if f := await Bot.FetchTarget.fetch_target(target):
await f.send_direct_message(f"[i18n:error.message.report,module={msg.trigger_msg}]\n{tb}".strip(), enable_parse_message=False, disable_secret_check=True)
await f.send_direct_message(f"[I18N:error.message.report,module={msg.trigger_msg}]\n{tb}".strip(), enable_parse_message=False, disable_secret_check=True)
finally:
ExecutionLockList.remove(msg)

Expand Down
2 changes: 1 addition & 1 deletion core/queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ async def check_job_queue():
try:
for target in report_targets:
if ft := await Bot.FetchTarget.fetch_target(target):
await ft.send_direct_message(f"[i18n:error.message.report,module={tsk.action}]\n{f}".strip(),
await ft.send_direct_message(f"[I18N:error.message.report,module={tsk.action}]\n{f}".strip(),
enable_parse_message=False, disable_secret_check=True)
except Exception:
Logger.error(traceback.format_exc())
Expand Down
12 changes: 6 additions & 6 deletions core/tos.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,14 @@ async def warn_user(user: str, count: int = 1):

async def tos_report(sender: str, target: str, reason: str, banned: bool = False):
if report_targets:
warn_template = [f"[i18n:tos.message.report,sender={sender},target={target}]"]
reason = re.sub(r"\{([^}]+)\}", lambda match: f"[i18n:{match.group(1)}]", reason)
warn_template.append("[i18n:tos.message.reason]" + reason)
warn_template = [f"[I18N:tos.message.report,sender={sender},target={target}]"]
reason = re.sub(r"\{([^}]+)\}", lambda match: f"[I18N:{match.group(1)}]", reason)
warn_template.append("[I18N:tos.message.reason]" + reason)
if banned:
action = "[i18n:tos.message.action.blocked]"
action = "[I18N:tos.message.action.blocked]"
else:
action = "[i18n:tos.message.action.warning]"
warn_template.append("[i18n:tos.message.action]" + action)
action = "[I18N:tos.message.action.warning]"
warn_template.append("[I18N:tos.message.action]" + action)

for target_ in report_targets:
if f := await Bot.FetchTarget.fetch_target(target_):
Expand Down
6 changes: 3 additions & 3 deletions modules/core/su_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ async def _(msg: Bot.MessageSession, display_msg: str):

@rse.command()
async def _(msg: Bot.MessageSession):
e = "[i18n:core.message.raise]"
e = "[I18N:core.message.raise]"
raise TestException(e)


Expand All @@ -500,7 +500,7 @@ async def _(msg: Bot.MessageSession, display_msg: str):
async def _(msg: Bot.MessageSession, target: str, post_msg: str):
if not target.startswith(f'{msg.target.client_name}|'):
await msg.finish(msg.locale.t('message.id.invalid.target', target=msg.target.target_from))
post_msg = f"[i18n:core.message.post.prefix] {post_msg}"
post_msg = f"[I18N:core.message.post.prefix] {post_msg}"
session = await Bot.FetchTarget.fetch_target(target)
confirm = await msg.wait_confirm(msg.locale.t("core.message.post.confirm", target=target, post_msg=post_msg), append_instruction=False)
if confirm:
Expand All @@ -512,7 +512,7 @@ async def _(msg: Bot.MessageSession, target: str, post_msg: str):

@post_.command('global <post_msg>')
async def _(msg: Bot.MessageSession, post_msg: str):
post_msg = f"[i18n:core.message.post.prefix] {post_msg}"
post_msg = f"[I18N:core.message.post.prefix] {post_msg}"
confirm = await msg.wait_confirm(msg.locale.t("core.message.post.global.confirm", post_msg=post_msg), append_instruction=False)
if confirm:
await Bot.FetchTarget.post_global_message(post_msg)
Expand Down

0 comments on commit 160775e

Please sign in to comment.