KiTTY, un bot Discord qui est un petit chat :) Il est basé sur une ancienne version du bot Red, sous Python 3.6 et qui a des fonctionnalités bien sympatiques !
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

80 lines
2.5KB

  1. import json
  2. import os
  3. import logging
  4. from random import randint
  5. class InvalidFileIO(Exception):
  6. pass
  7. class DataIO():
  8. def __init__(self):
  9. self.logger = logging.getLogger("red")
  10. def save_json(self, filename, data):
  11. """Atomically saves json file"""
  12. rnd = randint(1000, 9999)
  13. path, ext = os.path.splitext(filename)
  14. tmp_file = "{}-{}.tmp".format(path, rnd)
  15. self._save_json(tmp_file, data)
  16. try:
  17. self._read_json(tmp_file)
  18. except json.decoder.JSONDecodeError:
  19. self.logger.exception("Attempted to write file {} but JSON "
  20. "integrity check on tmp file has failed. "
  21. "The original file is unaltered."
  22. "".format(filename))
  23. return False
  24. os.replace(tmp_file, filename)
  25. return True
  26. def load_json(self, filename):
  27. """Loads json file"""
  28. return self._read_json(filename)
  29. def is_valid_json(self, filename):
  30. """Verifies if json file exists / is readable"""
  31. try:
  32. self._read_json(filename)
  33. return True
  34. except FileNotFoundError:
  35. return False
  36. except json.decoder.JSONDecodeError:
  37. return False
  38. def _read_json(self, filename):
  39. with open(filename, encoding='utf-8', mode="r") as f:
  40. data = json.load(f)
  41. return data
  42. def _save_json(self, filename, data):
  43. with open(filename, encoding='utf-8', mode="w") as f:
  44. json.dump(data, f, indent=4,sort_keys=True,
  45. separators=(',',' : '))
  46. return data
  47. def _legacy_fileio(self, filename, IO, data=None):
  48. """Old fileIO provided for backwards compatibility"""
  49. if IO == "save" and data != None:
  50. return self.save_json(filename, data)
  51. elif IO == "load" and data == None:
  52. return self.load_json(filename)
  53. elif IO == "check" and data == None:
  54. return self.is_valid_json(filename)
  55. else:
  56. raise InvalidFileIO("FileIO was called with invalid"
  57. " parameters")
  58. def get_value(filename, key):
  59. with open(filename, encoding='utf-8', mode="r") as f:
  60. data = json.load(f)
  61. return data[key]
  62. def set_value(filename, key, value):
  63. data = fileIO(filename, "load")
  64. data[key] = value
  65. fileIO(filename, "save", data)
  66. return True
  67. dataIO = DataIO()
  68. fileIO = dataIO._legacy_fileio # backwards compatibility