So I have my prefix setup so each guild can separately change it doing a command. I want to be able to mention the bot and it respond with "My prefix is:" but also respond to commands called using the set prefix. Currently if I add the when
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
def Mentioned_prefix(client, message):
prefix = get_prefix(client.message)
return commands.when_mentioned_or(f'{prefix}')
client = commands.Bot(command_prefix = Mentioned_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.command()
@commands.has_permissions(administrator=True)
async def setprefix(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 is now: {prefix}')
@client.event
async def on_message(message):
if client.user.mentioned_in(message):
prefix = get_prefix(client, message)
await message.channel.send(f"Prefix is:' {prefix} '")
CodePudding user response:
You should make a separate function to get a guild's prefix. You can check if a guild's id is in your 'prefixes.json' file, then return this. A further explanation can be found in the code below.
def prefix_check(guild):
# Check if this is a dm instead of a server
# Will give an error if this is not added (if guild is None)
if guild == None:
return "!"
try:
# Check if the guild id is in your 'prefixes.json'
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
p = prefixes[str(guild.id)]
except:
# Otherwise, default to a set prefix
p = "!"
# If you're confident that the guild id will always be in your json,
# feel free to remove this try-except block
return p
# on_message event
@client.event
async def on_message(message):
if client.user.mentioned_in(message):
# This is how you call the prefix_check function. It takes a guild object
await message.channel.send(f"My prefix is {prefix_check(message.guild)}")
# Don't forget to process, otherwise your commands won't work!
await client.process_commands(message)
# In a command (using ctx), do use prefix_check(ctx.guild) to get the guild's prefix