检查 discord bot 的权限,这样它就不会崩溃

Check discord bot's permissions so it wont crash

我正在制作一个愚蠢的 discord 机器人,但每次当他被静音或超时时它都会崩溃。 如何添加发送消息权限检查?

import discord
import random

TOKEN = "blahblahblah"

client = discord.Client()

@client.event
async def on_ready():
    print("{0.user} is now online!".format(client))

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

    if 'blah' in message.content or client.user.mentioned_in(message):
        print(message.author, ":", message.content)
        if random.randint(1,2) == 2:
            await message.channel.send('blah?')
        else:
            await message.channel.send('blah!')
client.run(TOKEN)

当他超时并尝试发送消息时,python 给我一个 403 禁止错误。

我在互联网上找到的所有解决方案都令人困惑,其中大部分都不起作用

你可以像这样捕获异常:

try:
    await message.channel.send("blah")
except discord.Forbidden:
    print("Bot is missing permissions")

我强烈建议使用 commands.Bot() 而不是 discord.Client(),因为它有几个好处,例如错误处理、命令扩展支持和检查等等。

https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html