Python 如何使用cogs实现更改前缀命令?
首先,这是我的机器人目录 现在,所有用于促进前缀更改的事件和命令都是这样的Python 如何使用cogs实现更改前缀命令?,python,python-3.x,discord,discord.py,discord.py-rewrite,Python,Python 3.x,Discord,Discord.py,Discord.py Rewrite,首先,这是我的机器人目录 现在,所有用于促进前缀更改的事件和命令都是这样的 def get_prefix(client, message): with open("./prefixes_data.json", "r") as f: prefixes = json.load(f) return prefixes[str(message.guild.id)] client = commands.Bot(command_pr
def get_prefix(client, message):
with open("./prefixes_data.json", "r") as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
client = commands.Bot(command_prefix = get_prefix)
@client.event
async def on_ready():
print('bot ready hai')
@client.event
async def on_guild_join(guild):
with open("./prefixes_data.json", "r") as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = "!" # default value, implemented when bot joins for the first time
with open("./prefixes_data.json", "w") as f:
json.dump(prefixes, f, indent=4)
@client.event
async def on_guild_remove(guild):
with open("./prefixes_data.json", "r") as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open("./prefixes_data.json", "w") as f:
json.dump(prefixes, f, indent=4)
命令
@client.command()
async def changeprefix(ctx, new_prefix):
with open("./prefixes_data.json", "r") as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = new_prefix
with open("./prefixes_data.json", "w") as f:
json.dump(prefixes, f, indent=4)
ctx.send(f"Changed the prefix to: {new_prefix}")
现在,我想这样做,但使用cog(特别是bot调节cog)。但我没有得到想要的东西。请帮忙。请这是我试过的齿轮代码
import discord
from discord.ext import commands
import json
class botmodcoms(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command
async def changeprefix(self, ctx, new_prefix):
with open("../prefixes_data.json", "r") as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = new_prefix
with open("../prefixes_data.json", "w") as f:
json.dump(prefixes, f, indent=4)
def setup(client):
client.add_cog(botmodcoms(client))
我想要的是所有事件都应该在主bot.py文件中,并且该命令位于cog文件(BotModeration)下。我似乎已经让它工作了
import discord
from discord.ext import commands
import json
class Config(commands.Cog, name="Configuration"):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print(f"{self.__class__.__name__} Cog has been loaded\n-----")
@commands.command()
async def prefix(self, ctx, new_prefix):
with open("./prefixes.json", "r") as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = new_prefix
with open("./prefixes.json", "w") as f:
json.dump(prefixes, f, indent=4)
def setup(bot):
bot.add_cog(Config(bot))
当说“这在Cogs中不起作用”时,它有助于发布您尝试的代码,以便我们能够识别问题。你能显示Cog的代码吗?你想做什么?@stijndcl当然,等一下,你是否正在主bot.py文件中加载Cog?我没有看到你在任何地方这样做。这可能是个愚蠢的问题,但也可能是答案。@stijndcl是的,我已将cog加载到主bot.py文件中。