【发布时间】:2021-09-22 15:23:13
【问题描述】:
我最近开始尝试使用 discord.py 进行机器人开发,并且一直在努力应对某种情况,我在 Cogs 中使用常规类方法。这是一个示例,机器人应向“-hello”命令回复“hello there”:
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
class TestCog(commands.Cog):
def __init__(self):
super().__init__()
self.testMessage = "hello there"
@commands.command(name = 'hello')
async def hello(self, ctx):
await self.sayHello(ctx)
@classmethod
async def sayHello(self, ctx):
await ctx.send(self.testMessage)
token = os.getenv("botToken")
intents = discord.Intents().all()
client = discord.Client(intents = intents)
bot = commands.Bot(command_prefix='-', intents=intents)
bot.add_cog(TestCog())
if __name__ == "__main__":
bot.run(token)
如果我运行此代码,然后使用命令“-hello”,我会收到错误消息:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'TestCog' has no attribute 'testMessage'
我认为这是因为常规的类方法可能在 Cog 中不起作用,所以我也尝试这样写:
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
class TestBot(commands.Bot):
def __init__(self, command_prefix, intents):
super().__init__(command_prefix=command_prefix, intents=intents)
self.testMessage = "hello there"
self.add_cog(TestCog(self))
@classmethod
async def sayHello(self, ctx):
await ctx.send(self.testMessage)
class TestCog(commands.Cog):
def __init__(self, bot) -> None:
super().__init__()
self.bot = bot
@commands.command(name = 'hello')
async def hello(self, ctx):
await self.bot.sayHello(ctx)
token = os.getenv("botToken")
intents = discord.Intents().all()
client = discord.Client(intents = intents)
bot = TestBot('-', intents)
if __name__ == "__main__":
bot.run(token)
这也给出了同样的错误。但是,如果我不使用方法,则将其写为:
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
class TestBot(commands.Bot):
def __init__(self, command_prefix, intents):
super().__init__(command_prefix=command_prefix, intents=intents)
self.add_cog(TestCog(self))
class TestCog(commands.Cog):
def __init__(self, bot) -> None:
super().__init__()
self.testMessage = 'hello there'
@commands.command(name = 'hello')
async def hello(self, ctx):
await ctx.send(self.testMessage)
token = os.getenv("botToken")
intents = discord.Intents().all()
client = discord.Client(intents = intents)
bot = TestBot('-', intents)
if __name__ == "__main__":
bot.run(token)
它可以工作fine。它也适用于我不引用 self 的前两种情况,例如 await ctx.send('hello there') 而不是 await ctx.send(self.testMessage)。
但是,不能在命令中使用方法有点麻烦,所以我会绕过前两个场景来工作?
【问题讨论】:
-
这就是类方法的工作方式,它们无法访问实例变量。 classmethods 不用于类中的字面方法。查看 classmethod 装饰器实际上做了什么
标签: python discord discord.py