0

Is it possible to pass a message to a bots function? Like this:

@bot.command(pass_context=True)
async def message(ctx, user.message):
    if user.message == "xyz":
        await bot.say("Hi")

It would be good to pass the actual message and not a string with the same content.

Tristo
  • 2,328
  • 4
  • 17
  • 28
The S1
  • 39
  • 1
  • 5
  • 1
    You can also use the keyword-only syntax to capture the remainder of a message. See [Keyword-Only Arguments](https://discordpy.readthedocs.io/en/rewrite/ext/commands/commands.html#keyword-only-arguments) from the documentation – Patrick Haugh Sep 05 '18 at 20:34

1 Answers1

0

Yes, you can do

@bot.event
async def on_message(message):
  if message.content == "Hi":
    await bot.send_message(message.channel,"Hello")

This way you use an event instead of a command so when you write "Hi" into the chat the bot will catch it and run the method

If you want to pass something to the command function you can do so just like you would with a normal method

@bot.command()
async def example(something):
  print(something)

When you do !example Hello There the bot will print out Hello because from the strings it got as input (separated by whitespaces) it picked the first value and assigned it to your variable just like a normal program getting its input from the command line.

To catch all elements you can use *args

@bot.command()
async def example(*args):
  print(args)

which will return a tuple of all the values you gave from the chat. !example Hello There will print out ('Hello', 'There')

Tristo
  • 2,328
  • 4
  • 17
  • 28
  • When i use the event the rest of the commands dont work(or activate). – The S1 Sep 06 '18 at 15:51
  • [Here's the answer, you need to add an additional line at the end of on_message()](https://stackoverflow.com/a/49331419/9917504) – Tristo Sep 06 '18 at 15:55
  • One last question. Can i treat the message.content as a normal string? As an Example can i write if "asdf" in message.content? – The S1 Sep 07 '18 at 12:30
  • Yes, `content` returns a [normal string](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.content) – Tristo Sep 07 '18 at 12:32
  • In "await bot.send_message(message.channel,"Hello")" what do you have to replace message.channel with? – The S1 Sep 07 '18 at 13:28
  • If it's inside the event you don't have to replace it with anything since bot passes the message argument to the function and you can just take the `.channel` from it. [Check out the documentation](https://discordpy.readthedocs.io/ja/latest/api.html#discord.on_message) – Tristo Sep 07 '18 at 13:36