如何验证discord用户ID



我目前正在开发一个discord.py重写机器人,该机器人具有一些审核功能,如ban、kick,由于问题现在是unban,我需要一种方法来验证输入的discord-id是否有效,而不是例如字符串、太短或太长。

根据您想要验证输入的原因(我在这里假设您只是想尝试取消对不存在的用户的绑定,以免引发错误(,您无论如何都可以调用它。假设您正在执行的步骤有点像get user,然后是user unban,您可以使用一些try-catch,如下所示:

try:
int_id = int(string_id)
user = bot.fetch_user(int_id) # this should likely be async
# whatever code you are already using here to link user id to a server
# member or using the guild context route
except ValueError: # Python error if you cast a non-numeric string to int
print(f"{string_id} is not a well-formed id.") # is not a number
except NotFound: #  # Discord error if there is no user for given id
print(f"{int_id} is not a valid id.") # is a number but not a user
except HTTPException: # Discord error if could not contact server
print(f"{int_id} could not be fetched.") # nothing to do with id

最新更新