Reputation: 108
I want to implement custom prefixes per server as, well as a permanent prefix which is bot mention, which means people can use like default prefix .
as well as @bot
and the prefixes are stored in json file.
Here is my current code:
with open("prefixes.json") as f:
prefixes = json.load(f)
default_prefix = "."
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
client = commands.Bot(
command_prefix= (get_prefix),
intents=intents
)
@client.event
async def on_guild_join(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = '.'
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
@client.event
async def on_guild_remove(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
@client.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def prefix(ctx, prefix):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
await ctx.send(f'`Prefix changed to:` {prefix}')
I tried to find a way and tried the way below and it threw errors. Any help will be appreciated.
client = commands.Bot(
command_prefix= [(get_prefix), '<@!123>'],
intents=intents
)
json file format:
{
"121212121212121221": "-",
"121212121212121222": "-",
"121212121212121223": "!",
"121212121212121224": "-",
"121212121212121225": "."
}
Upvotes: 1
Views: 786
Reputation: 2907
This is an improved version
def get_prefix(client, message):
prefix = default_prefix
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefix = prefixes[str(message.guild.id)]
return commands.when_mentioned_or(prefix)(client, message)
client = commands.Bot(command_prefix=get_prefix, case_insensitive=True, intents=intents)
Upvotes: 1