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