Reputation: 3
I want to make custom prefixes system for my discord bot on python. How can I make it?
Upvotes: 0
Views: 2495
Reputation: 336
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')
Upvotes: 2
Reputation: 1427
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");
Upvotes: 1