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