Search code examples
pythondiscorddiscord.pybots

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


some days ago, I have opened a question about bot message.content here

Now, I would want the bot to replace two words in the same text with replying only with one message.

So far I have this.

@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)

This is what the bot does: here

For some reason, it only works for one of the words.


Solution

  • You're sending the message to the channel every time around the loop

    don't call message.channel.send until after all the replacement loops are complete.

    you may consider making all the changes within the loop and using a single message.send after that is complete

    
    @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)