view pyikb/ikariam.py @ 62:a4c364888197

add ikriam game binding lib python version
author hychen@mluna
date Wed, 22 Oct 2008 04:04:32 +0800
parents 610bbe1824ef
children 1c42ae140ad3
line wrap: on
line source

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os,sys,re,string
import cookielib,urllib2,urllib # for urlencode
import time
from sgmllib import SGMLParser  

class ContentParser(SGMLParser):
    def __init__(self):
        SGMLParser.__init__(self)
        self.anchor =  {'link':'', 'title':''}
        self.anchorlist = []
	self.liattr={}
        self.inside_elements=['site']
	self.pat=re.compile('\r|\t|\n')

    def start_a(self, attributes):
        """For each anchor tag, pay attention to the href and title attributes."""
        href, title = '', ''
        for name, value in attributes:
            if name.lower() == 'href': href = value
            if name.lower() == 'title': title = value
        self.anchor['link'] = href
        self.anchor['title'] = title
        self.inside_elements.append('anchor')

    def end_a(self):
        self.anchorlist.append(self.anchor) # store the anchor in a list 
        self.anchor = {'link':'', 'title':''}   # reset the dictionary,  
        self.inside_elements.pop()

    def handle_data(self, text):
        if self.inside_elements[-1]=='anchor':
            self.anchor['title'] = text
	if self.inside_elements[-1]=='li':
	    text=self.pat.sub(' ',text)
	    text=string.split(text," ")
	    if self.liattcl in self.liattr:
	    	self.liattr[self.liattcl]=self.liattr[self.liattcl]+text
	    else:
	        self.liattr[self.liattcl]=text

    def start_li(self,attributes):
	self.liattcl=''
        attrs = dict(attributes)
	if attrs.has_key('class'):
	     	self.liattcl=attrs['class']
		self.inside_elements.append('li')

    def end_li(self):
	if self.inside_elements[-1]=='li':
	    self.inside_elements.pop()
	

class connection(object):
    def __init__(self):
	self.page=''
	self.server='s2.ikariam.tw'
	self.baseurl='http://'+self.server
        self.COOKIEFILE = '/tmp/ikcookies.lwp'
	self.cj = cookielib.LWPCookieJar()
	if os.path.isfile(self.COOKIEFILE):
	    self.cj.load(self.COOKIEFILE)
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
	opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-TW; rv:1.8.1.12pre) Gecko/20071220 BonEcho/2.0.0.12pre')]
	urllib2.install_opener(opener)

    def login(self):
        if not os.path.isfile(self.COOKIEFILE):
	    print "create cookie file"+self.COOKIEFILE
	    # /index.php?action=loginAvatar&function=login
            params = {"universe":self.server, "name":'username', "password":'passwd'}
            data = urllib.urlencode(params)
            self.page=urllib2.urlopen(self.baseurl+'/index.php?action=loginAvatar&function=login',data).read()
	self.cj.save(self.COOKIEFILE)
	return 1

    def parser(self):
        parser=ContentParser()
        parser.feed(self.page)
        parser.close
	for x in parser.liattr.keys():
	    print x,parser.liattr[x]
	#parser.anchorlist:

    def logout(self):
        logout=urllib2.urlopen(self.baseurl+'/index.php?action=loginAvatar&function=logout').read()
	os.remove(self.COOKIEFILE)
	return 1

    def plunder(self):
    	'/index.php?view=plunder&destinationCityId=1978'


    def upgradetest(self):
        urllib2.urlopen(self.baseurl+'/index.php?view=academy&id=117257&position=9').read()
	params = {"action":'CityScreen', \
	          "function":'upgradeBuilding', \
		  "id":'117257',\
		  "position":'9',\
		  "level":'7',\
		  "oldView":'academy'}
	print urllib2.urlopen(self.baseurl+'/index.php?view=townHall&id=117257&position=0#upgrade',urllib.urlencode(params)).read()
	return 1

def help():
        print ("Usage: %s [Option] [Channel] [second]") % os.path.basename(sys.argv[0])
        print ("Option: ")
	helplist=[
	("-h","--help","show this usage message."),
	("-g","--game","Login to the game")
	]
	helplist.sort()
	for x in helplist:
	    print ("\t%2s, %-25s %s" % x)

if __name__=='__main__':
    if len(sys.argv) == 1:
	help()
	sys.exit(2) # common exit code for syntax error
    else:
	arglist=sys.argv[1:]
	if arglist[0] in ('--game','-g'):
	     gc=connection()
	     gc.login()
	     gc.parser()
	     gc.logout()