ameliabot/plugins/quote.py

74 lines
1.8 KiB
Python
Raw Permalink Normal View History

from datetime import datetime, timezone
import random
import sqlite3
"""
This is a really, really rough plugin and needs to be redone.
"""
def insert(owner, submitter, text):
conn = __connect()
text = text.replace("'", "''")
conn.execute('''
INSERT INTO quotes (submitter, text, timestamp)
VALUES ('{}', '{}', {})'''.format(
submitter, text, datetime.now().replace(tzinfo=timezone.utc)))
def get(arg=None):
conn = __connect()
num_quotes = __get_num_quotes()
if arg:
ret = "SELECT id, text, timestamp FROM quotes WHERE "
try:
if int(arg) > num_quotes:
return "No quote matching that number."
ret += "id = %s" % arg
except ValueError:
ret += "text like '%{}%'".format(arg.lower())
quote = conn.execute(ret)
return __format(list(quote.fetchone()))
else:
return get(random.randint(0, num_quotes))
def __get_num_quotes():
conn = __connect()
try:
num = conn.execute("SELECT COUNT(id) FROM quotes")
except sqlite3.OperationalError:
return 0
return int(num.fetchone()[0])
def __format(quote):
num, text, timestamp = quote
timestamp = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f%z')
return "{}. {}, {}".format(
num, text, datetime.strftime(timestamp, '%Y'))
def __connect():
return sqlite3.connect("data/quote.db")
def __init_table():
try:
conn = __connect()
except sqlite3.OperationalError:
import os
os.makedirs("data")
__init_table()
conn.execute('''
CREATE TABLE IF NOT EXISTS quotes (
id INTEGER PRIMARY KEY, submitter TEXT,
text TEXT, timestamp TEXT
)''')
def run(arg=None):
__init_table()
return get(arg)