I am trying to make a discord bot using discord.py 2.0.0. I want to make a slash command that returns the user id of a Bot object, below is a simplified version of my code:
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)
I tried to access the bot’s user id by using the Bot.id attribute. However, I got the following error that the attribute does not exist:
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'
Can someone please help me? Thank you!
>Solution :
According to the documentation and code neither of Bot‘s base classes, BotBase and Client have an id attribute.
BotBase provides owner_id and owner_ids respectively to get the id of the owning user.
The id attribute can be found on the user attribute (code) along with the name:
import discord
import asyncio
client = discord.Client()
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.run('token')