我将如何回复用户所说的消息?

时间:2021-01-25 19:55:11

标签: python discord discord.py

我正在尝试制作一个不和谐的机器人,当用户说“我很无聊”和“嗨,无聊,我是爸爸!”时,它会响应用户。我如何使“无聊”部分成为某人在“我是”之后所说的任何内容。现在是{sender},它只是说“嗨{sender},我是爸爸!”而不是我的用户名。

当前机器人代码:

import discord
from discord.utils import get
 
# imports library resources
 
client = discord.Client()
# connects to client
 
@client.event
async def on_ready():
    print('Logged in as {0.user}'.format(client))
    # prints in console the message when bot is turned on
 
@client.event
async def on_message(message):
    if message.author == client.user:
      # prevents the bot from responding to itself
        return
 
    if message.content.startswith('I\'m'):
      await message.channel.send('Hi {sender}, I\'m dad!')
 
    if message.content.startswith('im'):
      await message.channel.send('Hi {sender}, I\'m dad!')
  
    if message.content.startswith('Im'):
      await message.channel.send('Hi {sender}, I\'m dad!')
 
    if message.content.startswith('i\'m'):
      await message.channel.send('Hi {sender}, I\'m dad!')

2 个答案:

答案 0 :(得分:1)

如果其他反应不是您正在寻找的:

解决此问题的一种方法是拆分消息内容,切掉第一个元素(如果您也想查找,则拆分为前两个元素)

if message.content.startswith("I'm"):
      await message.channel.send(f"Hi {' '.join(message.content.split()[1:])}, I'm dad!")

编辑:一些 " 和 ' 问题

答案 1 :(得分:0)

您可以使用 .split() 将单词以空格分隔成一个列表。然后你可以使用 .index() 在列表中找到 I 的索引,然后 +1 得到下一个使用的词。

if "I\'m" in message.content:    
    word_list = message.content.split()
    index = word_list.index("I\'m")
    if index != len(word_list):
        name = word_list[index+1]