Facts: refactoring; move the database querying into its own method (for reuse)
This commit is contained in:
parent
e16d698d0e
commit
71688f2389
@ -78,24 +78,40 @@ class Facts(Module):
|
|||||||
if match:
|
if match:
|
||||||
category = match.group(1)
|
category = match.group(1)
|
||||||
regex = match.group(2)
|
regex = match.group(2)
|
||||||
category_facts = cur.execute('SELECT * FROM facts_facts WHERE category=? AND fact REGEXP ?', (category, regex))
|
return self.reply(connection, event, self._get_fact(category, regex))
|
||||||
facts = category_facts.fetchall()
|
|
||||||
if len(facts) > 0:
|
|
||||||
fact = facts[random.randint(1,len(facts))-1]
|
|
||||||
return self.reply(connection, event, fact['fact'].rstrip().encode('utf-8', 'ignore'))
|
|
||||||
|
|
||||||
match = re.search('^!facts\s+(\S+)$', what)
|
match = re.search('^!facts\s+(\S+)$', what)
|
||||||
if match:
|
if match:
|
||||||
category = match.group(1)
|
category = match.group(1)
|
||||||
category_facts = cur.execute('SELECT * FROM facts_facts WHERE category=?', (category,))
|
return self.reply(connection, event, self._get_fact(category))
|
||||||
facts = category_facts.fetchall()
|
|
||||||
if len(facts) > 0:
|
|
||||||
fact = facts[random.randint(1,len(facts))-1]
|
|
||||||
return self.reply(connection, event, fact['fact'].rstrip().encode('utf-8', 'ignore'))
|
|
||||||
db.close()
|
db.close()
|
||||||
except sqlite3.Error as e:
|
except sqlite3.Error as e:
|
||||||
db.close()
|
db.close()
|
||||||
return self.reply(connection, event, "sqlite error: " + str(e))
|
return self.reply(connection, event, "sqlite error: " + str(e))
|
||||||
|
|
||||||
|
def _get_fact(self, category, search=""):
|
||||||
|
"""Get a fact in the given category from the database."""
|
||||||
|
|
||||||
|
try:
|
||||||
|
db = self.get_db()
|
||||||
|
cur = db.cursor()
|
||||||
|
|
||||||
|
if search == "":
|
||||||
|
category_facts = cur.execute("SELECT * FROM facts_facts WHERE category=?", (category,))
|
||||||
|
facts = category_facts.fetchall()
|
||||||
|
db.close()
|
||||||
|
else:
|
||||||
|
category_facts = cur.execute("SELECT * FROM facts_facts WHERE category=? AND fact REGEXP ?",
|
||||||
|
(category, search))
|
||||||
|
facts = category_facts.fetchall()
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
if len(facts) > 0:
|
||||||
|
fact = facts[random.randint(1,len(facts))-1]
|
||||||
|
return fact['fact'].rstrip().encode('utf-8', 'ignore')
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
db.close()
|
||||||
|
return self.reply(connection, event, "sqlite error in _get_fact: " + str(e))
|
||||||
|
|
||||||
# vi:tabstop=4:expandtab:autoindent
|
# vi:tabstop=4:expandtab:autoindent
|
||||||
# kate: indent-mode python;indent-width 4;replace-tabs on;
|
# kate: indent-mode python;indent-width 4;replace-tabs on;
|
||||||
|
Loading…
Reference in New Issue
Block a user