I’m working on a Discord bot using Python and I need help with extracting arguments from user commands. When someone types a command like %test 123, I want my bot to grab just the 123 part and use it in my response.
Right now I’m having trouble because my current code captures the entire message including the command prefix. For instance, if a user writes %test 123, I want the bot to reply with only 123 in the chat.
Here’s what I have so far:
@bot.event
async def on_message(msg):
if msg.content.startswith("%test"):
await bot.send_message(msg.channel, msg.content)
The problem is this sends back the whole command instead of just the number part. Also the bot keeps repeating messages which is annoying. How can I split the command from the actual input I want to work with?
Your bot’s stuck in a loop because it’s responding to its own messages. You need to ignore bot messages and fix how you’re slicing the command. Here’s the fix: ```python @bot.event
async def on_message(msg):
if msg.author == bot.user:
return
if msg.content.startswith(“%test”):
argument = msg.content[6:] # Remove "%test " (6 characters)
await bot.send_message(msg.channel, argument)
The `msg.author == bot.user` check stops the infinite loop. Using `[6:]` strips the first 6 characters ("%test " with the space), so you get just "123". Just make sure there's actually something after the command or you'll get blank responses.
An issue causing the infinite loop is that the bot is replying to its own messages. To prevent this, include a check at the beginning of your code to ignore messages from the bot. For extracting arguments, instead of relying on slicing by character count, utilizing the split() function is a more dependable approach:
@bot.event
async def on_message(msg):
if msg.author.bot:
return
if msg.content.startswith("%test"):
parts = msg.content.split(" ", 1)
if len(parts) > 1:
argument = parts[1]
await bot.send_message(msg.channel, argument)
Using split will divide the input at the first space, allowing you to easily separate the command from its arguments. The check for the length of parts ensures you don’t encounter errors if the command is used without any arguments.
btw you should also add await bot.process_commands(msg) at the end if you’re planning to use @bot.command decorators later. also try msg.content.replace('%test ', '', 1) - it’s simpler than splitting and handles the space automatically without counting chars