remind now actually uses the bot's database

This commit is contained in:
iou1name 2018-03-02 21:25:50 -05:00
parent 0723754012
commit e013a50711
6 changed files with 82 additions and 37 deletions

2
.gitignore vendored
View File

@ -1,11 +1,11 @@
__pycache__/ __pycache__/
*/__pycache__/ */__pycache__/
logs/ logs/
modules_old/
default.cfg default.cfg
*.db *.db
*.pid *.pid
*.dat *.dat
*.txt *.txt
*.swp
tourettes.py tourettes.py

View File

@ -3,6 +3,8 @@
""" """
Long live the Internet of Things! Long live the Internet of Things!
""" """
import time
import requests import requests
import module import module
@ -34,6 +36,8 @@ def roomTemp(bot, trigger):
""" """
try: try:
res = requests.get("http://192.168.1.25/", timeout=10) res = requests.get("http://192.168.1.25/", timeout=10)
time.sleep(0.5)
res = requests.get("http://192.168.1.25/", timeout=10)
except requests.exceptions.ReadTimeout: except requests.exceptions.ReadTimeout:
return bot.say("Connection error. Timeout reached.") return bot.say("Connection error. Timeout reached.")
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:

View File

@ -5,15 +5,14 @@ Reminds of things.
import os import os
import re import re
import time import time
import sqlite3
import threading import threading
import collections import collections
import codecs from datetime import datetime
import pytz import pytz
from datetime import datetime
from module import commands, example, NOLIMIT from module import commands, example, NOLIMIT
import tools
from tools.time import get_timezone, format_time from tools.time import get_timezone, format_time
def filename(self): def filename(self):
@ -21,37 +20,77 @@ def filename(self):
return os.path.join(self.config.core.homedir, name) return os.path.join(self.config.core.homedir, name)
def load_database(name): def init_database(bot):
"""
Initializes the 'remind' table in the bot's database. Does nothing if
the table already exists.
"""
con = bot.db.connect()
cur = con.cursor()
try:
cur.execute("SELECT * FROM remind").fetchone()
except sqlite3.OperationalError:
cur.execute("CREATE TABLE remind("
"unixtime INT DEFAULT (STRFTIME('%s', 'now')),"
"channel STRING,"
"nick STRING,"
"message STRING)")
con.commit()
con.close()
def load_database(bot):
"""
Loads all entries from the 'remind' table in the bot's database and
stores them in memory
"""
data = {} data = {}
if os.path.isfile(name): con = bot.db.connect()
f = codecs.open(name, 'r') cur = con.cursor()
for line in f: reminds = cur.execute("SELECT * FROM remind").fetchall()
unixtime, channel, nick, message = line.split('\t') con.close()
message = message.rstrip('\n')
t = int(float(unixtime)) # WTFs going on here? for remind in reminds:
reminder = (channel, nick, message) unixtime, channel, nick, message = remind
try: reminder = (channel, nick, message)
data[t].append(reminder) try:
except KeyError: data[unixtime].append(reminder)
data[t] = [reminder] except KeyError:
f.close() data[unixtime] = [reminder]
return data return data
def dump_database(name, data): def insert_reminder(bot, unixtime, reminder):
f = codecs.open(name, 'w', encoding='utf-8') """
for unixtime, reminders in tools.iteritems(data): Inserts a new reminder into the 'remind' table in the bot's database.
for channel, nick, message in reminders: reminder - a tuple containing (channel, nick, message)
f.write('%s\t%s\t%s\t%s\n' % (unixtime, channel, nick, message)) """
f.close() con = bot.db.connect()
cur = con.cursor()
cur.execute("INSERT INTO remind (unixtime, channel, nick, message) "
"VALUES(?,?,?,?)", (unixtime,) + reminder)
con.commit()
con.close()
def delete_reminder(bot, unixtime):
"""
Deletes a reminder from the 'remind' table in the bot's database, using
unixtime as the key.
"""
con = bot.db.connect()
cur = con.cursor()
cur.execute("DELETE FROM remind WHERE unixtime = ?", (unixtime,))
con.commit()
con.close()
def setup(bot): def setup(bot):
bot.rfn = filename(bot) init_database(bot)
bot.rdb = load_database(bot.rfn) bot.rdb = load_database(bot)
def monitor(bot): def monitor(bot):
time.sleep(5) time.sleep(10)
while True: while True:
now = int(time.time()) now = int(time.time())
unixtimes = [int(key) for key in bot.rdb] unixtimes = [int(key) for key in bot.rdb]
@ -64,7 +103,7 @@ def setup(bot):
else: else:
bot.say(nick + '!', channel) bot.say(nick + '!', channel)
del bot.rdb[oldtime] del bot.rdb[oldtime]
dump_database(bot.rfn, bot.rdb) delete_reminder(bot, oldtime)
time.sleep(2.5) time.sleep(2.5)
targs = (bot,) targs = (bot,)
@ -207,7 +246,7 @@ def create_reminder(bot, trigger, duration, message, tz):
except KeyError: except KeyError:
bot.rdb[t] = [reminder] bot.rdb[t] = [reminder]
dump_database(bot.rfn, bot.rdb) insert_reminder(bot, t, reminder)
if duration >= 60: if duration >= 60:
remind_at = datetime.utcfromtimestamp(t) remind_at = datetime.utcfromtimestamp(t)

