Skip to content

Commit

Permalink
fix regex
Browse files Browse the repository at this point in the history
  • Loading branch information
DoroWolf committed Dec 28, 2024
1 parent ff393ee commit b6e330c
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 89 deletions.
4 changes: 3 additions & 1 deletion core/builtins/message/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import asyncio
from datetime import datetime, UTC as datetimeUTC
from typing import Any, Coroutine, Dict, List, Optional, Union
from re import Match
from typing import Any, Coroutine, Dict, List, Optional, Tuple, Union

from core.builtins.message.chain import *
from core.builtins.message.elements import MessageElement
Expand Down Expand Up @@ -195,6 +196,7 @@ def __init__(self, target: MsgInfo, session: Session):
self.session = session
self.sent: List[MessageChain] = []
self.trigger_msg: Optional[str] = None
self.matched_msg: Optional[Union[Match[str], Tuple[Any]]] = None
self.parsed_msg: Optional[dict] = None
self.prefixes: List[str] = []
self.data = exports.get("BotDBUtil").TargetInfo(self.target.target_id)
Expand Down
6 changes: 3 additions & 3 deletions core/parser/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,16 +539,16 @@ async def execute_submodule(msg: Bot.MessageSession, command_first_word):
for rfunc in regex_module.regex_list.set: # 遍历正则模块的表达式
time_start = datetime.now()
try:
msg.matched_msg = False
matched = False
matched_hash = 0
trigger_msg = msg.as_display(msg.trigger_msg)
if rfunc.mode.upper() in ['M', 'MATCH']:
msg.matched_msg = re.match(rfunc.pattern, msg.trigger_msg, flags=rfunc.flags)
msg.matched_msg = re.match(rfunc.pattern, trigger_msg, flags=rfunc.flags)
if msg.matched_msg:
matched = True
matched_hash = hash(msg.matched_msg.groups())
elif rfunc.mode.upper() in ['A', 'FINDALL']:
msg.matched_msg = re.findall(rfunc.pattern, msg.trigger_msg, flags=rfunc.flags)
msg.matched_msg = re.findall(rfunc.pattern, trigger_msg, flags=rfunc.flags)
msg.matched_msg = tuple(set(msg.matched_msg))
if msg.matched_msg:
matched = True
Expand Down
4 changes: 2 additions & 2 deletions example/new_module/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,14 @@ async def _(msg: Bot.MessageSession):
await msg.send_message([Plain("A picture:"), Image("https://http.cat/100.jpg")])


@test.regex(re.compile(r"\{\{(.*)}}"), mode="M") # re.match
@test.regex(r"\{\{(.*)}}", mode="M") # re.match
async def _(msg: Bot.MessageSession):
# >>> {{Hello World!}}
# <<< Hello World!
await msg.finish(msg.matched_msg.group(1))


@test.regex(re.compile(r"\[\[(.*)]]"), mode="A") # re.findall
@test.regex(r"\[\[(.*)]]", mode="A") # re.findall
async def _(msg: Bot.MessageSession):
# >>> [[Hello]] [[World]]
# <<< Hello
Expand Down
32 changes: 14 additions & 18 deletions modules/bilibili/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,34 +36,30 @@ async def _(msg: Bot.MessageSession, bid: str, get_detail=False):
await msg.finish(msg.locale.t("message.cooldown", time=int(30 - res)))


@bili.regex(
re.compile(r"av(\d+)", flags=re.I), mode="M", desc="{bilibili.help.regex.av}"
)
@bili.regex(r"av(\d+)", flags=re.I, mode="A", desc="{bilibili.help.regex.av}")
async def _(msg: Bot.MessageSession):
query = f"?aid={msg.matched_msg.group(1)}"
await get_video_info(msg, query)
matched = msg.matched_msg[:5]
for video in matched:
if video:
query = f"?aid={video}"
await get_video_info(msg, query)


@bili.regex(
re.compile(r"\bBV[a-zA-Z0-9]{10}\b"), mode="A", desc="{bilibili.help.regex.bv}"
)
@bili.regex(r"\bBV[a-zA-Z0-9]{10}\b", mode="A", desc="{bilibili.help.regex.bv}")
async def _(msg: Bot.MessageSession):
matched = list(set(msg.matched_msg))[:5]
matched = msg.matched_msg[:5]
for video in matched:
if video != "":
if video:
query = f"?bvid={video}"
await get_video_info(msg, query)


