如何打印自定义错误消息?

问题描述 投票:-2回答:1

我有以下Discord bot向特定用户发送私人消息,但如果用户在服务器上禁用了直接消息,我在cmd中收到以下错误:

discord.errors.Forbidden:FORBIDDEN(状态代码:403):无法向此用户发送消息

如何修改代码以便获取自定义消息而不是上述错误,例如“无法向此用户发送消息”

我用谷歌搜索但无法找到解决方案。

这是当前的代码:

import discord
import asyncio
import os
from users import userID

key = open("ID.txt","r").readline()
message = open("message.txt","r").read()

bot = discord.Client() # Assign client to an easier variable to follow... for fun.

@bot.event  # must confirm the connection when it's done connecting
async def on_ready():
    print("Connected!")
    print("Username: " + bot.user.name)
    print("   ")
    user = await bot.get_user_info(userID)
    await bot.send_message(user, message)
    print("Done")

bot.run(key.strip())
python python-3.x discord discord.py
1个回答
1
投票

您需要使用try-except块,并带有可选的else关键字。

try:
    user = bot.send_message(user, message)
except discord.errors.Forbidden:
    print(“User doesn’t allow direct messaging.”)
else:
    print(“Done”)

它的作用是:它尝试将消息发送给用户。如果失败,并收到discord.errors.Forbidden异常,它将进入except块,并打印消息,告知它被禁止。如果它没有得到异常,它会进入else块,并完成打印。

© www.soinside.com 2019 - 2024. All rights reserved.