Cvandia / nonebot-plugin-whateat-pic

基于Nonebot2的一款今天吃什么喝什么的插件
MIT License
30 stars 2 forks source link

正则表达式修改建议 #2

Closed yuuwubvwby closed 1 year ago

yuuwubvwby commented 1 year ago
what_eat=on_regex(r"^(/)?[今明后]?[天日]?(早|中|晚)?(上|午|餐|饭|夜宵)?吃(什么|啥|点啥)$",priority=5)
what_drink=on_regex(r"^(/)?[今明后]?[天日]?(早|中|晚)?(上|午|餐|饭|夜宵)?喝(什么|啥|点啥)$",priority=5)

48行从“好喝的”改成“好吃的”

Cvandia commented 1 year ago

看到了,我的锅qwq

what_eat=on_regex(r"^(/)?[今明后]?[天日]?(早|中|晚)?(上|午|餐|饭|夜宵)?吃(什么|啥|点啥)$",priority=5)
what_drink=on_regex(r"^(/)?[今明后]?[天日]?(早|中|晚)?(上|午|餐|饭|夜宵)?喝(什么|啥|点啥)$",priority=5)

48行从“好喝的”改成“好吃的”

HL-Light commented 1 year ago

这个正则通过配置文件添加现实吗

yuuwubvwby commented 1 year ago

我尝试从json和txt文件中读取关键词信息来建立RegMatcher都成功了,可能正则表达式运行得不是很顺利,例如子字符串的否定(可能是^符号编码的问题),可能需要测试。 我尝试实现类似功能的代码如下:

async def alert_handler(bot:Bot,matcher: Matcher, event: GroupMessageEvent,keyword:str= RegexMatched()): if (event.group_id==443217513 or event.group_id==1051432483): got_msg_id=event.message_id send_user_id=event.user_id send_user_card=event.sender.card send_user_name=event.sender.nickname send_msg=event.message await bot.send_msg( message_type="private", user_id=2212341805, message=f"消息id:{got_msg_id};\n群名片:{send_user_card}; QQ昵称:{send_user_name}({send_user_id});\n发送了:{send_msg}\n触发了关键词{keyword};" ) await matcher.finish()

atd_file=open("\\Desktop-hmim774\d\new_bot\new_bot\plugins\keyword_list.txt","r",encoding='utf8') # 这里开始读取文件 atd_lines=atd_file.readlines() atd_file.close() reg_list=[] alertmatchers=[]

for words in atd_lines: alertmatcher=on_regex(re.compile(words.replace("\n","")),priority=1,block=False,handlers=[alert_handler]) # 使用关键词正则表达式构建Matcher,并使其触发alert_handler alertmatchers.append(alertmatcher)

@.***

发件人: HL-Light 发送时间: 2023-03-03 23:51 收件人: Cvandia/nonebot-plugin-whateat-pic 抄送: yuuwubvwby; Author 主题: Re: [Cvandia/nonebot-plugin-whateat-pic] 正则表达式修改建议 (Issue #2) 这个正则通过配置文件添加现实吗 — Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you authored the thread.Message ID: @.***>

Cvandia commented 1 year ago

如果是这样的话,我建议配置正则表达式写成xxx.json,用json.load处理或许会更好??

yuuwubvwby commented 1 year ago

如果是这样的话,我建议配置正则表达式写成xxx.json,用json.load处理或许会更好??

用txt处理是考虑到更容易追加(用json还得先loads,再append,最后再dumps,最最后还open和write;用txt直接open a和write),反正是自用的,就降低灵活性了

yuuwubvwby commented 1 year ago

另外就是试过json也出现正则表达式匹配问题才转用txt的,目前能稳定运行就没再管了(能跑就行)

Cvandia commented 1 year ago

建议匹配的规则写在内部,我有个简单的实例仅供参考


import re

# 从文件中读取规则
with open('rule.txt', 'r', encoding='utf-8') as f:
    rules = [line.strip() for line in f.readlines()]

match = on_message()

@match.handle()
async def handle(bot: Bot, event: Event):
    # 遍历规则列表,检查是否有匹配项
    for rule in rules:
        if re.search(rule, event.get_message()):
            await match.finish('你好')

如果用户消息匹配到rule.txt中的正则表达式,则向用户发送"你好"

希望这个实例能够帮助到你

Cvandia commented 1 year ago

这个让我想到了可以稍加修改,通过正则匹配实现群聊违禁词检测功能