#! /usr/bin/env python # # AaplBot # # Based on Joel Rosdahl's work. Uses http://python-irclib.sourceforge.net/ # # @author Wil Clouser import os import sys import ConfigParser import string import urllib2 from ircbot import SingleServerIRCBot from irclib import nm_to_n, nm_to_h, irc_lower, ip_numstr_to_quad, ip_quad_to_numstr #=============================================================================== # global variables #=============================================================================== config = {} configfile = 'aaplsauce.conf' configfile = os.path.dirname(sys.argv[0]) + '/' + configfile standardError = sys.stderr #=============================================================================== # getConfig #=============================================================================== def getConfig(): """Read configuration file if present, otherwise pick default values.""" global config, configfile # try to get data off a config file try: cp = ConfigParser.ConfigParser() cp.read(configfile) config['server'] = cp.get('main', 'server') config['port'] = cp.getint('main', 'port') config['channel'] = cp.get('main', 'channel') config['nickname'] = cp.get('aaplbot', 'nickname') except Exception, x: print >>standardError, "Error reading config file: ", configfile sys.exit(1) class AaplBot(SingleServerIRCBot): def __init__(self, channel, nickname, server, port=6667): SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname) self.channel = channel def on_nicknameinuse(self, c, e): c.nick(c.get_nickname() + "_") def on_welcome(self, c, e): c.join(self.channel) def on_pubmsg(self, c, e): a = string.split(e.arguments()[0], ":", 1) if len(a) > 1 and irc_lower(a[0]) == irc_lower(self.connection.get_nickname()): self.do_command(e, string.strip(a[1])) elif string.join(e.arguments()).lower().find('aapl') != -1: self.do_command(e, 'aapl') return def do_command(self, e, cmd): global config nick = nm_to_n(e.source()) c = self.connection if cmd == "gtfo": self.die() elif cmd == "aapl": try: # Is this against the yahoo TOS? response = urllib2.urlopen("http://download.finance.yahoo.com/d/quotes.csv?s=AAPL&f=sl1d1t1c1ohgv&e=.csv") csv = response.read() data = csv.split(',') c.privmsg(config['channel'], "omg, aapl last traded at " + data[1] + "!") except Exception, e: print "Exception: " + str(e) + "\n" if __name__ == "__main__": getConfig() bot = AaplBot(config['channel'], config['nickname'], config['server'], config['port']) bot.start()