@bili.regex(
re.compile(
r"\b(?:http[s]?://)?(?:bili(?:22|33|2233)\.cn|b23\.tv)/([A-Za-z0-9]{7})(?:/.*?|)\b"
),
mode="A",
desc="{bilibili.help.regex.url}",
)
@bili.regex(r"\b(?:http[s]?://)?(?:bili(?:22|33|2233)\.cn|b23\.tv)/([A-Za-z0-9]{7})(?:/.*?|)\b",
mode="A",
desc="{bilibili.help.regex.url}",
)
async def _(msg: Bot.MessageSession):
matched = list(set(msg.matched_msg))[:5]
matched = msg.matched_msg[:5]
for video in matched:
if video != "":
query = await parse_shorturl(f"https://b23.tv/{video}")
Expand Down
3 changes: 2 additions & 1 deletion modules/bugtracker/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ async def _(msg: Bot.MessageSession, mojiraid: str):
desc="{bugtracker.help.regex.desc}",
)
async def _(msg: Bot.MessageSession):
titles = list(set(msg.matched_msg))[:5]

titles = msg.matched_msg[:5]
for title in titles:
if title != "":
await query_bugtracker(msg, title)
20 changes: 10 additions & 10 deletions modules/exchange_rate/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import datetime
import re

from core.builtins import Bot
from core.component import module
from core.config import Config
from core.constants.exceptions import ConfigValueError
from core.utils.http import get_url
from core.utils.text import isfloat

api_key = Config("exchange_rate_api_key", cfg_type=str, secret=True)

Expand Down Expand Up @@ -61,8 +63,6 @@ async def exchange(base_currency, target_currency, amount: float, msg):
await msg.finish(
f"{msg.locale.t('exchange_rate.message.invalid.unit')}{' '.join(unsupported_currencies)}"
)
else:
raise Exception(data["error-type"])

url = f"https://v6.exchangerate-api.com/v6/{api_key}/pair/{base_currency}/{target_currency}/{amount}"
data = await get_url(url, 200, fmt="json")
Expand All @@ -81,18 +81,18 @@ async def exchange(base_currency, target_currency, amount: float, msg):
time=time,
)
)
else:
raise Exception(data["error-type"])


@excr.regex(
r"(\d+(\.\d+)?)?\s?([a-zA-Z]{3})\s?[兑换兌換]\s?([a-zA-Z]{3})",
r"(\d+(?:\.\d+)?)?\s?([a-zA-Z]{3})\s?[兑换兌換]\s?([a-zA-Z]{3})",
mode="M",
flags=re.I,
desc="{exchange_rate.help.regex.desc}",
)
async def _(msg: Bot.MessageSession):
groups = msg.matched_msg.groups()
amount = groups[0] if groups[0] else "1"
base = groups[2].upper()
target = groups[3].upper()
matched_msg = msg.matched_msg
amount = matched_msg.group(1) if matched_msg.group(1) and isfloat(matched_msg.group(1)) else 1
base = matched_msg.group(2).upper()
target = matched_msg.group(3).upper()
if base != target:
await msg.finish(await exchange(base, target, amount, msg))
await msg.finish(await exchange(base, target, float(amount), msg))
36 changes: 8 additions & 28 deletions modules/maimai/regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@
)


@mai_regex.regex(
re.compile(r"(.+)\s?是什[么麼]歌"), desc="{maimai.help.maimai_regex.song}"
)
@mai_regex.regex(r"(.+)\s?是什[么麼]歌", desc="{maimai.help.maimai_regex.song}")
async def _(msg: Bot.MessageSession):
name = msg.matched_msg.groups()[0]
if name[:2].lower() == "id":
Expand Down Expand Up @@ -75,10 +73,7 @@ async def _(msg: Bot.MessageSession):
await msg.finish(await get_info(music, Plain(res)))


@mai_regex.regex(
re.compile(r"(?:id)?(\d+)\s?有什(?:么别|麼別)[名称稱]", flags=re.I),
desc="{maimai.help.maimai_regex.alias}",
)
@mai_regex.regex(r"(?:id)?(\d+)\s?有什(?:么别|麼別)[名称稱]", flags=re.I, desc="{maimai.help.maimai_regex.alias}")
async def _(msg: Bot.MessageSession):
sid = msg.matched_msg.groups()[0]
music = (await total_list.get()).by_id(sid)
Expand All @@ -96,42 +91,30 @@ async def _(msg: Bot.MessageSession):
await msg.finish([Plain(result.strip())])


@mai_regex.regex(
re.compile(r"(.+)\s?有什[么麼]分\s?(.+)?"), desc="{maimai.help.maimai_regex.info}"
)
@mai_regex.regex(r"(.+)\s?有什[么麼]分\s?(.+)?", desc="{maimai.help.maimai_regex.info}")
async def _(msg: Bot.MessageSession):
songname = msg.matched_msg.groups()[0]
username = msg.matched_msg.groups()[1]
await query_song_info(msg, songname, username)


