Added the irclog django project
[pyIRCbot.git] / plugins / django_log_plugin.py
blobbef062a2815e6447bb7e64d1bc984f46f2e9fab3
1 import sqlalchemy as sql
2 from time import strftime
4 # for more info see
5 # http://www.sqlalchemy.org/docs/04/intro.html#overview_sqlalchemy
6 DATABASE_PATH = "sqlite://../../django/irclog/django_sqlite3_database.db"
8 class _DatabaseConnection(object):
9 """Connect to database.
10 Class name starts with `_` becouse it's not a plugin - it's privete class
11 and it shouldn't be loaded
12 """
13 def __init__(self, dblink):
14 """Create database connection"""
15 self.database = sql.create_engine(dblink)
16 metadata = sql.MetaData(self.database)
17 self.message = sql.Table('log_message', metadata, autoload=True)
18 self.user = sql.Table('log_user', metadata, autoload=True)
20 def add_msg(self, user_id, text):
21 """Add new message. Doesn't check if user_id exist"""
22 # example 2008-02-17 18:03:46.072746
23 # TODO
24 now = strftime("%Y-%m-%d %H:%M:%S.000000")
25 text = unicode(text, encoding="utf-8")
26 i = self.message.insert()
27 i.execute(user_id_id=user_id, date=now, text=text)
29 def add_user(self, nick):
30 """Add new user. Doesn't check if allready exist
31 Return his new id.
32 """
33 i = self.user.insert()
34 i.execute(nick_name=nick, first_name='', last_name='',
35 about='', homepage='', email='', avatar='')
36 return self.get_user(nick)
38 def get_user(self, nick):
39 """Find user and returns his id, or None if doesn't exist"""
40 s = self.user.select(self.user.c.nick_name == nick)
41 try:
42 return s.execute().fetchone()[0]
43 except TypeError:
44 return None
46 class Log(object):
47 def __init__(self):
48 self.db = _DatabaseConnection(DATABASE_PATH)
49 self.users = {}
51 def __call__(self, server):
52 if server.msg_data['command'] in ('join', 'quit', 'part'):
53 msg = " ******* " + server.msg_data['command']
54 elif server.msg_data['command'] == 'pubmsg':
55 msg = server.msg_data['args'][0]
56 else:
57 # do nothing, just end
58 return
59 nick = server.msg_data['user']
60 if not nick in self.users.keys():
61 self.users[nick] = self.db.get_user(nick)
62 if not self.users[nick]:
63 self.users[nick] = self.db.add_user(nick)
64 # /me message
65 if msg[1:].startswith('ACTION'):
66 msg = "**" + msg[7:-1]
67 # add message to database
68 self.db.add_msg(self.users[nick], msg)