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.