Skip to content

Instantly share code, notes, and snippets.

@4Kaylum
Created December 20, 2017 00:34
Show Gist options
  • Select an option

  • Save 4Kaylum/07da4a8d45abe0a0204f38716aa5c697 to your computer and use it in GitHub Desktop.

Select an option

Save 4Kaylum/07da4a8d45abe0a0204f38716aa5c697 to your computer and use it in GitHub Desktop.
from json import load, dump
from random import choice
class JsonDB(object):
'''
An object to handle the quotes database for you
Parameters:
filename: str
The name of the file which contains your database
'''
def __init__(self, filename:str):
self.filename = filename
self.data = None
# self.next_id -> defined as @property
# self.count -> defined as @property
try:
with open(filename) as a:
self.data = load(a)
except IOError:
self.data = {
'count': 0,
'users': [],
'next_id': 1
}
@property
def next_id(self):
'''
Gives you the next id that wil be used for a quote
'''
return self.data['next_id']
@next_id.setter
def next_id(self, new:int):
'''
Sets the next id
'''
self.data['next_id'] = new
@property
def count(self):
'''
Gives you the count from the database
'''
return self.data['count']
@count.setter
def count(self, new:int):
'''
Sets the counter
'''
self.data['count'] = new
def save_database(self):
'''
Saves the data currently stored into the given file
'''
with open(self.filename, 'w') as a:
dump(a, self.data)
def get_user(self, user_id:int, catch_error:bool=True) -> list:
'''
Gives you the quotes from a user by their Discord ID
Parameters:
user_id: int
The ID of the user to be searched for
catch_error: bool = True
Whether you want to catch the error if a user doesn't exist or not
Returns:
list
A list of the user's quotes
'''
try:
return self.data['users'][user_id]
except KeyError as e:
if not catch_error: raise e
self.data['users'][user_id] = []
self.save()
return []
def set_user(self, user_id:int, data:list):
'''
Sets a list of quotes to a specific user
Parameters:
user_id: int
The ID of the user
data: list
A list of quotes from the user
'''
self.data['users'][user_id] = data
self.save()
def add_new_quote(self, user_id:int, text:str):
'''
Adds a new quote to the database
Parameters:
user_id: int
The user whose quote list you're going to add to
text: str
The quote text you want to add
'''
# Generate the new quote
quote_id = self.next_id
quote = {
'id': quote_id,
'text': text,
}
# Add it to the current quotes
current_quotes = self.get_user(user_id)
current_quotes.append(quote)
self.set_user(user_id, current_quotes)
# Increments the counters
self.count += 1
self.next_id += 1
def get_user_quote_at_index(self, user_id:int, index:int=-1) -> dict:
'''
Gives you a quote from the user by its index in the user's quote list
If the given index doesn't exist, the newest quote will be given
If the user doesn't exist, None will be returned
Parameters:
user_id: int
The user to be searched for
index: int = -1
The index of the quote
Returns:
dict
A dictionary of the user's quote as {'id': int, 'text': str}
'''
try:
current_quotes = self.get_user(user_id)
except Exception as e:
return None
try:
return current_quotes[index]
except IndexError:
return current_quotes[-1]
def get_user_quote_at_random(self, user_id:int) -> dict:
'''
Gives you a random quote from a user, but None if that user doesn't exist
Parameters:
user_id: int
The user to be searched for
Returns:
dict
A dictionary of the user's quote as {'id': int, 'text': str}
'''
try:
current_quotes = self.get_user(user_id)
return choice(current_quotes)
except Exception as e:
return None
def get_quote_by_id(self, quote_id:int) -> dict:
'''
Gives you a quote from the database, returning None if it doesn't exist
Parameters:
quote_id: int
The quote id to be searched for
Returns:
dict
A dictionary of the quote as {'id': int, 'text': str}
'''
for user_quotes in self.data['users'].values():
for i in user_quotes:
if i['id'] == quote_id:
return i
return None
def get_random_quote(self) -> dict:
'''
Gives you a random quote from the database, returning None if no quotes exist
Returns:
dict
A dictionary of the quote as {'id': int, 'text': str}
'''
quotes = []
for user_quotes in self.data['users'].values():
quotes += user_quotes
if quotes:
return choice(quotes)
return None
'''
Changes summary
* JsonDB.js -> JsonDB.data
* JsonDB.save() -> JsonDB.save_database()
* JsonDB.get_user now takes the arguments of the user's ID, and a second optional argument, "catch_error".
This is a boolean value of whether or not to catch the KeyError raised if a user doesn't exist in the database.
It will always return the user's quotes, even if they don't have any, and even if they don't already exist in the DB.
* JsonDB.get_new_id() -> JsonDB.next_id
* JsonDB.update_quote_created() doesn't exist, and is instead replaced by "self.count += 1" and "self.next_id += 1"
* JsonDB.update_quote_deleted() -> see above
* JsonDB.add_quote() -> JsonDB.add_new_quote()
* JsonDB.get_quote_user_index() -> JsonDB.get_user_quote_at_index()
* JsonDB.get_quote_ID() -> JsonDB.get_quote_by_id()
* JsonDB.get_random_quote_user() -> JsonDB.get_user_quote_at_random()
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment