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