将我的 python 代码迁移到 discord.py 时遇到问题。问题是,我不知道如何使用客户端。discord.py cogs 中的变量如client.sniped_messages = {}
... 它显示错误 -
Traceback (most recent call last):
File "C:\Users\arjun\Documents\Arjun\Python\discord.py\swayde\main.py", line 55, in <module>
client.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\arjun\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\arjun\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Utility' raised an error: NameError: name 'self' is not defined
这是代码 -
import discord
from discord.ext import commands
import random
import datetime
class Utility(commands.Cog):
def __init__(self, client):
self.client = client
self.client.sniped_messages = {}
@commands.Cog.listener()
async def on_message_delete(self,message):
self.client.sniped_messages[message.guild.id] = (message.content, message.author, message.channel.name, message.created_at)
@commands.command()
async def snipe(self, ctx):
try:
contents, author, channel_name, time = self.client.sniped_messages[ctx.guild.id]
except:
await ctx.channel.send("Couldn't find a message to snipe!")
return
embed = discord.Embed(description=contents, color=discord.Color.purple(), timestamp=time)
embed.set_author(name=f"{author.name}#{author.discriminator}", icon_url=author.avatar_url)
embed.set_footer(text=f"Deleted in : #{channel_name}")
await ctx.channel.send(embed=embed)
def setup(client):
client.add_cog(Utility(client))
现在,当我删除变量client.sniped_messages = {}
时,代码运行完美。
请告诉我如何解决这个问题以及如何.client
在 cogs 中使用变量。
提前致谢!