【问题标题】:How to print custom error message?如何打印自定义错误消息?
【发布时间】:2018-08-08 08:39:26
【问题描述】:

我有以下 Discord 机器人,它向特定用户发送私人消息,但如果用户在服务器上禁用了直接消息传递,我会在 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】:

您需要使用 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 块,并打印完成。

【讨论】:

    猜你喜欢
    • 2016-12-03
    • 2023-02-22
    • 2023-03-26
    • 1970-01-01
    • 2021-01-10
    • 2015-12-20
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    相关资源
    最近更新 更多