chiark / gitweb /
fish: track last_cfg too
[irc.git] / Servus-chiark.py
1 # This file is part of Acrobat.
2 #
3 # Acrobat is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published
5 # by the Free Software Foundation; either version 2 of the License,
6 # or (at your option) any later version.
7 #
8 # Acrobat is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with Acrobat; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
16 # USA.
17
18 # Andrew Walkingshaw <andrew@lexical.org.uk>
19 # Peter Corbett <ptc24@cam.ac.uk>
20 # Matthew Vernon <matthew@debian.org>
21 # Stephen Early <steve@greenend.org.uk>
22 # Richard Kettlewell <rjk@greenend.org.uk
23
24 # Acrobat configuration file
25
26 # The following definitions are required to be present in this module:
27 # You can also override them on the command-line
28 # e.g. python acrobat.py Servus-chiark nickname=testbot channel=\#test owner=MyNick
29 server = "chiark"
30 port = 6667
31 nickname = "Servus"
32 channel = "#chiark"
33 owner = "Emperor"
34 # Also a function called "command"; see later.
35
36 # Everything else in this file is configuration-specific.
37
38 import os, time, re, twitter, subprocess, sys, os.path
39
40 # Most command implementations are stored in a separate module.
41 import commands as c
42
43 # This fishpond is shared between trouts and flirts.  It doesn't have to be;
44 # you can define as many ponds as you like.
45 class fish:
46         cur_fish=5
47         max_fish=5
48         nofish_time=60
49         fish_time_inc=60
50         fish_inc=2
51         DoS=0
52         Boring_Git='Nobody'
53         quotatime=0
54         last=""
55         last_cfg=None
56
57 # load the "blame" details for a file
58 def loadblame(filename):
59     p=subprocess.Popen(["git","blame","-s",filename],
60                        stdout=subprocess.PIPE,stderr=subprocess.PIPE)
61     out,err=p.communicate()
62     if len(err)>0:
63         sys.exit("git blame failure: %s" % err)
64     bdb={}
65     lines=out.split("\n")
66     for line in lines:
67         l=line.split()
68         if len(line.strip())>0:
69             commit=l[0]
70             thing=' '.join(l[2:])
71             bdb[thing]=commit
72     keys=bdb.keys()
73     return bdb,keys
74     
75 #set up blame dbs for trouts/flirts/slashes
76 tbdb,tbdbk=loadblame("trouts")
77 fbdb,fbdbk=loadblame("flirts")
78 sbdb,sbdbk=loadblame("slashes")
79
80 # load a file full of flirts or trouts
81 def __load(filename):
82     try:
83         f = open(filename, "r")
84         r = [l.strip() for l in f.readlines() if l.find("%s") != -1]
85         f.close()
86     except IOError:
87         r = [ "doesn't know what to do about %s." ]
88     return r
89
90 # (troutlist,selftroutmsg,DoSmsg,notargetmsg,nofishmsg,fishpond,selftroutprob)
91 troutcfg = (
92         __load("trouts"),
93         ' (at the instigation of %s)',
94         "Sorry, but %s is being a spoilsport.",
95         "Who do you wish me to trout?",
96         "Fish stocks exhausted.",
97         fish,
98         0.1)
99
100 flirtcfg = (
101         __load("flirts"),
102         ' (but %s is their secret admirer)',
103         "Sorry, but %s made me take Holy Orders.",
104         "Who do you wish me to flirt with?",
105         "My libido is over-used!",
106         fish,
107         0.1)
108
109 slashcfg= ( 
110         __load("slashes"),
111         ' (while %s watches)',
112         "Sorry, but %s stole my pen.",
113         "Who do you want to slash?",
114         "I have writer's block!",
115         fish,
116         0.1)
117
118 # Hacky command to output the current fishpond state
119 def fishq(bot, cmd, nick, conn, public,f):
120         from irclib import irc_lower
121         if not public and irc_lower(nick) == irc_lower(bot.owner):
122                 state=("Fishpond state: cur_fish=%d, max_fish=%d, nofish_time=%d, "
123                        +"fish_time_inc=%d, fish_inc=%d, DoS=%d, Boring_Git=%s, "
124                        +"quotatime=%d")%(f.cur_fish,f.max_fish,f.nofish_time,
125                                          f.fish_time_inc,f.fish_inc,f.DoS,f.Boring_Git,
126                                          f.quotatime)
127                 bot.automsg(public,nick,state)
128                     
129 # Karma implementation
130 import cPickle
131 karmafilename = "chiark-karma-"+channel
132 # load the karma db
133 try:
134     f = open(karmafilename, "r")
135     karmadb = cPickle.load(f)
136     f.close()
137 except IOError:
138     karmadb = {}
139 # Modify karma
140 def karma(cmd, amount):
141     thing=cmd.split()[0][:-2].lower()
142     if karmadb.has_key(thing):
143         karmadb[thing] += amount
144     else:
145         karmadb[thing] = amount
146     savekarma()
147 def savekarma():
148     tmp = "%s.tmp" % karmafilename
149     try:
150         f = open(tmp, "w")
151         cPickle.dump(karmadb, f)
152         f.close()
153         os.rename(tmp, karmafilename)
154     except IOError, e:
155         sys.stderr.write("error writing karma: %s" % e)
156
157 def quit(bot,cmd,nick,conn,public):
158     c.quitq(bot,cmd,nick,conn,public)
159 def reload(bot,cmd,nick,conn,public):
160     c.reloadq(bot,cmd,nick,conn,public)
161
162 # initialise the urldb on startup
163 urldb={}
164 lastexp=time.time()
165 #expire urls if not asked about or seen for >71 hours
166 expirelen=71*60*60
167 #do an expiry run every hour
168 expirevery=60*60
169
170
171 #path where Oauth details are kept
172 twioauthpath=os.path.expanduser("~/private/servus_twapi_oauth.txt")
173
174 try:
175   f=open(twioauthpath,"r")
176   for line in f:
177     if line[0]=='#':
178       continue
179     key,val=map(str.strip,line.split(':'))
180     if key == "consumer_key":
181       twoaapck = val
182     elif key == "consumer_secret":
183       twoaapcs = val
184     elif key == "access_token":
185       twoapat = val
186     elif key == "access_token_secret":
187       twoapats = val
188     else:
189       raise ValueError, "Invalid line in twitter auth details file %s" % line
190   f.close()
191   twitapi = twitter.Api(consumer_key = twoaapck,
192                         consumer_secret = twoaapcs,
193                         access_token_key = twoapat,
194                         access_token_secret = twoapats,
195                         tweet_mode = "extended")
196 except IOError:
197 # non-authenticated twitter api instance
198   twitapi = twitter.Api()
199
200 # Command processing: whenever something is said that the bot can hear,
201 # "command" is invoked and must decide what to do.  This configuration
202 # defines a couple of special cases (for karma) but is otherwise driven
203 # by a dictionary of commands.
204
205 commands = {"karma": (c.karmaq,karmadb),
206             "karmalist": (c.listkeysq,karmadb),
207             "karmadel": (c.karmadelq,karmadb),
208             "info": (c.infoq,karmadb),
209             "trout": (c.troutq,troutcfg),
210             "slash": (c.slashq, slashcfg),
211             "rot13": c.rot13q,
212             "fish": (fishq,fish),
213             "flirt": (c.troutq,flirtcfg),
214             "quiet": (c.nofishq,fish),
215             "reload": reload,
216             "quit": quit,
217             "die": quit,
218             "define": c.defineq,
219             "google": c.googleq,
220             "url": (c.urlq,urldb),
221             "nsfw": (c.nsfwq,urldb),
222             "nws": (c.nsfwq,urldb),
223             "units": c.unitq,
224             "currency":c.currencyq,
225             "blame": (c.blameq,fish,tbdb,tbdbk,fbdb,fbdbk,sbdb,sbdbk),
226             "help": c.helpq,
227             "say": c.sayq,
228             "do": c.doq, 
229             "twit": (c.twitterq,twitapi) }
230 # disconnect and hop annoy people
231 #            "disconnect": c.disconnq,
232 #            "hop": c.disconnq }
233 commands["list"]=(c.listkeysq,commands,True)
234
235 triggers = ("!", "~") # what character should the bot be invoked by:
236                       # eg !trout, ~trout etc.
237
238 def command(bot, cmd, nick, conn, public):
239     global urldb,lastexp,expirelen,expirevery,twitapi
240     ours=0
241     try:
242             if public and cmd[0] in triggers:
243                     ours=1
244                     cmd=cmd[1:]
245             if not public:
246                     ours=1
247             command = cmd.split()[0]
248     except IndexError:
249             command=""
250
251     t=time.time()
252     if t - lastexp > expirevery:
253             c.urlexpire(urldb,expirelen)
254             lastexp=t
255
256     if public:
257       if c.urlre.search(cmd) and command.lower()!="url":
258         c.dourl(bot,conn,nick,cmd,urldb)
259
260     # karma: up
261     if command.endswith("++"):
262         karma(cmd,1)
263     # karma: down
264     if command.endswith("--"):
265         karma(cmd,-1)
266
267     if ours and command.lower() in commands.keys():
268         e=commands[command.lower()]
269         if callable(e):
270             e(bot,cmd,nick,conn,public)
271         else:
272             e[0](bot,cmd,nick,conn,public,*e[1:])