Discord bot slash command initialization fails with AttributeError

I’m building a Python Discord bot that uses slash commands for my class assignment. When I try to run the bot, I keep getting this error:

Traceback (most recent call last):
  File "d:\Projects\bot\main.py", line 10, in <module>
    command_handler = SlashCommand(client, sync_commands=True)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\discord_slash\client.py", line 59, in __init__
    self._discord.loop.create_task(self.sync_all_commands(delete_from_unused_guilds))
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\discord\client.py", line 140, in __getattr__
    raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook

Here’s my code:

import discord
import serial
from discord_slash import SlashCommand
from discord.ext import commands

permissions = discord.Intents.all()

client = commands.Bot(command_prefix="!", intents=permissions)

command_handler = SlashCommand(client, sync_commands=True)

bulb_status = False

connection = serial.Serial("COM4", baudrate=9600, timeout=1)

@client.event
async def on_ready():
    print(f"{client.user.name} has started")

@command_handler.slash(name="light on", description="activate all lights")
async def activate_lights(interaction):
    connection.write(b'1')
    await interaction.send("Lights have been activated")

client.run(MY_TOKEN)

Not sure what’s causing this issue.

The error is due to the attempt to initialize SlashCommand outside of an asynchronous context. The discord-slash library requires access to the bot’s event loop, which isn’t available during synchronous execution. A solution would be to either move the initialization into an asynchronous function like setup_hook, or consider switching to the native slash commands in discord.py, which are more streamlined. You can update your slash command decorator to @client.tree.command() and ensure to call await client.tree.sync() in the on_ready event. This change will help eliminate the issues you’re facing.

yeah, the discord-slash lib aint working well with the latest discord.py. u should look into using the built-in slash commands instead. it’s way easier! just use @client.tree.command() and make sure to call await client.tree.sync() in your setup hook.