Z
Z
Zakkaru2022-01-06 16:12:02
Python
Zakkaru, 2022-01-06 16:12:02

How can I transfer the command to json?

I have a ready command, but I have no idea how to transfer to json? For I often restart the bot and so that the list is constantly active

@client.event
async def on_message(message):
    global afk_users
    if message.author.bot:
        return

    # выход пользователя из афк
    if str(message.author.id) in afk_users.keys():
        afk_users.pop(str(message.author.id)) 
        await message.reply("Вы покинули AFK!!!", delete_after=15)

    # проверка, является ли сообщение командой
    await client.process_commands(message)

    # проверка, находится ли пользователь в афк
    for member in message.mentions:
        if str(member.id) in afk_users.keys():
            reason = '*без причины*' if afk_users[str(member.id)] is None else afk_users[str(member.id)]
            await message.delete()
            await message.channel.send(f'Пользователь {member} сейчас в AFK режиме пр причине: __{reason}__', delete_after=15)
            return

@client.command()
async def afk(ctx,*, reason=None):
  with open('afk_users.json', 'w', encoding='utf-8') as file:
    file.write(json.dumps(afk_users, indent=4, ensure_ascii=False))
    file.close()
  afk_users[str(ctx.author.id)] = reason
  await ctx.reply(f"Вы ввошли в AFK режим по причине: __{reason}__", delete_after=15)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2022-01-06
@Zakkaru

Zakkaru so that the bot saves the state of the afk_users variable to a json file? Well, I would say so.
Well then, you have written a lot of nonsense ... well, at least here.

with open('afk_users.json', 'w', encoding='utf-8') as file:
    file.write(json.dumps(afk_users, indent=4, ensure_ascii=False))
    file.close()

First, the with statement itself will call file.close() at the end.
Secondly, it could have been easier - json.dump(afk_users, file, indent=4, ensure_ascii=False). Pay attention, not dumps(), but dump().
with open('afk_users.json', 'w', encoding='utf-8') as file:
    json.dump(afk_users, file, indent=4, ensure_ascii=False))

Thirdly, why do you save the state of the afk_users variable and then change it immediately? Maybe it's the other way around?
Fourth, where are you loading the afk_users state from a file? It should be done when the bot starts, for example inside on_ready.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question