discord py - Custom command prefix doesnt work (no command run)

2024/11/16 2:47:27

i have a problem that i can't solve. I'm trying to add a prefix switcher for all guilds, that uses my bot. So I've done that, but currently no command get's triggered and I can't find a solution since hours. Its really frustrating.

import os
import json
import discord.ext
from discord.ext import commands#from discord_slash import SlashCommand, SlashContext
#from discord_slash.utils.manage_commands import create_option, create_choice# Prefix-Wechsler
def get_prefix(client, message):with open("prefix.json", "r") as f:prefix = json.load(f)return prefix(str(message.guild.id))##### Wichtige Bot-Einstellungen ######
intents = discord.Intents().default()
intents.members = Truebot = commands.Bot(command_prefix=str(get_prefix), intents=intents)
bot.remove_command('help')# slash = SlashCommand(bot, override_type = True, sync_on_cog_reload=True, sync_commands=True)### Server-Join ###
@bot.event
async def on_guild_join(guild):with open("prefix.json", "r") as f:prefix = json.load(f)prefix[str(guild.id)] = "="with open("prefix.json", "w") as f:json.dump(prefix, f)### Aktionen für den Bot-Start ###
@bot.event
async def on_ready():print('  ____  _ _  _       _    _ _     _   ')print(' |  _ \| | || |     | |  | (_)   | |  ')print(' | |_) | | || |_ ___| | _| |_ ___| |_ ')print(' |  _ <| |__   _/ __| |/ / | / __| __|')print(' | |_) | |  | || (__|   <| | \__ \ |_ ')print(' |____/|_|  |_| \___|_|\_\_|_|___/\__|')print('                                      ')print(f'Entwickelt von Yannic | {bot.user.name}')print('────────────')# Prefix-Wechsler
@bot.command(aliases=["changeprefix", "Setprefix", "Changeprefix"])
@commands.has_permissions(administrator=True)
@commands.bot_has_permissions(read_messages=True, read_message_history=True, send_messages=True, attach_files=True, embed_links=True)
async def setprefix(ctx, prefix):if prefix is None:return await ctx.reply('› `📛` - **Prefix vergessen**: Du hast vergessen, einen neuen Prefix anzugeben! <a:pepe_delete:725444707781574737>')with open("prefix.json", "r") as f:prefixes = json.load(f)prefixes[str(ctx.guild.id)] = prefixwith open("prefix.json", "w") as f:json.dump(prefixes, f)await ctx.reply(f'› Mein Bot-Prefix wurde erfolgreich auf `{prefix}` geändert! <a:WISCHEN_2:860466698566107149>')def load_all():for filename in os.listdir('./cogs'):if filename.endswith('.py'):bot.load_extension(f'cogs.{filename[:-3]}')load_all()bot.run("TOKEN")

And that's my task for checking if all bot guilds are in the prefix file (in another cog):

@tasks.loop(minutes=10)

async def prefix_check(self): await self.client.wait_until_ready()

        for guild in self.client.guilds:with open("prefix.json", "r") as f:prefix = json.load(f)if guild.id not in prefix:prefix[str(guild.id)] = "="with open("prefix.json", "w") as f:json.dump(prefix, f)
Answer

As mentioned in the comments, you are making this way too complicated. Your on_guild_join event can be omitted completely, you just need to make some adjustments for it.

Also, my other answer would have helped you if you had looked at it a bit.

Based on that and adapted a bit to you here is a possible answer:

TOKEN = "YourToken"DEFAULT_PREFIX = "-" # The prefix you want everyone to have if you don't define your owndef determine_prefix(bot, msg):guild = msg.guildbase = [DEFAULT_PREFIX]with open('prefix.json', 'r', encoding='utf-8') as fp:  # Open the JSONcustom_prefixes = json.load(fp) # Load the custom prefixesif guild:  # If the guild existstry:prefix = custom_prefixes[f"{guild.id}"] # Get the prefixbase.append(prefix) # Append the new prefixexcept KeyError:passreturn baseintents = discord.Intents.all() # import all intents if enabled
bot = commands.Bot(command_prefix=determine_prefix, intents=intents) # prefix is our function@bot.command()
async def setprefix(ctx, prefixes: str):with open('prefix.json', 'r', encoding='utf-8') as fp:custom_prefixes = json.load(fp) # load the JSON filetry:custom_prefixes[f"{ctx.guild.id}"] = prefixes # If the guild is in the JSONexcept KeyError:  # If no entry for the guild existsnew = {ctx.guild.id: prefixes}custom_prefixes.update(new) # Add the new prefix for the guildawait ctx.send(f"Prefix wurde zu `{prefixes}` geändert.")with open('prefix.json', 'w', encoding='utf-8') as fpp:json.dump(custom_prefixes, fpp, indent=2) # Change the new prefix

To show that it works:

enter image description here

https://en.xdnf.cn/q/119246.html

Related Q&A

How to use sep parameter in .format?

I just started learning python and Im experimenting new things. isim = input("Name:") soyad = input("Surname:") yaş = input("Age:") edu = input("Education:") ge…

Python table classification

I have different type of data for example:4.5,3.5,U1 4.5,10.5,U2 4.5,6,U1 3.5,10.5,U2 3.5,10.5,U2 5,7,U1 7,6.5,U1I need output:U1: [[4.5, 3.5], [4.5, 6], [5, 7], [7, 6.5]] U2: [[4.5, 10.5], [3.5, 10.5]…

python json.loads / json.load truncates nested json objects?

given the following code: import json foo = {"root":"cfb-score","children":{"gamecode":{"attribute":"global-id"},"gamestate":{&quo…

How to make an encrypted executable file

I have made a tool/program on Ubuntu written in Python. I want to give this to my friend to test on his PC, but I dont want to share the source code.This program has many folders and many .py files. Is…

Organizing pythonic dictionaries for a JSON schema validation

Scenario: I am trying to create a JSON schema validator in python. In this case, I am building a dictionary which contain the information that will be used for the validation.Code:import json import os…

Scraping a specific website with a search box and javascripts in Python

On the website https://sray.arabesque.com/dashboard there is a search box "input" in html. I want to enter a company name in the search box, choose the first suggestion for that name in the d…

Uppercasing letters after ., ! and ? signs in Python

I have been searching Stack Overflow but cannot find the proper code for correcting e.g."hello! are you tired? no, not at all!"Into:"Hello! Are you tired? No, not at all!"

Why does list() function is not letting me change the list [duplicate]

This question already has answers here:How do I clone a list so that it doesnt change unexpectedly after assignment?(24 answers)Python pass by value with nested lists?(1 answer)Closed 2 years ago.If …

How can I explicitly see what self does in python?

Ive read somewhere that the use of ‘self’ in Python converts myobject.method (arg1, arg2) into MyClass.method(myobject, arg1, arg2). Does anyone know how I can prove this? Is it only possible if I…

Recieve global variable (Cython)

I am using Cython in jupyter notebook. As I know, Cython compiles def functions.But when I want to call function with global variable it doesnt see it. Are there any method to call function with variab…