lolbot/models.py
Jonathan Harker d76ec8a3b6 Fix broken/missing URL recording and logging.
- Fix broken title lookups.
 - Respond to !command shortcuts.
 - Tidy up a bit.
2015-11-23 17:14:21 +13:00

80 lines
2.2 KiB
Python

#! /usr/bin/env python
"""
Database models for lolbot.
"""
from __future__ import print_function, unicode_literals
import requests
from datetime import datetime
from bs4 import BeautifulSoup
from sqlalchemy import (Column, String, Text, Integer, DateTime)
from sqlalchemy.ext.declarative import (declarative_base)
Model = declarative_base()
class Log(Model):
"""
This class represents an event in the log table and inherits from a SQLAlchemy
convenience ORM class.
"""
__tablename__ = "log"
id = Column(Integer, primary_key=True)
timestamp = Column(DateTime)
nickname = Column(String(20))
text = Column(Text)
def __init__(self, nickname, text, timestamp=None):
"""
Creates an event log for the IRC logger.
"""
if timestamp is None:
timestamp = datetime.now()
self.timestamp = timestamp
self.nickname = nickname
self.text = text
def __repr__(self):
return "(%s) %s: %s" % (self.timestamp.strftime("%Y-%m-%d %H:%M:%S"), self.nickname, self.text)
class Url(Model):
"""
This class represents a saved URL and inherits from a SQLAlchemy convenience
ORM class.
"""
__tablename__ = "url"
id = Column(Integer, primary_key=True)
timestamp = Column(DateTime)
nickname = Column(String(20))
url = Column(String(200), unique=True)
title = Column(Text)
def __init__(self, nickname, url, title=None, timestamp=None):
if timestamp is None:
timestamp = datetime.now()
self.timestamp = timestamp
self.nickname = nickname
self.url = url
self.title = title
# populate the title from the URL if not given.
if title is None:
r = requests.get(url)
if r.status_code == 200:
dom = BeautifulSoup(r.content, 'html.parser')
self.title = dom.title.string
else:
self.title = "Error: HTTP %s" % r.status_code
def __repr__(self):
if not self.title:
return "%s: %s" % (self.nickname, self.url)
else:
return "%s: %s - %s" % (self.nickname, self.url, self.title)