Help needed with Discord bot command recognition

I’m working on a Discord bot and I’m stuck on how to check if a message starts with one of the commands in my list. Here’s what I’ve got so far:

import discord

bot = discord.Client()

@bot.event
async def on_message(msg):
    cmd_list = ['!hello', '!info', '!help']

    for cmd in cmd_list:
        if msg.content.startswith(cmd):
            print('Command found!')
            break

bot.run('my_secret_token')

When I run this, I get an error saying something about ‘startswith’ being read-only. I’m not sure what that means or how to fix it. Can someone explain what I’m doing wrong and how to properly check if a message starts with any of the commands in my list? Thanks!

yo, i think ur problem might be with how ur handling the message content. try using msg.content.lower() instead of just msg.content. it’ll make ur commands case-insensitive too. like this:

if msg.content.lower().startswith(cmd.lower()):
print(‘Command found!’)
break

hope that helps! lemme know if u need anything else

I’ve run into similar issues when working with Discord bots. The problem isn’t actually with ‘startswith’ being read-only, but rather with how Discord.py handles message content. Here’s a solution that worked for me:

Instead of using msg.content directly, try accessing the content as a string using msg.content.lower(). This converts the content to lowercase, making your command checks case-insensitive too. So your code would look like this:

if msg.content.lower().startswith(cmd):
print(‘Command found!’)
break

Also, consider adding a prefix check before looping through commands to improve efficiency. For example:

if msg.content.startswith(‘!’):
for cmd in cmd_list:
# Your command check logic here

This way, you’re only checking messages that actually start with your command prefix. Hope this helps!

The error you’re encountering is likely due to the ‘msg.content’ attribute being a property rather than a regular string. To fix this, you can convert it to a string before using the startswith method. Try modifying your code like this:

if str(msg.content).startswith(cmd):
    print('Command found!')
    break

This should resolve the ‘read-only’ error. Additionally, consider using a set instead of a list for your commands if you have many of them, as it can improve lookup performance. Also, don’t forget to add a check to ignore messages from the bot itself to prevent potential loops. Good luck with your Discord bot project!