I just started building my own Twitch Bot with Python. Now I wanted to build an voting funktion. I push the Data into an .json File because I need to access the Data from an Web-Interface to control the Voting (set Questions, activate/de-activate, Playout on the CasparCG-Server) and push it forward to my GC-Server (CasparCG) to show it on my Stream.
@bot.command(name="vote")
async def vote(ctx):
with open("poll.json", "r+") as f:
data = json.loads(f.read())
vote_active = (data['poll_active'])
vote_options = (data['vote_options']['options'])
print("json File has been read") #Debug
print("Vote Options:") #Debug
print(vote_options) #Debug
print("Vote Active:") #Debug
print(vote_active) #Debug
pollOptions = vote_options
if ctx.author.name not in pollEntrants and vote_active:
try:
vote = int(ctx.message.content.split("vote ")[1])
pollOptions[list(pollOptions.keys())[vote-1]] += 1
pollEntrants.append(ctx.author.name)
print ("I did count that!") #Debug
print(pollEntrants) #Debug
print(pollOptions) #Debug
except IndexError:
pass
else:
print ("I didnt't count that!") #Debug
print(pollEntrants) #Debug
print(pollOptions) #Debug
pass
And this is my poll.json:
{
"question": "Testquestion",
"question_desc": "Questiondescription",
"question_desc_size": "155%",
"poll_active": true,
"options": {
"option1": "Answer 1",
"option2": "Answer 2",
"option3": "Answer 3",
"option4": "Answer 4"
},
"vote_options": {
"options": {
"opt_1": 0,
"opt_2": 0,
"opt_3": 0,
"opt_4": 0
}
}
}
So first things first... the json-File handling is implemented in the voting function. To keep the Function cleaner I tried it with an get_voteopts(): Function.
def get_voteopts():
global vote_options
global vote_active
with open("poll.json") as f:
data = json.loads(f.read())
vote_active = (data['poll_active'])
vote_options = (data['vote_options']['options'])
print(vote_options)
but calling that function with "get_voteopts()" did nothing. The function gets called once and only gets called again, when I restart the script. This is bad as the json-File only gets checked once and I can't check if the File has been changed externally. But putting this directly in the vote Function does what I want.
Main Problem and the reason I am looking for help:
I want to write the collected Data back to the place in the json-File it came from. So I want my Script to update the values in the vote_options, options, opt_1, 2, 3, part of the json-File.
Can someone help me with that Issue? Maybe choosing json was bad in first place.:D If my plans are too complicated, maybe someone can suggest me another file format? XML? YAML?
Regards