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