chiark / gitweb /
change blame text to modified from added (suggestion from rejs)
[irc.git] / commands.py
1 # Part of Acrobat.
2 import string, cPickle, random, urllib, sys, time, re, os, twitter, subprocess, datetime
3 from irclib import irc_lower, nm_to_n
4
5 # query karma
6 def karmaq(bot, cmd, nick, conn, public, karma):
7     try:
8         item=cmd.split()[1].lower()
9     except IndexError:
10         item=None
11     if item==None:
12         bot.automsg(public,nick,"I have karma on %s items." %
13                          len(karma.keys()))
14     elif karma.has_key(item):
15         bot.automsg(public,nick,"%s has karma %s."
16                      %(item,karma[item]))
17     else:
18         bot.automsg(public,nick, "%s has no karma set." % item)
19
20 # delete karma
21 def karmadelq(bot, cmd, nick, conn, public, karma):
22     try:
23         item=cmd.split()[1].lower()
24     except IndexError:
25         conn.notice(nick, "What should I delete?")
26         return
27     if nick != bot.owner:
28         conn.notice(nick, "You are not my owner.")
29         return
30     if karma.has_key(item):
31         del karma[item]
32         conn.notice(nick, "Item %s deleted."%item)
33     else:
34         conn.notice(nick, "There is no karma stored for %s."%item)
35
36 # help - provides the URL of the help file
37 def helpq(bot, cmd, nick, conn, public):
38     bot.automsg(public,nick,
39                 "For help see http://www.chiark.greenend.org.uk/~matthewv/irc/servus.html")
40
41
42 # query bot status
43 def infoq(bot, cmd, nick, conn, public, karma):
44     bot.automsg(public,nick,
45         ("I am Acrobat %s, on %s, as nick %s.  "+
46         "My owner is %s; I have karma on %s items.") %
47         (bot.revision.split()[1], bot.channel, conn.get_nickname(),
48          bot.owner, len(karma.keys())))
49
50 # Check on fish stocks
51 def fish_quota(pond):
52     if pond.DoS:
53         if time.time()>=pond.quotatime:
54             pond.DoS=0
55         else:
56             return
57     if (time.time()-pond.quotatime)>pond.fish_time_inc:
58         pond.cur_fish+=(((time.time()-pond.quotatime)
59                          /pond.fish_time_inc)*pond.fish_inc)
60         if pond.cur_fish>pond.max_fish:
61             pond.cur_fish=pond.max_fish
62         pond.quotatime=time.time()
63
64 # trout someone, or flirt with them
65 def troutq(bot, cmd, nick, conn, public, cfg):
66     fishlist=cfg[0]
67     selftrout=cfg[1]
68     quietmsg=cfg[2]
69     notargetmsg=cfg[3]
70     nofishmsg=cfg[4]
71     fishpond=cfg[5]
72     selftroutchance=cfg[6]
73
74     fish_quota(fishpond)
75     if fishpond.DoS:
76         conn.notice(nick, quietmsg%fishpond.Boring_Git)
77         return
78     if fishpond.cur_fish<=0:
79         conn.notice(nick, nofishmsg)
80         return
81     target = string.join(cmd.split()[1:])
82     if len(target)==0:
83         conn.notice(nick, notargetmsg)
84         return
85     me = bot.connection.get_nickname()
86     trout_msg = random.choice(fishlist)
87     fishpond.last=trout_msg
88     # The bot won't trout or flirt with itself;
89     if irc_lower(me) == irc_lower(target):
90         target = nick
91     # There's a chance the game may be given away if the request was not
92     # public...
93     if not public:
94         if random.random()<=selftroutchance:
95             trout_msg=trout_msg+(selftrout%nick)
96
97     conn.action(bot.channel, trout_msg % target)
98     fishpond.cur_fish-=1
99
100 # slash a pair
101 def slashq(bot, cmd, nick, conn, public, cfg):
102     fishlist=cfg[0]
103     selfslash=cfg[1]
104     quietmsg=cfg[2]
105     notargetmsg=cfg[3]
106     nofishmsg=cfg[4]
107     fishpond=cfg[5]
108     selfslashchance=cfg[6]
109
110     fish_quota(fishpond)
111     if fishpond.DoS:
112         conn.notice(nick, quietmsg%fishpond.Boring_Git)
113         return
114     if fishpond.cur_fish<=0:
115         conn.notice(nick, nofishmsg)
116         return
117     target = string.join(cmd.split()[1:])
118     #who = cmd.split()[1:]
119     who = ' '.join(cmd.split()[1:]).split(' / ')
120     if len(who) < 2:
121         conn.notice(nick, "it takes two to tango!")
122         return
123     elif len(who) > 2:
124         conn.notice(nick, "we'll have none of that round here")
125         return
126     me = bot.connection.get_nickname()
127     slash_msg = random.choice(fishlist)
128     # The bot won't slash people with themselves
129     if irc_lower(who[0]) == irc_lower(who[1]):
130         conn.notice(nick, "oooooh no missus!")
131         return
132     # The bot won't slash with itself, instead slashing the requester
133     for n in [0,1]:
134         if irc_lower(me) == irc_lower(who[n]):
135             who[n] = nick
136     # Perhaps someone asked to slash themselves with the bot then we get
137     if irc_lower(who[0]) == irc_lower(who[1]):
138         conn.notice(nick, "you wish!")
139         return
140     # There's a chance the game may be given away if the request was not
141     # public...
142     if not public:
143         if random.random()<=selfslashchance:
144             slash_msg=slash_msg+(selfslash%nick)
145
146     conn.action(bot.channel, slash_msg % (who[0], who[1]))
147     fishpond.cur_fish-=1
148
149 #query units
150 def unitq(bot, cmd, nick, conn, public):
151     args = ' '.join(cmd.split()[1:]).split(' as ')
152     if len(args) != 2:
153         args = ' '.join(cmd.split()[1:]).split(' / ')
154         if len(args) != 2:
155             conn.notice(nick, "syntax: units arg1 as arg2")
156             return
157     if args[1]=='?':
158         sin,sout=os.popen4(["units","--verbose","--",args[0]],"r")
159     else:
160         sin,sout=os.popen4(["units","--verbose","--",args[0],args[1]],"r")
161     sin.close()
162     res=sout.readlines()
163     #popen2 doesn't clean up the child properly. Do this by hand
164     child=os.wait()
165     if os.WEXITSTATUS(child[1])==0:
166         bot.automsg(public,nick,res[0].strip())
167     else:
168         conn.notice(nick,'; '.join(map(lambda x: x.strip(),res)))
169
170 # Shut up trouting for a minute
171 def nofishq(bot, cmd, nick, conn, public, fish):
172     fish.cur_fish=0
173     fish.DoS=1
174     fish.Boring_Git=nick
175     fish.quotatime=time.time()
176     fish.quotatime+=fish.nofish_time
177     conn.notice(nick, "Fish stocks depleted, as you wish.")
178
179 # rehash bot config
180 def reloadq(bot, cmd, nick, conn, public):
181     if not public and irc_lower(nick) == irc_lower(bot.owner):
182         try:
183             reload(bot.config)
184             conn.notice(nick, "Config reloaded.")
185         except ImportError:
186             conn.notice(nick, "Config reloading failed!")
187     else:
188         bot.automsg(public,nick,
189                 "Configuration can only be reloaded by my owner, by /msg.")
190
191 # quit irc
192 def quitq(bot, cmd, nick, conn, public):
193     if irc_lower(nick) == irc_lower(bot.owner):
194         bot.die(msg = "I have been chosen!")
195     elif public:
196         conn.notice(nick, "Such aggression in public!")
197     else:
198         conn.notice(nick, "You're not my owner.")
199
200 # google for something
201 def googleq(bot, cmd, nick, conn, public):
202     cmdrest = string.join(cmd.split()[1:])
203     # "I'm Feeling Lucky" rather than try and parse the html
204     targ = ("http://www.google.com/search?q=%s&btnI=I'm+Feeling+Lucky"
205             % urllib.quote_plus(cmdrest))
206     try:
207         # get redirected and grab the resulting url for returning
208         gsearch = urllib.urlopen(targ).geturl()
209         if gsearch != targ: # we've found something
210             bot.automsg(public,nick,str(gsearch))
211         else: # we haven't found anything.
212             bot.automsg(public,nick,"No pages found.")
213     except IOError: # if the connection times out. This blocks. :(
214         bot.automsg(public,nick,"The web's broken. Waah!")
215
216 # Look up the definition of something using google
217 def defineq(bot, cmd, nick, conn, public):
218     #this doesn't work any more
219     bot.automsg(public,nick,"'define' is broken because google are bastards :(")
220     return
221     cmdrest = string.join(cmd.split()[1:])
222     targ = ("http://www.google.co.uk/search?q=define%%3A%s&ie=utf-8&oe=utf-8"
223             % urllib.quote_plus(cmdrest))
224     try:
225         # Just slurp everything into a string
226         defnpage = urllib.urlopen(targ).read()
227         # For definitions we really do have to parse the HTML, sadly.
228         # This is of course going to be a bit fragile. We first look for
229         # 'Definitions of %s on the Web' -- if this isn't present we
230         # assume we have the 'no definitions found page'.
231         # The first defn starts after the following <p> tag, but as the
232         # first <li> in a <ul type="disc" class=std>
233         # Following that we assume that each definition is all the non-markup
234         # before a <br> tag. Currently we just dump out the first definition.
235         match = re.search(r"Definitions of <b>.*?</b> on the Web.*?<li>\s*([^>]*)((<br>)|(<li>))",defnpage,re.MULTILINE)
236         if match == None:
237            bot.automsg(public,nick,"Some things defy definition.")
238         else:
239            # We assume google has truncated the definition for us so this
240            # won't flood the channel with text...
241            defn = " ".join(match.group(1).split("\n"))
242            bot.automsg(public,nick,defn)
243     except IOError: # if the connection times out. This blocks. :(
244          bot.automsg(public,nick,"The web's broken. Waah!")
245
246 # Look up a currency conversion via xe.com
247 def currencyq(bot, cmd, nick, conn, public):
248     args = ' '.join(cmd.split()[1:]).split(' as ')
249     if len(args) != 2 or len(args[0]) != 3 or len(args[1]) != 3:
250         conn.notice(nick, "syntax: currency arg1 as arg2")
251         return
252     targ = ("http://www.xe.com/ucc/convert.cgi?From=%s&To=%s" % (args[0], args[1]))
253     try:
254         currencypage = urllib.urlopen(targ).read()
255         match = re.search(r"(1&nbsp;%s&nbsp;=&nbsp;[\d\.]+&nbsp;%s)" % (args[0],args[1]),currencypage,re.MULTILINE)
256         if match == None:
257             bot.automsg(public,nick,"Dear Chief Secretary, there is no money.")
258         else:
259             conversion = match.group(1);
260             conversion = conversion.replace('&nbsp;',' ');
261             bot.automsg(public,nick,conversion + " (from xe.com)")
262     except IOError: # if the connection times out. This blocks. :(
263         bot.automsg(public,nick,"The web's broken. Waah!")
264                  
265
266 ### extract the commit message and timestamp for commit 
267 def __getcommitinfo(commit):
268     cmd=["git","log","-n","1","--pretty=format:%ct|%s",commit]
269     x=subprocess.Popen(cmd,
270                        stdout=subprocess.PIPE,stderr=subprocess.PIPE)
271     out,err=x.communicate()
272
273     if len(err):
274         return(err)
275
276     ts,mes=out.split('|')
277     when=datetime.date.fromtimestamp(float(ts))
278     return mes.strip(), when
279
280 ###Return an array of commit messages and timestamps for lines in db that match what
281 def __getcommits(db,keys,what):
282     ans=[]
283     for k in keys:
284         if what in k:
285             ret=__getcommitinfo(db[k])
286             if len(ret)==1: #error message
287                 return ["Error message from git blame: %s" % ret]
288             else:
289                 ans.append( (k,ret[0],ret[1]) )
290     return ans
291
292 ###search all three databases for what
293 def __getall(tdb,tdbk,fdb,fdbk,sdb,sdbk,what):
294     if what.strip()=="":
295         return []
296     tans=__getcommits(tdb,tdbk,what)
297     fans=__getcommits(fdb,fdbk,what)
298     sans=__getcommits(sdb,sdbk,what)
299     return tans+fans+sans
300
301 def blameq(bot,cmd,nick,conn,public,fish,tdb,tdbk,fdb,fdbk,sdb,sdbk):
302     clist=cmd.split()
303     if len(clist) < 2:
304         bot.automsg(public,nick,"Who or what do you want to blame?")
305         return
306     cwhat=' '.join(clist[2:])
307     if clist[1]=="#last":
308         ans=__getall(tdb,tdbk,fdb,fdbk,sdb,sdbk,fish.last)
309     elif clist[1]=="#trouts" or clist[1]=="#trout":
310         ans=__getcommits(tdb,tdbk,cwhat)
311     elif clist[1]=="#flirts" or clist[1]=="#flirt":
312         ans=__getcommits(fdb,fdbk,cwhat)
313     elif clist[1]=="#slashes" or clist[1]=="#slash":
314         ans=__getcommits(sdb,sdbk,cwhat)
315     else:
316         cwhat=' '.join(clist[1:])
317         ans=__getall(tdb,tdbk,fdb,fdbk,sdb,sdbk,cwhat)
318     if len(ans)==0:
319         bot.automsg(public,nick,"No match found")
320     elif len(ans)==1:
321         if len(ans[0])==1:
322             bot.automsg(public,nick,ans[0])
323         else:
324             bot.automsg(public,nick,"Modified %s: %s" % (ans[0][2].isoformat(),ans[0][1]))
325     elif len(ans)>4:
326         bot.automsg(public,nick,"I found %d matches, which is too many. Please be more specific!" % (len(ans)) )
327     else:
328         for a in ans:
329             if len(a)==1:
330                 bot.automsg(public,nick,a)
331             else:
332                 bot.automsg(public,nick,"'%s' modified on %s: %s" % (a[0],a[2].isoformat(),a[1]))
333
334 ### say to msg/channel            
335 def sayq(bot, cmd, nick, conn, public):
336     if irc_lower(nick) == irc_lower(bot.owner):
337         conn.privmsg(bot.channel, string.join(cmd.split()[1:]))
338     else:
339         if not public:
340             conn.notice(nick, "You're not my owner!")
341
342 ### action to msg/channel
343 def doq(bot, cmd, nick, conn, public):
344     sys.stderr.write(irc_lower(bot.owner))
345     sys.stderr.write(irc_lower(nick))
346     if not public:
347         if irc_lower(nick) == irc_lower(bot.owner):
348             conn.action(bot.channel, string.join(cmd.split()[1:]))
349         else:
350             conn.notice(nick, "You're not my owner!")
351
352 ###disconnect
353 def disconnq(bot, cmd, nick, conn, public):
354     if cmd == "disconnect": # hop off for 60s
355         bot.disconnect(msg="Be right back.")
356
357 ### list keys of a dictionary
358 def listkeysq(bot, cmd, nick, conn, public, dict, sort=False):
359     d=dict.keys()
360     if sort:
361         d.sort()
362     bot.automsg(public,nick,string.join(d))
363
364 ### rot13 text (yes, I could have typed out the letters....)
365 ### also "foo".encode('rot13') would have worked
366 def rot13q(bot, cmd, nick, conn, public):
367     a=''.join(map(chr,range((ord('a')),(ord('z')+1))))
368     b=a[13:]+a[:13]
369     trans=string.maketrans(a+a.upper(),b+b.upper())
370     conn.notice(nick, string.join(cmd.split()[1:]).translate(trans))
371
372 ### URL-tracking stuff
373
374 ### return a easy-to-read approximation of a time period
375 def nicetime(tempus):
376   if (tempus<120):
377     tm="%d seconds ago"%int(tempus)
378   elif (tempus<7200):
379     tm="%d minutes ago"%int(tempus/60)
380   if (tempus>7200):
381     tm="%d hours ago"%int(tempus/3600)
382   return tm
383
384 ### class to store URL data
385 class UrlLog:
386     "contains meta-data about a URL seen on-channel"
387     def __init__(self,url,nick):
388         self.nick=nick
389         self.url=url
390         self.first=time.time()
391         self.count=1
392         self.lastseen=time.time()
393         self.lastasked=time.time()
394     def recenttime(self):
395         return max(self.lastseen,self.lastasked)
396     def firstmen(self):
397         return nicetime(time.time()-self.first)
398     def urltype(self):
399         z=min(len(urlcomplaints)-1, self.count-1)
400         return urlcomplaints[z]
401
402 #(?:) is a regexp that doesn't group        
403 urlre = re.compile(r"((?:(?:http)|(?:nsfw))s?://[^ ]+)( |$)")
404 hturlre= re.compile(r"(http)(s?://[^ ]+)( |$)")
405 #matches \bre\:?\s+ before a regexp; (?i)==case insensitive match
406 shibboleth = re.compile(r"(?i)\bre\:?\s+((?:(?:http)|(?:nsfw))s?://[^ ]+)( |$)")
407 urlcomplaints = ["a contemporary","an interesting","a fascinating","an overused","a vastly overused"]
408
409 ### Deal with /msg bot url or ~url in channel
410 def urlq(bot, cmd, nick, conn, public,urldb):
411   if (not urlre.search(cmd)):
412     bot.automsg(False,nick,"Please use 'url' only with http, https, nsfw, or nsfws URLs")
413     return
414
415   urlstring=urlre.search(cmd).group(1)
416   url=canonical_url(urlstring)
417   if (url in urldb):
418     T = urldb[url]
419     complaint="That's %s URL that was first mentioned %s by %s" % \
420                (T.urltype(),T.firstmen(),T.nick)
421     if (public):
422       complaint=complaint+". Furthermore it defeats the point of this command to use it other than via /msg."
423       T.count+=1
424     bot.automsg(False,nick,complaint)
425     T.lastasked=time.time()
426     #URL suppressed, so mention in #urls
427     if urlstring != cmd.split()[1]: #first argument to URL was not the url
428       conn.privmsg("#urls","%s remarks: %s" % (nick," ".join(cmd.split()[1:])))
429     else:
430       conn.privmsg("#urls","(via %s) %s"%(nick," ".join(cmd.split()[1:])))
431   else:
432     if (public):
433       bot.automsg(False,nick,"That URL was unique. There is little point in using !url out loud; please use it via /msg")
434     else:
435       if urlstring != cmd.split()[1]: #first argument to URL was not the url
436         conn.privmsg(bot.channel,"%s remarks: %s" % (nick," ".join(cmd.split()[1:])))
437       else:
438         conn.privmsg(bot.channel,"(via %s) %s"%(nick," ".join(cmd.split()[1:])))
439       bot.automsg(False,nick,"That URL was unique; I have posted it into IRC")
440     urldb[url]=UrlLog(url,nick)
441
442 ### Deal with URLs spotted in channel
443 def dourl(bot,conn,nick,command,urldb):
444   urlstring=urlre.search(command).group(1)
445   urlstring=canonical_url(urlstring)
446
447   if urlstring in urldb:
448     T=urldb[urlstring]
449     message="observes %s URL, first mentioned %s by %s" % \
450              (T.urltype(),T.firstmen(),T.nick)
451     if shibboleth.search(command)==None:
452         conn.action(bot.channel, message)
453     T.lastseen=time.time()
454     T.count+=1
455   else:
456     urldb[urlstring]=UrlLog(urlstring,nick)
457
458 ### Expire old urls
459 def urlexpire(urldb,expire):
460     urls=urldb.keys()
461     for u in urls:
462         if time.time() - urldb[u].recenttime() > expire:
463             del urldb[u]
464
465 # canonicalise BBC URLs (internal use only)
466 def canonical_url(urlstring):
467   if "nsfw://" in urlstring or "nsfws://" in urlstring:
468       urlstring=urlstring.replace("nsfw","http",1)
469   if (urlstring.find("news.bbc.co.uk") != -1):
470     for middle in ("/low/","/mobile/"):
471       x = urlstring.find(middle)
472       if (x != -1):
473         urlstring.replace(middle,"/hi/")
474   return urlstring
475
476 # automatically make nsfw urls for you and pass them on to url
477 def nsfwq(bot,cmd,nick,conn,public,urldb):
478   if (not hturlre.search(cmd)):
479     bot.automsg(False,nick,"Please use 'nsfw' only with http or https URLs")
480     return
481   newcmd=hturlre.sub(nsfwify,cmd)
482   urlq(bot,newcmd,nick,conn,public,urldb)
483
484 def nsfwify(match):
485     a,b,c=match.groups()
486     return 'nsfw'+b+c
487
488 #get tweet text
489 def twitterq(bot,cmd,nick,conn,public,twitapi):
490   
491   if (not urlre.search(cmd)):
492     bot.automsg(False,nick,"Please use 'twit' only with http URLs")
493     return
494
495   urlstring = urlre.search(cmd).group(1)
496   if (urlstring.find("twitter.com") !=-1):
497     stringout = getTweet(urlstring,twitapi)
498     bot.automsg(public, nick, stringout)
499   
500 def getTweet(urlstring,twitapi):
501   parts = string.split(urlstring,'/')
502   tweetID = parts[-1]
503   try:
504     status = twitapi.GetStatus(tweetID)
505     tweeter_screen = status.user.screen_name.encode('UTF-8', 'replace')
506     tweeter_name = status.user.name.encode('UTF-8', 'replace')
507     tweetText = status.text.encode('UTF-8', 'replace')
508     tweetText = tweetText.replace('\n',' ')
509     stringout = "tweet by %s (%s): %s" %(tweeter_screen,tweeter_name,tweetText)
510   except twitter.TwitterError:
511     terror = sys.exc_info()
512     stringout = "Twitter error: %s" % terror[1].__str__()
513   return stringout