View File

@ -6,6 +6,7 @@ through them.
import os import os
import threading import threading
import random import random
import sqlite3
from module import commands, example from module import commands, example
@ -18,13 +19,13 @@ def setup(bot):
cur = con.cursor() cur = con.cursor()
try: try:
cur.execute("SELECT * FROM topic").fetchone() cur.execute("SELECT * FROM topic").fetchone()
except: except sqlite3.OperationalError:
cur.execute("CREATE TABLE topic(" cur.execute("CREATE TABLE topic("
"topic STRING PRIMARY KEY," "topic STRING PRIMARY KEY,"
"added_by STRING," "added_by STRING,"
"added_date INT DEFAULT (STRFTIME('%s', 'now')))") "added_date INT DEFAULT (STRFTIME('%s', 'now')))")
con.commit() con.commit()
con.close() con.close()
@commands('topic') @commands('topic')
@ -48,8 +49,10 @@ def addTopic(bot, trigger):
""" """
Adds the specified topic to the topic database. Adds the specified topic to the topic database.
""" """
bot.memory['topic_lock'].acquire()
topic = trigger.group(2) 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() con = bot.db.connect()
cur = con.cursor() cur = con.cursor()
insert = (topic, trigger.nick) insert = (topic, trigger.nick)

View File

@ -28,7 +28,6 @@ def setup(bot):
"time_since STRING," "time_since STRING,"
"channel STRING)") "channel STRING)")
cur.commit() cur.commit()
con.close()
else: else:
for thread in watching: for thread in watching:
if get_thread_url(thread[0]) in bot.memory["watcher"].keys(): if get_thread_url(thread[0]) in bot.memory["watcher"].keys():
@ -37,7 +36,7 @@ def setup(bot):
thread[4]) thread[4])
t.start() t.start()
bot.memory["watcher"][get_thread_url(thread[0])] = t bot.memory["watcher"][get_thread_url(thread[0])] = t
con.close() con.close()
def get_time(): def get_time():

View File

@ -168,10 +168,10 @@ def relativeTime(bot, nick, telldate):
if timediff.days: if timediff.days:
if timediff.days // 365: if timediff.days // 365:
reltime.append( str(timediff.days // 365) + " year" ) reltime.append( str(timediff.days // 365) + " year" )
if timediff.days % 365 // 30: if timediff.days % 365 // (365/12):
reltime.append( str(timediff.days % 365 // 30.416).partition(".")[0] + " month") reltime.append( str(timediff.days % 365 // (365/12)).partition(".")[0] + " month")
if timediff.days % 365 % 30: if timediff.days % 365 % (365/12):
reltime.append( str(timediff.days % 365 % 30.416).partition(".")[0] + " day") reltime.append( str(timediff.days % 365 % (365/12)).partition(".")[0] + " day")
else: else:
if timediff.seconds // 3600: if timediff.seconds // 3600: