有没有办法制作一个可以在消息后面找到 "I'm" 的 Discord Dadbot?

Is there a way to make a Discord Dadbot that can find "I'm" later in a message?

所以我正在我的 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"]

如果您在 discord 中输入“我饿了”之类的消息,它会回复“嗨,饿了,我是 Pigeonbot”。但是,如果你在“我”之前说些什么,比如“外面很热,我很饿”,它会 return “嗨,外面很热,我很饿,我是 Pigeonbot” . 有没有办法让机器人找到消息中 imlist 或 iamlist 的位置,并从那里开始“嗨 [],我是 Pigeonbot”?谢谢:)

尝试类似的东西。

all_list = imlist+iamlist
message_word_text = message.content.split(" ")
indices = []
for word in all_list:
      try:
       indices.append(message_word_text[word])
      except:
       indices.append(100)
noun = message_word_text[message_word_text.index(all_list[indices.index(min(indices)])+1]
print(f'Hi {noun}')




本质上,我们在这个程序中所做的是在 I'm 列表中附加与消息词相关的每个词的索引。这些指数中最低的意味着第一个词。然后我们通过取最低值的索引找到名词,将它传递到 I'm 列表中,然后在消息内容中找到它,最后我们找到后面的单词。

这是 regular expressions

的一个很好的用例

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

解释:

  • I:匹配文字I.
  • (?:...)?:使内容成为可选的non-capturing group
  • '| a:非捕获组的内容:匹配一个撇号,或者一个space和a.
  • m :先匹配一个m再匹配一个space.
  • (...): 创建一个capturing group
  • [^\s]*:匹配除space以外的任意字符,任意次数

从演示中可以看出,这只会捕获 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