I’m working on a Discord bot and need help with parsing command arguments. When someone types a command like ?show 123, I want to capture just the 123 part and use it in my bot’s response.
Right now my code isn’t working correctly. It either repeats the entire command or creates an endless loop. Here’s what I have so far:
@bot.event
async def on_message(msg):
if msg.content.startswith("?show"):
await bot.send_message(msg.channel, msg.content)
This outputs ?show 123 but I only want 123. I’ve tried using msg.content but it includes the command prefix too. How can I extract just the user input after the command? I want to store that number in a variable so I can process it further.
Any suggestions would be really helpful. Thanks in advance!
String slicing works great for this. Use msg.content[5:].strip() to cut out the command prefix and clean up whitespace. The 5 jumps past “?show” and strip() fixes spacing problems.
@bot.event
async def on_message(msg):
if msg.content.startswith("?show"):
argument = msg.content[5:].strip()
if argument: # Check if there's actually something after the command
await bot.send_message(msg.channel, argument)
This handles users who type multiple spaces between the command and argument. Really useful for longer arguments with spaces in them. Just validate the input before you process it in your bot.
you could also use regex for more flexibility. just import re and then re.search(r'\?show\s+(\S+)', msg.content) to grab the argument. it’s great when your commands get complex, but probably overkill for something this simple.
Had this exact issue when I started with discord.py. Just slice the string after splitting it. Use msg.content.split() to break the message into parts, then grab everything after the command. Here’s what worked for me:
@bot.event
async def on_message(msg):
if msg.content.startswith("?show"):
parts = msg.content.split()
if len(parts) > 1:
number = parts[1] # Gets "123" from "?show 123"
await bot.send_message(msg.channel, number)
You could also use msg.content[6:] since "?show " is 6 characters, but splitting is more reliable with varying command lengths. Just check if the argument exists before using it - you’ll get index errors if someone types “?show” with nothing after it.