Python Discord Bot 消息复制但更改了 2 个或更多单词的内容

Python Discord Bot Message Copy But Changing Content For 2 or More Words

几天前,我打开了一个关于机器人的问题message.content

现在,我希望机器人将同一文本中的两个单词替换为仅回复一条消息。

到目前为止我有这个。

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    words = ['test', 'winter']
    changes = ['nice', 'summer']

    for word in words:
        if word in message.content:
            await message.channel.send(f"{message.content.replace(word, changes[words.index(word)])}")

    await client.process_commands(message)

这是机器人的作用: here

出于某种原因,它只对其中一个词有效。

您每次都在循环中向频道发送消息

在所有替换循环完成之前不要调用 message.channel.send

您可以考虑在循环内进行所有更改,并在完成后使用单个 message.send


@client.event
async def on_message(message):
    if message.author == client.user:
        return
    
    words = ['test', 'winter']
    changes = ['nice', 'summer']

    response_message = message.content
    for word in words:
        if word in message.content:
            response_message = f"{response_message.replace(word, changes[words.index(word)])}"  # in place update

    await message.channel.send(response_message)  # send this one after the replacement loop

    await client.process_commands(message)