如何使discord.py自定义前缀系统?

时间:2020-08-19 21:26:55

标签: python discord discord.py

我想为python上的Discord机器人制作自定义前缀系统。我该怎么做?

2 个答案:

答案 0 :(得分:2)

我假设您正在谈论让每个服务器都有一个自定义前缀。如果您使用的是异步分支,我建议您这样做。在与名为prefixes.txt的.py文件相同的目录中创建文件。之后,只需使用下面的代码,其余的事情就会完成:

import discord

bot = discord.Client()

def get_prefix(guild_id):
    file = open('prefixes.txt') 
    for line in file.readlines():
        line = line.split(',')
        if(line[0] == str(guild_id)):
            return line[1]
    return '!'

@bot.event
async def on_message(message):
    prefix = get_prefix(message.guild.id)
    command = message.content.split(' ')[0].replace(prefix, '')
    if(message.content.startswith(prefix)):
        if(command == 'some_command_name'):
            #do stuff

        if(command == 'prefix'):
            file = open('prefixes.txt')
            newfile = ''
            for line in file.readlines():
                lineSplit = line.split(',')
                if(lineSplit[0] == str(message.guild.id)):
                    newfile += str(message.guild.id) + ',' + message.content.split(' ')[1]
                else:
                    newfile += line
            file = open('prefixes.txt', 'w')
            file.write(newfile)
            await message.channel.send('The prefix for this server is now `' + message.content.split(' ')[1] + '`')
                    

bot.run('token')

答案 1 :(得分:1)

创建机器人实例时,可以通过传递command_prefix参数来设置自定义前缀:

client = commands.Bot(command_prefix = "custom_prefix_here")

,如果您使用的是重写版本,则此:

client = discord.ext.commands.Bot(command_prefix = "custom_prefix_here");