首页 > 解决方案 > 有没有办法让 Discord Dadbot 稍后在消息中找到“我是”?

问题描述

所以我正在我的 Discord 服务器上使用 Python 开发一个个人机器人,它可以做很多事情,其中​​之一是模仿常见的 Dadbot。这是执行此操作的代码:

if any(word in msg for word in imlist):      
    resp = message.content.split(" ",1)[1]
    await message.channel.send("Hi "+ resp +", I'm Pigeonbot")

if any(word in msg for word in iamlist):
    resp = message.content.split(" ",2)[2]
    await message.channel.send("Hi "+ resp +", I'm Pigeonbot")

这是两个列表:

imlist = ["I'm", "Im", "im", "i'm", "IM", "I'M"]
iamlist = ["i am", "I am", "I AM"]

如果您输入不和谐的消息,例如“我饿了”,它会回复“嗨,饿了,我是 Pigeonbot”。但是,如果你在“我是”之前说一些东西,例如“外面很热,我很饿”,它会返回“你好,外面很热,我很饿,我是 Pigeonbot”。有没有办法让机器人在消息中找到 imlist 或 iamlist 的位置并从那里启动“嗨 [],我是 Pigeonbot”?谢谢 :)

标签: pythonlistdiscordbots

解决方案


这是正则表达式的一个很好的用例

您可以使用正则表达式I(?:'| a)?m ([^\s]*) 演示

解释:

  • I: 匹配文字I
  • (?:...)?:使内容成为可选的非捕获组
  • '| a: 非捕获组的内容:匹配撇号,或空格和a
  • m : 匹配一个m然后是一个空格。
  • (...):创建捕获组
  • [^\s]*: 匹配除空格以外的任意字符,任意次数

从演示中可以看出,这只会捕获I'm. 如果您想在之后捕获所有内容I'm,可以将正则表达式更改为I(?:'| a)m (.*) Demo。在这里,捕获组的内容匹配任意字符,任意次数

import re

expr1 = re.compile(r"I(?:'| a)m ([^\s]*)", re.IGNORECASE) # Use the re.IGNORECASE flag for case-insensitive match

expr2 = re.compile(r"I(?:'| a)m (.*)", re.IGNORECASE)

test_texts = ["I'm hungry", "It's hot and I'm parched", "I'm not stupid", "I'm going to go to bed now, see you tomorrow"]

for s in test_texts:
    print(f"text: {s}")
    match = re.search(expr1, s)
    if match:
        resp = match.group(1)
        print(f"\texpr1: Hi {resp}, I'm pigeonbot")

    match2 = re.search(expr2, s)
    if match2:
        resp2 = match2.group(1)
        print(f"\texpr2: Hi {resp2}, I'm pigeonbot")

这给了我们输出:

text: I'm hungry
    expr1: Hi hungry, I'm pigeonbot
    expr2: Hi hungry, I'm pigeonbot
text: It's hot and I'm parched
    expr1: Hi parched, I'm pigeonbot
    expr2: Hi parched, I'm pigeonbot
text: I'm not stupid
    expr1: Hi not, I'm pigeonbot
    expr2: Hi not stupid, I'm pigeonbot
text: I'm going to go to bed now, see you tomorrow
    expr1: Hi going, I'm pigeonbot
    expr2: Hi going to go to bed now, see you tomorrow, I'm pigeonbot

推荐阅读