Hi. So I’m currently trying to create a Discord bot with discord.py that allows users to create events, enter a date for the event down to the minute(must be divisible by five), and select a role to ping for the event. Overall that sounds not that hard. But my usual strategy of working with .txt files won’t work, so I’m trying my hand at JSON. And that’s proving to be significantly harder. If I can figure out the baseline function, I should be able to get it connected to the Discord bot with ease.
I need Python to, every five minutes, check the events.json file to see if there is an event soon, or to clean out already executed events. Events will have the variables of “name”, “date”(in a yyyy/mm/dd/hh/mm format), “roles”(one or more roles to ping when executing the event; probably just allow for one role currently, then add support for multiple roles in the future), and “isExecuted”, which will be a boolean. If it is equal to true, then the event will be removed from the array. Here’s my code so far:
events.json
{
"events": [
{
"name": "Pizza Party",
"date": null,
"roles": null,
"isExecuted": false
},
{
"name": "The Big Meeting",
"date": null,
"roles": null,
"isExecuted": false
},
{
"name": "The Small Meeting",
"date": null,
"roles": null,
"isExecuted": true
},
{
"name": "The Medium Meeting",
"date": null,
"roles": null,
"isExecuted": false
}
]
}
main.py
import datetime
import json
from threading import Timer
# Create currentTime object
now = datetime.datetime.now()
currentTime = f"{now.year} {now.month} {now.day} {now.hour} {now.minute}"
# To reference time objects(e.g. year, month, etc.), use now.<time format>, such as now.minute
def check_for_events():
# To make life easier, the file will only be opened and closed only when the function check_for_events() is called/ran.
# Open the JSON file
with open("data.json", "r") as read_file:
data = json.load(read_file)
data_length = len(data)
# Causes task to repeat every five minutes
Timer(300, check_for_events).start()
# The actual code.
print("Checking event list...")
for events in data['events']:
x = events # When run, returns TypeError: list indices must be integers or slices, not dict
if data['events'][x]['isExecuted']:
print(data['events'][x]['name'] + ' has already been executed and will now be removed.')
continue
# Got stuck so haven't done any more code.
check_for_events()
I don’t need the file coded for me in a hand-holding way, but a push in the right direction would definitely help. Manipulating JSON with Python is a lot harder than it looks.