Search code examples
discorddiscord.pypython-asyncioattributeerror

An error occurred when trying to async def discord.py without a command. How to perform async def?


How do I perform functions without a command and why do I get this error?

from discord.ext import commands
import json
import discord
import asyncio
import pathlib
from pathlib import Path

client = discord.Client(command_prefix="!", intents=discord.Intents.all())

dir_path = pathlib.Path.cwd()
path_class_components = Path(dir_path, 'class_app', 'class_components')
path_class_components = str(path_class_components).replace("\class_wark\class_app","")+"\config.json"

config = json.load(open(path_class_components, 'r'))

async def my_background_task():
    await client.wait_until_ready()
    counter = 0
    channel = client.get_channel(id=970589128355905539) # replace with channel_id
    while not client.is_closed():
        counter += 1
        await channel.send(f"{counter}")
        await asyncio.sleep(60)

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.loop.create_task(my_background_task())
client.run(config['token'])
  • gives me an error... how do I fix it or what code should I use I don't understand at all)

Traceback (most recent call last): File "C:\Users\Monik\PycharmProjects\DiscordBuy\class_app\class_wark\class_requests.py", line 36, in <module> client.loop.create_task(my_background_task()) File "C:\Users\Monik\PycharmProjects\DiscordBuy\venv\lib\site-packages\discord\client.py", line 108, 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


Solution

  • Tasks are a great way to have functions/tasks executing every X period of time. Have a look at the docs and give them a go - shouldn't be too tricky to implement for your use case.