I’m working on a Discord bot using Python 3.8.2 and I’m stuck on a problem. Right now, my bot only responds when a message starts with certain words from a list. But I want it to respond if those words appear anywhere in the message.
Here’s a simplified version of what I’ve got:
import discord
from discord.ext import commands
duck_bot = commands.Bot(command_prefix='!')
duck_sounds = ['QUACK', 'HONK', 'SQUAWK', 'WADDLE']
@duck_bot.event
async def on_message(msg):
if any(sound in msg.content for sound in duck_sounds):
await msg.channel.send('Bread please!')
@duck_bot.event
async def on_ready():
print('Duck bot is ready to waddle!')
How can I change this so the bot checks for these words anywhere in the message, not just at the beginning? Any help would be awesome!
yo, ur almost there! just gotta tweak that on_message function a bit. try using the ‘in’ operator to check if any duck sound is in the message. like this:
if any(sound.lower() in msg.content.lower() for sound in duck_sounds):
that’ll catch those quacks anywhere. good luck with ur bot!
Your approach is on the right track. To achieve what you’re after, you’ll want to modify your on_message event handler. The ‘in’ operator is indeed the key here. Consider this modification:
@duck_bot.event
async def on_message(msg):
if any(sound.lower() in msg.content.lower() for sound in duck_sounds):
await msg.channel.send(‘Bread please!’)
This checks for duck sounds anywhere in the message, case-insensitively. One thing to keep in mind: this might make your bot quite chatty if these words appear frequently. You might want to implement a cooldown mechanism to prevent spam. Also, don’t forget to add duck_bot.process_commands(msg) at the end of your on_message function if you’re using command decorators elsewhere in your code.
Hey there! I’ve actually tackled this exact issue before with my own Discord bot. The good news is, your code is pretty close to what you need. The key is in how you’re checking for the words.
Instead of using ‘startswith’, you can use the ‘in’ operator to check if any of your duck sounds appear anywhere in the message. Here’s a quick tweak that should do the trick:
@duck_bot.event
async def on_message(msg):
if any(sound.lower() in msg.content.lower() for sound in duck_sounds):
await msg.channel.send('Bread please!')
This checks for the sounds regardless of case and position in the message. I’ve found it works like a charm. Just remember to handle potential spam if the bot starts responding too frequently. Good luck with your duck bot!