如何获取可自定义的前缀discord.py

时间:2020-10-24 13:13:09

标签: discord.py discord.py-rewrite

假设我不想将自己限制为一个前缀,而是使用命令将前缀更改为我要使用的每个服务器的前缀。

基本上,首先会有一个默认前缀,例如bl!,如果还有另一个带有该前缀的漫游器,我可以做类似bl!prefix ...的操作。这样,机器人就可以读取给定的文本文件或json,根据公会编辑前缀,并与该公会和仅与该公会一起使用。

1 个答案:

答案 0 :(得分:1)

第1步-设置json文件: 首先,您需要制作一个json文件。该文件将存储message.guild.id的信息以及该行会的前缀。在下面的图片中,您将在将json文件添加到多个服务器后看到它。如果您的机器人已经在大量服务器中,则可能需要手动添加它们,然后才能拥有自动系统。 A bot I used with a custom prefix

第2步-定义get_prefix :在设置discord.py机器人时,通常会遇到一行代码,指出该机器人的command_prefix。要具有自定义前缀,您首先需要定义get_prefix,它将从您之前创建的json文件中读取。

def get_prefix(client, message): ##first we define get_prefix
    with open('prefixes.json', 'r') as f: ##we open and read the prefixes.json, assuming it's in the same file
        prefixes = json.load(f) #load the json as prefixes
    return prefixes[str(message.guild.id)] #recieve the prefix for the guild id given

第3步-您的漫游器command_prefix :这是为了确保您的漫游器具有前缀。而不是使用command_prefix = "bl!",而是使用先前定义的get_prefix

client = commands.Bot(
    command_prefix= (get_prefix),
    )

第4步-加入和离开服务器:所做的只是操作prefixes.json

@client.event
async def on_guild_join(guild): #when the bot joins the guild
    with open('prefixes.json', 'r') as f: #read the prefix.json file
        prefixes = json.load(f) #load the json file

    prefixes[str(guild.id)] = 'bl!'#default prefix

    with open('prefixes.json', 'w') as f: #write in the prefix.json "message.guild.id": "bl!"
        json.dump(prefixes, f, indent=4) #the indent is to make everything look a bit neater

@client.event
async def on_guild_remove(guild): #when the bot is removed from the guild
    with open('prefixes.json', 'r') as f: #read the file
        prefixes = json.load(f)

    prefixes.pop(str(guild.id)) #find the guild.id that bot was removed from

    with open('prefixes.json', 'w') as f: #deletes the guild.id as well as its prefix
        json.dump(prefixes, f, indent=4)

第5步-更改前缀命令

@client.command(pass_context=True)
@has_permissions(administrator=True) #ensure that only administrators can use this command
async def changeprefix(ctx, prefix): #command: bl!changeprefix ...
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(ctx.guild.id)] = prefix

    with open('prefixes.json', 'w') as f: #writes the new prefix into the .json
        json.dump(prefixes, f, indent=4)

    await ctx.send(f'Prefix changed to: {prefix}') #confirms the prefix it's been changed to
#next step completely optional: changes bot nickname to also have prefix in the nickname
    name=f'{prefix}BotBot'

client.run("TOKEN")