Hey everyone! I’m working on a Discord bot using Python. I’m stuck on a part where I want to compare a user’s message to a list of events.
Here’s what I’m trying to do:
- User types a command like
?event_add [event name]
- Bot checks if the event is already in the list
- If it’s there, bot says it’s a duplicate
- If not, bot adds it (but I haven’t coded this part yet)
My problem is the comparison isn’t working right. It always says the event doesn’t match, even when it should. Here’s a simplified version of my code:
events = {'party time'}
@bot.command()
async def add_event(ctx, event):
if event in events:
await ctx.send('That event already exists!')
else:
await ctx.send('Something went wrong...')
Any ideas what I’m doing wrong? I’m using Python 3.6 and the latest discord.py library. Thanks for your help!
I’ve encountered a similar issue when building my Discord bot. The problem likely lies in how you’re handling the event input. Here’s what worked for me:
Use the ‘*’ parameter to capture multi-word events, strip whitespace and convert the input to lowercase for consistency, and use a set for faster lookups.
Here’s a snippet that should solve your problem:
events = set()
@bot.command()
async def add_event(ctx, *, event):
event = event.strip().lower()
if event in events:
await ctx.send('Event already exists!')
else:
events.add(event)
await ctx.send(f'Added event: {event}')
This approach ensures that ‘Party Time’, ‘party time’, and ’ party time ’ are all treated as the same event. Hope this helps!
hey man, i think i kno whats goin on. ur probably not handlin the input right. try this:
@bot.command()
async def add_event(ctx, *, event):
event = event.lower().strip()
if event in events:
await ctx.send(‘already got that one!’)
else:
events.add(event)
await ctx.send(f’added {event}')
this should fix ur issue. it makes everything lowercase and gets rid of extra spaces. good luck!
I’ve run into this issue before. The problem is likely with how you’re handling the input. Try modifying your code like this:
@bot.command()
async def add_event(ctx, *, event):
event = event.strip().lower()
if event in events:
await ctx.send(‘Event already exists!’)
else:
events.add(event)
await ctx.send(f’Added event: {event}')
This will normalize the input by removing extra spaces and converting to lowercase. It also allows for multi-word events. Make sure to initialize ‘events’ as a set for efficient lookups. This approach should solve your comparison problem and make your bot more robust.