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

new9mtju  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(386)

我有一个无法解决的问题。我正在尝试为所有使用我的机器人的行会添加前缀切换器。我已经这么做了,但目前还没有触发命令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)

异步定义前缀检查(self):等待self.client.wait_直到_就绪()

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)
ddarikpa

ddarikpa1#

正如评论中提到的,你把这种方式弄得太复杂了。你的 on_guild_join 事件可以完全省略,您只需要对其进行一些调整。
另外,如果你仔细看一下,我的另一个答案会对你有所帮助。
基于此,并对您稍作调整,这里有一个可能的答案:

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

为了证明它是有效的:

相关问题