Skip to content
Advertisement

Discord wait_for() how to add multiple responses from the author?

Currently my discord bot responds to one message.

  • !add 12345
  • bot responds “Do you wish to add this item? y/n
  • user writes y or n (currently only works with 1 response
  • if user writes y (bot responds “it was added”), if user writes n (bot responds “it was not added”)

How would I go about adding the “n” response?

Here is my current code

@client.command()
async def target(ctx, arg1):
    sku = arg1
    channel = ctx.channel
    await ctx.channel.send('Do you wish to add this item? y/n')

    def check(m):
        return m.content == 'y' and m.channel == channel

    msg = await client.wait_for('message', check=check)
    await ctx.channel.send('It was added!'.format(msg))

Advertisement

Answer

To answer this, I think you just need to understand a little more the discord.py client.wait_for() method, and specifically what its check callback and return actually do. From the documentation:

  • check (Optional[Callable[…, bool]]) – A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.

Returns

Returns no arguments, a single argument, or a tuple of multiple arguments that mirrors the parameters passed in the event reference.

In other words, check is simply a filter that must return True when you want to stop waiting and do something with the waited for message. The return in this case is the same as the message passed into the callback.

So you can simply extend the logic of check to filter on ‘n’ in addition to ‘y’ for example. (Or if you wanted to always say something after any message to the channel, you could get rid of the content checks entirely)

Then, once wait_for returns, you can use the returned Message() object to do your branching based on what was actually said:

@client.command()
async def target(ctx, arg1):
    sku = arg1
    channel = ctx.channel
    await ctx.channel.send('Do you wish to add this item? y/n')

    def check(m):
        return m.content in ['y', 'n'] and m.channel == channel

    msg = await client.wait_for('message', check=check)
    if msg.content == 'y':
        await ctx.channel.send('It was added!')
    elif msg.content == 'n':
        await ctx.channel.send('It was not added')

I also dropped the format() call as it was a no-op here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement