'Discord Python Bot, auto-unban after given time, how do I save the time until a user gets unbanned even if the bot goes offline?

I'm making a discord bot in python, and want to add a temporary ban command. The only problem is that if the bot goes offline (power outage, altering code, ect...) the time until the user(s) get unbanned is reset, and they stay banned forever (unless staff unbans them). How do I make it so the bot saves the ban time incase it goes offline? Here is my code so far:

@client.command()
@commands.has_any_role("Admin", "Server Owner")
async def ban(ctx, member : discord.Member, *, reason=None):
  await member.ban(reason=reason)
  await ctx.channel.send(f'A user was banned.')
  id = ctx.author.id
  user = client.get_user(id)
  await user.send(f'You were banned from this server by {user}.\nReason: {reason}.')

Anyone have ideas as to how I could do this? Thanks!



Solution 1:[1]

You will need to create a .json file that stores the member's id and the time that they should be unbanned. This can be accomplished by the json module provided by Python. The reason for the use of json rather than pickle is that json provides data that can be read by humans rather than pickle's rather strange way of storing data.

import json

#Loads .json file
with open(file_name, "r") as file:
    bans = json.load(file)

#Saves data to .json file
with open(file_name, "w") as file:
    json.dump(new_data)

Whenever your ban command is called, open the .json file and add the member's id and the time to unban them at. I personally use a dictionary, but you can go for whatever structure you want.

Just know that there could be errors that occur when using json, for example when you're trying to load an empty file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom The Cat