如何在discord.py 2.0.0中获取Bot对象的User_ID?
问题描述
我正在使用discord.py 2.0.0开发Discord机器人,想要实现一个斜杠命令来返回Bot对象的用户ID,以下是我的简化代码:
import discord from discord.ext.commands import Bot intents = discord.Intents.all() client = Bot(command_prefix='?', intents=intents) tree = client.tree @tree.command(name="help", description="Help command") async def help(interaction: discord.Interaction): await interaction.response.send_message(f"Hello, I am {str(client.id)}") token = "My Token" client.run(token)
我尝试通过Bot.id属性获取机器人的用户ID,但出现了属性不存在的错误,报错信息如下:
Traceback (most recent call last): File "C:\Users\trnt\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 851, in _do_call return await self._callback(interaction, **params) # type: ignore File "C:\discordbot\bot.py", line 8, in help await interaction.response.send_message(f"Hello, I am {str(client.id)}") AttributeError: 'Bot' object has no attribute 'id' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\trnt\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1240, in _call await command._invoke_with_namespace(interaction, namespace) File "C:\Users\trnt\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace return await self._do_call(interaction, transformed_values) File "C:\Users\trnt\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 869, in _do_call raise CommandInvokeError(self, e) from e discord.app_commands.errors.CommandInvokeError: Command 'help' raised an exception: AttributeError: 'Bot' object has no attribute 'id'
解决方案
Bot对象本身没有id属性,要获取机器人的用户ID,需通过client.user.id来实现。Bot类继承自Client类,Client的user属性对应机器人的User对象,该对象包含id属性。
修正后的代码如下:
import discord from discord.ext.commands import Bot intents = discord.Intents.all() client = Bot(command_prefix='?', intents=intents) tree = client.tree @client.event async def on_ready(): await tree.sync() # 同步斜杠命令到服务器 print(f"已登录为 {client.user} (ID: {client.user.id})") @tree.command(name="help", description="Help command") async def help(interaction: discord.Interaction): # 确保机器人已完成登录初始化 if client.user is None: await interaction.response.send_message("机器人尚未就绪!") return await interaction.response.send_message(f"你好,我是 {client.user} (ID: {client.user.id})") token = "My Token" client.run(token)
补充说明
- 机器人完成登录后,
client.user才会被初始化,建议在on_ready事件触发后再执行相关操作,或在命令中加入判断避免报错。 - 斜杠命令必须调用
tree.sync()同步到Discord服务器,否则用户无法触发命令。
内容的提问来源于stack exchange,提问作者turrnut
相关产品推荐
相关产品推荐

