How do I allow for multiple possible responses in a discord.py command?

做~自己de王妃 提交于 2021-02-08 07:01:33

问题


I'm attempting to set up a Discord bot while being relatively new to discord.py (and in reality, Python 3). I want to add the command "greet", which will prompt the user to say "hello" to it. It only responds to "hello", however, when I want it to respond to both "hello" and "Hello".

The only things I could think about fixing it was placing them in an or statement, which in theory should've made Python 3 and the bot choose between the two responses (as shown below).

@client.event
async def on_message(message):
    if message.content.startswith('~greet'):
        await client.send_message(message.channel, 'Say hello')
        msg = await client.wait_for_message(author=message.author, content=('hello' or 'Hello'))
        await client.send_message(message.channel, 'Hello.')

The original code I had for it was simple and only allowed for the one response of hello.

@client.event
async def on_message(message):
    if message.content.startswith('~greet'):
        await client.send_message(message.channel, 'Say hello')
        msg = await client.wait_for_message(author=message.author, content=('hello' or 'Hello'))
        await client.send_message(message.channel, 'Hello.')

For some reason I can't wrap my head around, it's still not recognizing 'Hello', and only ever allowing me to say 'hello' in response.


回答1:


or doesn't behave how you think it does. 'hello' or 'Hello' is evaluated before being passed to wait_for_message, and is equal to 'hello'.

Instead, you can provide a check function to wait_for_message:

def is_hello(message):
    return message.content.lower() == 'hello'

msg = await client.wait_for_message(author=message.author, check=is_hello)



回答2:


You should use command notation instead of checking for each message using on_message because it will make your code more readable. What will happen if you have 10 commands? Will you check for 10 strings in your on_message?

If thats's rewrite branch then the commands.Bot accepts a case_insensitive parameter:

bot = commands.Bot(command_prefix='!', case_insensitive=True)

Alternatively, if you want to use multiple words for the same command you can use aliases for example:

@bot.command(aliases=['info', 'stats', 'status'])
    async def about(self):
        # your code here


来源:https://stackoverflow.com/questions/55553158/how-do-i-allow-for-multiple-possible-responses-in-a-discord-py-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!