sopel/modules/topic.py

69 lines
1.6 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
"""
This module allows you to add topics to a list in the database and cycle
through them.
"""
import os
import threading
import random
import sqlite3
from module import commands, example
def setup(bot):
"""
Attempts to create the table in the database if it's not found.
"""
bot.memory['topic_lock'] = threading.Lock()
con = bot.db.connect()
cur = con.cursor()
try:
cur.execute("SELECT * FROM topic").fetchone()
except sqlite3.OperationalError:
cur.execute("CREATE TABLE topic("
"topic STRING PRIMARY KEY,"
"added_by STRING,"
"added_date INT DEFAULT (STRFTIME('%s', 'now')))")
con.commit()
con.close()
@commands('topic')
def topic(bot, trigger):
"""
Picks a random topic from the database and applies it.
"""
channel = trigger.sender
con = bot.db.connect()
cur = con.cursor()
cur.execute("SELECT topic FROM topic ORDER BY RANDOM() LIMIT 1;")
topic = cur.fetchone()[0]
con.close()
bot.write(('TOPIC', channel + ' :' + topic))
@commands('addtopic')
@example('.addtopic Daily reminder to kill all cia niggers on site.')
def addTopic(bot, trigger):
"""
Adds the specified topic to the topic database.
"""
topic = trigger.group(2)
if not topic:
return bot.say("Please be providing a topic sir.")
bot.memory['topic_lock'].acquire()
con = bot.db.connect()
cur = con.cursor()
insert = (topic, trigger.nick)
try:
cur.execute("INSERT INTO topic (topic, added_by) VALUES(?,?)",
insert)
confirm = "Added topic: " + topic
except sqlite3.IntegrityError:
confirm = "Error: " + topic + " is already in the database."
con.commit()
con.close()
bot.memory['topic_lock'].release()
bot.say(confirm)