chiark / gitweb /
0f40c2d044186102464562617c081ed7b172f4d7
[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 # load a file full of flirts or trouts
76 def __load(filename):
77     try:
78         f = open(filename, "r")
79         r = [l.strip() for l in f.readlines() if l.find("%s") != -1]
80         f.close()
81     except IOError:
82         r = [ "doesn't know what to do about %s." ]
83     return r
84
85 # (troutlist,selftroutmsg,DoSmsg,notargetmsg,nofishmsg,fishpond,selftroutprob)
86 troutcfg = (
87         __load("trouts"),
88         ' (at the instigation of %s)',
89         "Sorry, but %s is being a spoilsport.",
90         "Who do you wish me to trout?",
91         "Fish stocks exhausted.",
92         fish,
93         0.1,
94         loadblame("trouts"),
95         )
96
97 flirtcfg = (
98         __load("flirts"),
99         ' (but %s is their secret admirer)',
100         "Sorry, but %s made me take Holy Orders.",
101         "Who do you wish me to flirt with?",
102         "My libido is over-used!",
103         fish,
104         0.1,
105         loadblame("flirts"),
106         )
107
108 slashcfg= ( 
109         __load("slashes"),
110         ' (while %s watches)',
111         "Sorry, but %s stole my pen.",
112         "Who do you want to slash?",
113         "I have writer's block!",
114         fish,
115         0.1,
116         loadblame("slashes")
117         )
118
119 # Hacky command to output the current fishpond state
120 def fishq(bot, cmd, nick, conn, public,f):
121         from irclib import irc_lower
122         if not public and irc_lower(nick) == irc_lower(bot.owner):
123                 state=("Fishpond state: cur_fish=%d, max_fish=%d, nofish_time=%d, "
124                        +"fish_time_inc=%d, fish_inc=%d, DoS=%d, Boring_Git=%s, "
125                        +"quotatime=%d")%(f.cur_fish,f.max_fish,f.nofish_time,
126                                          f.fish_time_inc,f.fish_inc,f.DoS,f.Boring_Git,
127                                          f.quotatime)
128                 bot.automsg(public,nick,state)
129                     
130 # Karma implementation
131 import cPickle
132 karmafilename = "chiark-karma-"+channel
133 # load the karma db
134 try:
135     f = open(karmafilename, "r")
136     karmadb = cPickle.load(f)
137     f.close()
138 except IOError:
139     karmadb = {}
140 # Modify karma
141 def karma(cmd, amount):
142     thing=cmd.split()[0][:-2].lower()
143     if karmadb.has_key(thing):
144         karmadb[thing] += amount
145     else:
146         karmadb[thing] = amount
147     savekarma()
148 def savekarma():
149     tmp = "%s.tmp" % karmafilename
150     try:
151         f = open(tmp, "w")
152         cPickle.dump(karmadb, f)
153         f.close()
154         os.rename(tmp, karmafilename)
155     except IOError, e:
156         sys.stderr.write("error writing karma: %s" % e)
157
158 def quit(bot,cmd,nick,conn,public):
159     c.quitq(bot,cmd,nick,conn,public)
160 def reload(bot,cmd,nick,conn,public):
161     c.reloadq(bot,cmd,nick,conn,public)
162
163 # initialise the urldb on startup
164 urldb={}
165 lastexp=time.time()
166 #expire urls if not asked about or seen for >71 hours
167 expirelen=71*60*60
168 #do an expiry run every hour
169 expirevery=60*60
170
171
172 #path where Oauth details are kept
173 twioauthpath=os.path.expanduser("~/private/servus_twapi_oauth.txt")
174
175 try:
176   f=open(twioauthpath,"r")
177   for line in f:
178     if line[0]=='#':
179       continue
180     key,val=map(str.strip,line.split(':'))
181     if key == "consumer_key":
182       twoaapck = val
183     elif key == "consumer_secret":
184       twoaapcs = val
185     elif key == "access_token":
186       twoapat = val
187     elif key == "access_token_secret":
188       twoapats = val
189     else:
190       raise ValueError, "Invalid line in twitter auth details file %s" % line
191   f.close()
192   twitapi = twitter.Api(consumer_key = twoaapck,
193                         consumer_secret = twoaapcs,
194                         access_token_key = twoapat,
195                         access_token_secret = twoapats,
196                         tweet_mode = "extended")
197 except IOError:
198 # non-authenticated twitter api instance
199   twitapi = twitter.Api()
200
201 # Command processing: whenever something is said that the bot can hear,
202 # "command" is invoked and must decide what to do.  This configuration
203 # defines a couple of special cases (for karma) but is otherwise driven
204 # by a dictionary of commands.
205
206 commands = {"karma": (c.karmaq,karmadb),
207             "karmalist": (c.listkeysq,karmadb),
208             "karmadel": (c.karmadelq,karmadb),
209             "info": (c.infoq,karmadb),
210             "trout": (c.troutq,troutcfg),
211             "slash": (c.slashq, slashcfg),
212             "rot13": c.rot13q,
213             "fish": (fishq,fish),
214             "flirt": (c.troutq,flirtcfg),
215             "quiet": (c.nofishq,fish),
216             "reload": reload,
217             "quit": quit,
218             "die": quit,
219             "define": c.defineq,
220             "google": c.googleq,
221             "url": (c.urlq,urldb),
222             "nsfw": (c.nsfwq,urldb),
223             "nws": (c.nsfwq,urldb),
224             "units": c.unitq,
225             "currency":c.currencyq,
226             "blame": (c.blameq,fish, [troutcfg,flirtcfg,slashcfg]),
227             "help": c.helpq,
228             "say": c.sayq,
229             "do": c.doq, 
230             "twit": (c.twitterq,twitapi) }
231 # disconnect and hop annoy people
232 #            "disconnect": c.disconnq,
233 #            "hop": c.disconnq }
234 commands["list"]=(c.listkeysq,commands,True)
235
236 triggers = ("!", "~") # what character should the bot be invoked by:
237                       # eg !trout, ~trout etc.
238
239 def command(bot, cmd, nick, conn, public):
240     global urldb,lastexp,expirelen,expirevery,twitapi
241     ours=0
242     try:
243             if public and cmd[0] in triggers:
244                     ours=1
245                     cmd=cmd[1:]
246             if not public:
247                     ours=1
248             command = cmd.split()[0]
249     except IndexError:
250             command=""
251
252     t=time.time()
253     if t - lastexp > expirevery:
254             c.urlexpire(urldb,expirelen)
255             lastexp=t
256
257     if public:
258       if c.urlre.search(cmd) and command.lower()!="url":
259         c.dourl(bot,conn,nick,cmd,urldb)
260
261     # karma: up
262     if command.endswith("++"):
263         karma(cmd,1)
264     # karma: down
265     if command.endswith("--"):
266         karma(cmd,-1)
267
268     if ours and command.lower() in commands.keys():
269         e=commands[command.lower()]
270         if callable(e):
271             e(bot,cmd,nick,conn,public)
272         else:
273             e[0](bot,cmd,nick,conn,public,*e[1:])