1
votes

I wanted to use cogs to categorize commands and to not have to restart my whole bot to make an update to certain commands.

So I added the cogs and added my first command and everything worked: the command ran and I could update and reload it without having to restart my bot, but I noticed the async def coroutine didn't run no matter what.

I tried using asyncio.run() instead of await but that didn't help. I added the coroutine and the command back to the main file and everything worked. I don't get any error messages it just refuses to run. I would like to know what I'm doing wrong since I'm pretty new to cogs.

Cogs file:

class MembersCog(commands.Cog):
    def __init__(self, client):
        self.client = client


    async def printfunc(self):
        print("coroutine just ran") #This never runs.

    @commands.command()
    async def test(self, ctx):
        print("command just ran")
        await printfunc()

def setup(client):
    client.add_cog(MembersCog(client))
1

1 Answers

1
votes

When defining a method within a class, you'll want to access it via the self keyword, so that the program then knows that it's referring to the method inside its own class.

class MembersCog(commands.Cog):

    def __init__(self, client):
        self.client = client


    async def printfunc(self):
        print("coroutine just ran")

    @commands.command()
    async def test(self, ctx):
        print("command just ran")
        await self.printfunc()

def setup(client):
    client.add_cog(MembersCog(client))

(A bit overkill/unnecessary method, but it explains the concept) Example of calling methods within a class:

class Car:

    def __init__(self, mileage):
        self.mileage = mileage

    def add_miles(self, x):
        self.mileage += x

    def drive(self, x):
        self.add_miles(x)

And then using this class:

>>> c = Car(50)
>>> c.mileage
50
>>> c.drive(20)
>>> c.mileage
70

And if you were to change self.add_miles(x) to add_miles(x) and run the c.drive() method, it would spew a NameError exception, because it doesn't know what add_miles() is.