I’m trying to create a Discord bot in Python that can take user input after a specific command and use it. For instance, if a user types ‘!info 123’, I want the bot to only respond with ‘123’ in the channel.
I’ve attempted using message.content
, but it’s not working as expected. The bot keeps spamming and includes the command in its response. Here’s what I’ve tried so far:
@bot.event
async def on_message(msg):
if msg.content.startswith('!info'):
await bot.send_message(msg.channel, msg.content)
This code doesn’t work right. It keeps sending messages and shows the whole command. How can I fix this to only get the part after the command and use it once? Any tips would be really helpful. Thanks!
I’ve faced similar issues when developing Discord bots. Here’s a solution that should work for you:
Use the split() method to separate the command from the input. Then, you can access the input part using indexing. Also, to prevent the bot from spamming, you should add a check to ensure it doesn’t respond to its own messages.
Here’s an improved version of your code:
@bot.event
async def on_message(msg):
if msg.author == bot.user:
return
if msg.content.startswith('!info'):
user_input = msg.content.split(' ', 1)[1]
await msg.channel.send(user_input)
This code will extract everything after '!info ’ and send it as a response. It also includes a check to prevent the bot from responding to itself. Hope this helps!
As someone who’s been tinkering with Discord bots for a while, I can tell you that handling user input can be tricky at first. Here’s a neat trick I’ve learned:
Instead of using on_message, consider using Discord.py’s command framework. It’s much cleaner and easier to manage. Here’s how you could do it:
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
@bot.command()
async def info(ctx, *, arg):
await ctx.send(arg)
This approach automatically handles the command prefix and splits the arguments for you. It’s more efficient and less prone to errors. Plus, it gives you built-in error handling and help command generation.
Just remember to call bot.run(your_token) at the end of your script. This method has saved me countless headaches when dealing with user input in my bots.
yo, i had the same problem before. try this:
@bot.command()
async def info(ctx, *, stuff):
await ctx.send(stuff)
it grabs everything after ‘!info’ and sends it back. way easier than messing with message.content. hope it helps!