@mai_regex.regex(
re.compile(r"(\d+\+?)\s?([a-zA-Z]+\+?)\s?[进進]度\s?(.+)?"),
desc="{maimai.help.maimai_regex.process}",
)
@mai_regex.regex(r"(\d+\+?)\s?([a-zA-Z]+\+?)\s?[进進]度\s?(.+)?", desc="{maimai.help.maimai_regex.process}")
async def _(msg: Bot.MessageSession):
level = msg.matched_msg.groups()[0]
goal = msg.matched_msg.groups()[1]
username = msg.matched_msg.groups()[2]
await query_process(msg, level, goal, username)


@mai_regex.regex(
re.compile(r"(.?)([極极将將舞神者]舞?)[进進]度\s?(.+)?"),
desc="{maimai.help.maimai_regex.plate}",
)
@mai_regex.regex(r"(.?)([極极将將舞神者]舞?)[进進]度\s?(.+)?", desc="{maimai.help.maimai_regex.plate}")
async def _(msg: Bot.MessageSession):
plate = msg.matched_msg.groups()[0] + msg.matched_msg.groups()[1]
username = msg.matched_msg.groups()[2]
await query_plate(msg, plate, username)


@mai_regex.regex(
re.compile(
r"(?:随个|隨個)\s?((?:dx|DX|sd|SD|标准|標準)\s?)?([绿綠黄黃红紅紫白]?)\s?([0-9]+\+?)"
),
desc="{maimai.help.maimai_regex.random}",
)
@mai_regex.regex(r"(?:随个|隨個)\s?((?:dx|DX|sd|SD|标准|標準)\s?)?([绿綠黄黃红紅紫白]?)\s?([0-9]+\+?)",
desc="{maimai.help.maimai_regex.random}")
async def _(msg: Bot.MessageSession):
res = msg.matched_msg
if res:
Expand Down Expand Up @@ -162,10 +145,7 @@ async def _(msg: Bot.MessageSession):
await msg.finish(msg.locale.t("maimai.message.random.failed"))


@mai_regex.regex(
re.compile(r"(.+)\s?段位(?:[认認]定)?列?表"),
desc="{maimai.help.maimai_regex.grade}",
)
@mai_regex.regex(r"(.+)\s?段位(?:[认認]定)?列?表", desc="{maimai.help.maimai_regex.grade}")
async def _(msg: Bot.MessageSession):
grade = msg.matched_msg.groups()[0]
await get_grade_info(msg, grade)
39 changes: 13 additions & 26 deletions modules/wiki/inline.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,7 @@
)


@wiki_inline.regex(
re.compile(r"\[\[(.*?)\]\]", flags=re.I),
mode="A",
desc="{wiki.help.wiki_inline.page}",
)
@wiki_inline.regex(r"\[\[(.*?)\]\]", flags=re.I, mode="A", desc="{wiki.help.wiki_inline.page}")
async def _(msg: Bot.MessageSession):
query_list = []
for x in msg.matched_msg:
Expand All @@ -45,11 +41,7 @@ async def _(msg: Bot.MessageSession):
await query_pages(msg, query_list[:5], inline_mode=True)


@wiki_inline.regex(
re.compile(r"\{\{(.*?)\}\}", flags=re.I),
mode="A",
desc="{wiki.help.wiki_inline.template}",
)
@wiki_inline.regex(r"\{\{(.*?)\}\}", flags=re.I, mode="A", desc="{wiki.help.wiki_inline.template}")
async def _(msg: Bot.MessageSession):
query_list = []
for x in msg.matched_msg:
Expand All @@ -59,12 +51,11 @@ async def _(msg: Bot.MessageSession):
await query_pages(msg, query_list[:5], template=True, inline_mode=True)


@wiki_inline.regex(
re.compile(r"≺(.*?)≻|⧼(.*?)⧽", flags=re.I),
mode="A",
show_typing=False,
desc="{wiki.help.wiki_inline.mediawiki}",
)
@wiki_inline.regex(r"≺(.*?)≻|⧼(.*?)⧽",
flags=re.I,
mode="A",
show_typing=False,
desc="{wiki.help.wiki_inline.mediawiki}")
async def _(msg: Bot.MessageSession):
query_list = []
for x in msg.matched_msg:
Expand All @@ -75,16 +66,12 @@ async def _(msg: Bot.MessageSession):
await query_pages(msg, query_list[:5], mediawiki=True, inline_mode=True)


@wiki_inline.regex(
re.compile(
r"(https?://[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,4}\b[-a-zA-Z0-9@:%_+.~#?&/=]*)",
flags=re.I,
),
mode="A",
show_typing=False,
logging=False,
desc="{wiki.help.wiki_inline.url}",
)
@wiki_inline.regex(r"(https?://[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,4}\b[-a-zA-Z0-9@:%_+.~#?&/=]*)",
flags=re.I,
mode="A",
show_typing=False,
logging=False,
desc="{wiki.help.wiki_inline.url}")
async def _(msg: Bot.MessageSession):
match_msg = msg.matched_msg

Expand Down

0 comments on commit b6e330c

Please sign in to comment.