Reputation: 51
I would like to grab user input from the user when they enter a certain command and store the input into a variable (but not the command) so that I can do things with it.
As an example, when the user types "!id 500", I want the bot to type "500" in the channel. I have tried just using message.content but it doesn't work properly because the bot spams it indefinitely, plus it shows the command as well.
@client.event
async def on_message(message):
if message.content.startswith("!id"):
await client.send_message(message.channel, message.content)
Sorry if this is a silly question, but any help would mean a lot.
Upvotes: 5
Views: 15916
Reputation: 566
The reason your bot spams the text is because your bot is saying the command, which it follow. You need to block your bot from counting your output as a command. You could block it by:
if message.author.bot: return
.
This will return None if the author is a bot. Or, you could just block your bot's own id. You won't need to do this if you actually get your command to work correctly, but you should still add it. Second of all, the way I separate the command and arguments is
cmd = message.content.split()[0].lower()[1:]
args = message.content.split()[1:]
With these variables, you could do
@client.event
async def on_message(message):
if message.content.startswith('!'):
if message.author.bot: return # Blocks bots from using commands.
cmd = message.content.split()[0].lower()[1:]
args = message.content.split()[1:]
if command == "id":
await client.send_message(message.channel, ' '.join(args)
Upvotes: 0
Reputation: 303
If you want the bot to just send the message of the user without the command part ("!id") you'll have to specify which part of the string you want to send back. Since strings are really just lists of characters you can specify what part of the string you want by asking for an index.
For example:
"This is an example"[1]
returns "h".
In your case you just want to get rid of the beginning part of the string which can be done like so:
@client.event
async def on_message(message):
if message.content.startswith("!id"):
await client.send_message(message.channel, message.content[3:])
this works because it sends the string back starting with the 4th index place (indexes start at 0 so really [3] is starting at the fourth value)
This also applies if you just want to save the user's message as a variable as you can just do this:
userInput = message.content[3:]
You read more about string manipulation at the python docs.
Upvotes: 1
Reputation: 314
I would use commands extension - https://github.com/Rapptz/discord.py/blob/async/examples/basic_bot.py
Then make a command like,
@bot.command(pass_context=True)
async def id(ctx, number : int):
await bot.say(number)
Upvotes: 0