简体   繁体   中英

How to make discord.py custom prefixes system?

I want to make custom prefixes system for my discord bot on python. How can I make it?

I assume you are talking about letting each server have a custom prefix. If you are using the async branch, I would suggest this. Make a file in the same directory as your.py file named prefixes.txt . After that, just use this code, and it will do the rest:

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

You can set a custom prefix by passing a command_prefix argument when creating an instance of your bot:

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

or this if you're using the rewrite version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM