JanuZz_dk
JanuZz_dk

Reputation: 120

Normal function declaring doesn't work in a discord.py cog

When i try yo add a normal function in my discord.py cog it will pop up not defined

bot.py

import discord
from discord.ext import commands
import os

token = You cant have it
prefix = "."

client = commands.Bot(command_prefix=prefix)

@client.event
async def on_ready():
    print(f"{client.user.name} is ready!")

for filename in os.listdir("./commands"):
    if filename.endswith(".py"):
        client.load_extension(f"commands.{filename[:-3]}")
        print(f"loaded: {filename[:-3]}")

client.run(token)

cog.py

import discord
from discord.ext import commands

class Misc(commands.Cog):

    def __init__(self, client):
        self.client = client
    
    def print_message(self,message):
        print(f"New message received!\nAuthor: {message.author}\nContent: {message.content}\n----------")

    @commands.Cog.listener()
    async def on_message(self,message):
        print_message(message)

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

Full error:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Jlp02\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "E:\Discord Bots\Mike\commands\Misc.py", line 15, in on_message
    print_message(message)
NameError: name 'print_message' is not defined
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "hi" is not found
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Jlp02\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "E:\Discord Bots\Mike\commands\Misc.py", line 15, in on_message
    print_message(message)
NameError: name 'print_message' is not defined

Upvotes: 0

Views: 355

Answers (1)

MrSpaar
MrSpaar

Reputation: 3994

print_message is a Misc class method so you have to call it using self.print_message(message):

import discord
from discord.ext import commands

class Misc(commands.Cog):

    def __init__(self, client):
        self.client = client
    
    def print_message(self,message):
        print(f"New message received!\nAuthor: {message.author}\nContent: {message.content}\n----------")

    @commands.Cog.listener()
    async def on_message(self,message):
        self.print_message(message)

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

Upvotes: 1

Related Questions