как мне добавить префиксы, когда бот был оффлайн. discord.py - PullRequest
0 голосов
/ 04 августа 2020

Каждый раз, когда бот переходит в автономный режим, и кто-то добавляет его, бот не добавляет автоматически префикс с того момента, когда бот был в автономном режиме. Я не знаю, как создать что-то, чтобы автоматически добавлять это, любая идея?

я получаю эту ошибку:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 930, in on_message
    await self.process_commands(message)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 926, in process_commands
    ctx = await self.get_context(message)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 842, in get_context
    prefix = await self.get_prefix(message)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 787, in get_prefix
    ret = await discord.utils.maybe_coroutine(prefix, self, message)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\utils.py", line 317, in maybe_coroutine
    value = f(*args, **kwargs)
  File "C:\Users\Administrator\Desktop\doob\bot.py", line 16, in get_prefix
    return prefixes[str(message.guild.id)]
KeyError: '{insert server id here}

(prefix.py):

class prefix(commands.Cog):
    def __init__(self, client):
        self.client = client

    # Opens json file then dumps '-'
    @commands.Cog.listener()
    async def on_guild_join(self, 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)

    # Removes guild from json file when Doob leaves.
    @commands.Cog.listener()
    async def on_guild_remove(self, 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)

    # Changes the prefix (that the user provides.) for the specific server.
    @commands.command(aliases=['prefix'])
    @commands.has_permissions(administrator=True)
    async def changeprefix(self, 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)

        embed = discord.Embed(title="An administrator has changed the prefix.", description=f"An administrator has changed the prefix to {prefix}.", colour=discord.Color.blue())

        embed.add_field(name="The prefix has been changed to:", value=prefix)
        embed.set_thumbnail(url=doob_logo)
        await ctx.send(embed=embed)

(bot.py):

# Creates and loads the json file.
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)

Кто-то попросил мой код, так что это мой код, мне все еще нужна помощь, так что все может помочь! Спасибо заранее !!!

1 Ответ

0 голосов
/ 06 августа 2020

Я бы лично сделал это по-другому, вместо того, чтобы устанавливать префикс для каждой новой гильдии, иметь собственные префиксы только для гильдий, у которых он установлен, чтобы избежать этого. Что-то вроде этого будет делать то же самое, что и ваша сейчас, за исключением того, что оно должно обрабатывать все гильдии, поскольку это префикс запасного / стандартного

def get_prefix(client, message):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    try:
         return prefixes[str(message.guild.id)]
    except KeyError:
         return '-

...