discord py - 自定义命令前缀不起作用(没有命令运行)

时间:2021-07-09 22:44:16

标签: python python-3.x discord.py

我有一个我无法解决的问题。我正在尝试为所有使用我的机器人的公会添加前缀切换器。所以我已经这样做了,但目前没有触发命令 get 并且几个小时以来我找不到解决方案。真的很郁闷。

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 = True

bot = 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)] = prefix

    with 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")

这就是我检查所有机器人公会是否都在前缀文件中(在另一个 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)

1 个答案:

答案 0 :(得分:1)

正如评论中提到的,你让这种方式太复杂了。您的 on_guild_join 事件可以完全省略,您只需要对其进行一些调整即可。

此外,如果您稍微看一下我的 other answer 也会对您有所帮助。

基于此并根据您的情况稍作调整,这是一个可能的答案:

TOKEN = "YourToken"

DEFAULT_PREFIX = "-" # The prefix you want everyone to have if you don't define your own

def determine_prefix(bot, msg):
    guild = msg.guild
    base = [DEFAULT_PREFIX]

    with open('prefix.json', 'r', encoding='utf-8') as fp:  # Open the JSON
        custom_prefixes = json.load(fp) # Load the custom prefixes

    if guild:  # If the guild exists
        try:
            prefix = custom_prefixes[f"{guild.id}"] # Get the prefix
            base.append(prefix) # Append the new prefix
        except KeyError:
            pass

    return base

intents = 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 file

    try:
        custom_prefixes[f"{ctx.guild.id}"] = prefixes # If the guild is in the JSON
    except KeyError:  # If no entry for the guild exists
        new = {ctx.guild.id: prefixes}
        custom_prefixes.update(new) # Add the new prefix for the guild

    await 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

为了证明它有效:

enter image description here