【问题标题】:why does discord.py keep sending messages?为什么 discord.py 一直在发送消息?
【发布时间】:2021-03-16 19:13:02
【问题描述】:

我创建了一个事件,如果用户发送特定消息,则返回消息。 前。如果用户说“你好”,机器人会说“你好”。我发现在下面的代码中,第一个 elif 有一个 or..so 如果用户说 ddos​​ 或 hack,它会进入无限循环并继续发送 你不能这么说!。如果用户输入你好,机器人发送一次你好,然后进入无限循环并发送你不能这么说!。任何想法为什么?

@client.event
async def on_message(message):
    msg = message.content.lower()
    if str(msg) == "hello":
        await message.channel.send('hello there')
    elif str(msg) == "hack" or "ddos":
        await message.channel.send("you can't say that!")
    else:
        return

【问题讨论】:

    标签: discord.py


    【解决方案1】:

    您的代码有一些错误。第一个,你必须检查消息作者是否是机器人,所以on_message 事件不会检查机器人的消息。您可以通过discord.Member.bot查看。如果成员是机器人,这将返回 True。

    @client.event
    async def on_message(message):
        if message.author.bot:
            return
    

    第二个是elif str(msg) == "hack" or "ddos":不等于elif str(msg) == "hack" or str(msg) == "ddos":

    elif str(msg) == "hack" or "ddos": 表示msg 等于 hackddos 是否存在。此外,您不必执行str(msg)message.content 返回str 类型对象。

    @client.event
    async def on_message(message):
        if message.author.bot:
            return
        msg = message.content.lower()
        if msg == "hello":
            await message.channel.send('hello there')
        elif msg == "hack" or msg == "ddos":
            await message.channel.send("you can't say that!")
    

    编辑

    您可以使用if msg in list: 来检查消息内容是否在单词列表中。这是一个例子:

    if msg in ['hack', 'ddos']:
        await message.channel.send("you can't say that!")
    

    这将执行相同的操作:

    if msg == 'hack' or msg == 'ddos':
        await message.channel.send("you can't say that!")
    

    【讨论】:

    • 非常感谢!!我不知道你必须再写一次 msg ==。您还知道如何检查用户是否从列表中输入了某些内容吗?就像我可以制作一个单词列表然后查看该单词是否在列表中?如果是,它会向他们发送一条消息,如果不是,它会返回。我们会为此使用 for 循环吗?
    猜你喜欢
    • 2021-07-08
    • 2021-08-31
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2020-11-10
    • 2020-10-31
    • 2017-08-15
    • 2021-05-02
    相关资源
    最近更新 更多