当我尝试在discord.py齿轮中添加普通功能时,它将弹出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))
完整错误:
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
答案 0 :(得分:1)
print_message
是一种Misc
类方法,因此您必须使用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))