【问题标题】:How can you make a Discord's bot commands not case sensitive?如何让 Discord 的机器人命令不区分大小写?
【发布时间】:2020-09-22 16:14:11
【问题描述】:

所以我有一个运行 discord.py 的 Discord 机器人,它会回复你好!对在机器人运行时打招呼的任何人。代码看起来像

if message.content == "Hello":
        await message.channel.send('Hello!')

它有效,但前提是消息与原始消息的大小写完全相同。我希望这样如果有人打招呼,那么它也会返回 Hello!这可能吗,还是我只需要对 Hello 字符串的每个案例进行编码?

【问题讨论】:

标签: python discord discord.py


【解决方案1】:

只需将消息内容转换为小写,然后将其与小写命令进行比较。这样,无论输入如何大写,机器人都会看到相同的“hello”结果。

if message.content.lower() == "hello":
        await message.channel.send('Hello!')

【讨论】:

  • 这是否在前缀中起作用,其中前缀是一个符号,例如 if message.content.lower() == prefix + "hello": await message.channel.send('Hello!')
  • 在您的脑海中运行一些示例输入,看看您是否可以确定它们是否有效。如果您的前缀是“a?”然后你发送一个像“A?hELLo”这样的消息,左边和右边会比较什么?
  • 这对 .message.content.startswith 有什么作用?
  • @RyanYin message.content.lower() 返回一个字符串,你可以在上面调用startswith
  • 如果是 hello 函数会是什么样的代码?
【解决方案2】:

如果你想使用命令装饰器创建不区分大小写的命令,在实例化机器人时你可以这样做:

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

但是当您使用on_message 事件时,您可以将其转换为小写:

async def on_message(message):
    if message.content.lower() == "hello": # make sure the comparison string is all lower-case
        await message.channel.send("Hello!")

参考资料:

【讨论】:

    猜你喜欢
    • 2019-08-12
    • 2021-05-24
    • 2020-09-04
    • 2021-05-20
    • 2018-11-04
    • 2013-06-08
    • 1970-01-01
    • 2018-01-25
    • 2021-03-17
    相关资源
    最近更新 更多