0

so right now i have a bot that will change a boolean if something is happening. Now i'm also using API to this bot, so it's not impossible that there is going to be a connection error, so what i want the bot to do is to remember if the bot already change boolean of "x" to False/True instead of the default boolean value when Exceptions occured. My code looks something like this:

def boolean():
   try:
      x = False

      if x == False:
         if a >= b:
           do = something
           x = True

      elif x == True:
         if a <= b:
           do = something
           x = False

now that's my code, so when there's connection problems, i put an Exceptions code so that the program will try and try again to run "def boolean()", so the code looks something like this:

except Exceptions as e:
      print(e)
      time.sleep(10)
      boolean()

and here is where i need helps, because if the bot already change the boolean of "x" to "True" and then there's connection error occured, and then the program restart again, then "x" will be set to default boolean value which is "False" and i don't want that to happen, so what i want is the program to remember if it already change the boolean of "x" or not. I'm stuck with this problems so i need your help.

Elan JM
  • 1
  • 2
  • Can you use an instance variable or global? – k_ssb Sep 17 '18 at 01:21
  • How can i do that, and how it works with the problems that i'm occured with right now? – Elan JM Sep 17 '18 at 01:48
  • Which line(s) in your code may raise an exception? – DYZ Sep 17 '18 at 01:55
  • @DYZ the one that check connection with the API... cause for now what i get is just a connection error. – Elan JM Sep 17 '18 at 02:08
  • Is `x` a global variable? Can someone change it while `boolean` is executed? Where is the function that you say checks the connection? I do not see it in the code that you posted. (Also, why do you call your function `boolean` when it is not a boolean function?) – DYZ Sep 17 '18 at 03:29

1 Answers1

0

You can use JSON files to save settings. Have a json file with your initial boolean setting (lets call it settings.json):

{
  "x": false
}

Then, in you code, load the json file at the start, load the boolean. Then, whenever the boolean changes, write it into the json file:

import json

with open("settings.json", "r") as jsonFile:
    data = json.load(jsonFile)

x = data["x"]

.... blah blah code
....
# Modifying x
x = True
data["x"] = x

with open("settings.json", "w") as jsonFile:
    json.dump(data, jsonFile)
bunbun
  • 2,595
  • 3
  • 34
  • 52
  • Apologies, I have to rush somewhere now, so the code is untested. You can follow here if needed: https://stackoverflow.com/questions/13949637/how-to-update-json-file-with-python – bunbun Sep 17 '18 at 03:39