如何使用齿轮实现更改前缀命令?

时间:2020-10-19 11:14:28

标签: python python-3.x discord discord.py discord.py-rewrite

首先,这是我的机器人目录。

enter image description here

现在,这是所有促进前缀更改的事件和命令的样子。

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}")

现在,我要执行此操作,但要使用齿轮(特别是bot审核齿轮)。但是我没有得到想要的东西。请帮忙。请。这是我尝试的齿轮代码。

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)下

1 个答案:

答案 0 :(得分:0)

我似乎让它起作用了。

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))