Advertisement
invik

zpbot.py

Sep 27th, 2012
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.07 KB | None | 0 0
  1. #! /usr/bin/python2
  2.  
  3. import mechanize
  4. import cookielib
  5. import json
  6. import os
  7. import inspect
  8. import signal
  9. from time import *
  10. from sys import exit
  11. from urllib2 import HTTPError
  12.  
  13. #########################################################################
  14.  
  15. # Configuration Section
  16.  
  17. # What stat to train
  18. attr = "Agi" # Agi / Str / Mar / CCo / Con / Sma / Tec
  19.  
  20. # Time between relogs (keep the login cookie updated!)
  21. relog_freq = 8 * 12 # n hours * 12 pt/hour
  22.  
  23. # Log in credentials
  24. myuser = 'your_user_name'
  25. mypass = 'your_password'
  26.  
  27. #########################################################################
  28.  
  29. def log(txt):
  30.     global l
  31.     txt = strftime("%d-%m-%Y %H:%M:%S ") + txt
  32.     print txt
  33.     l.write(txt + "\n")
  34.     l.flush()
  35.  
  36. def dumphtml(txt):
  37.     f = open("log.html","w")
  38.     f.write(str(txt))
  39.     f.close()
  40.  
  41. def login(br):
  42.     log("Opening url...")
  43.  
  44.     html = ""
  45.     while (html == ""):
  46.         try:
  47.             r = br.open('http://www.zombiepandemic.com')
  48.             html = r.read()
  49.         except HTTPError, e:
  50.             log("Got error code %s on main screen" % str(e.code))
  51.             fibowait()
  52.  
  53.     fibo_c = [ 0, 1 ]
  54.  
  55.     log("Logging in...")
  56.  
  57.     html = ""
  58.     while (html == ""):
  59.         try:
  60.             br.select_form(nr=0)
  61.             br.form['ctl00$TextBoxUsername']=myuser
  62.             br.form['ctl00$TextBoxPassword']=mypass
  63.             br.submit()
  64.  
  65.             html = br.response().read()
  66.         except HTTPError, e:
  67.             log("Got error code %s on logging in" % str(e.code))
  68.             fibowait()
  69.  
  70.     fibo_c = [ 0, 1 ]
  71.  
  72.     dumphtml(html)
  73.  
  74.     if (html.find("Krilla")!=-1):
  75.         log("Login successful.")
  76.  
  77.     elif (html.find("Invalid login information")!=-1):
  78.         log("Login unsuccessful; aborting.")
  79.         exit(1)
  80.  
  81.     else:
  82.         log("Unknown Error. Logging response and exiting")
  83.         exit(2)
  84.  
  85.     line = html[html.find("window.ZP.gamestate.activities.activityList"):]
  86.     s_start = line.find("[") +1;
  87.     s_end = line.find("]");
  88.     data = line[s_start:s_end]
  89.  
  90.     if (data == ""):
  91.         data = {'SecondsLeft':0}
  92.     else:
  93.         data = json.loads(data)
  94.  
  95.     return data
  96.  
  97. def pidfile(pidfile):
  98.     my_pid = str(os.getpid())
  99.     if os.access(pidfile, os.F_OK):
  100.         pf = open(pidfile, "r")
  101.         pf.seek(0)
  102.         old_pid = pf.readline()
  103.         pf.close()
  104.         if  ((my_pid != old_pid) and (os.path.exists("/proc/%s" % old_pid))):
  105.             print "Already running, with pid %s" % old_pid
  106.             exit(0)
  107.         else:
  108.             os.remove(pidfile)
  109.  
  110.     pf = open(pidfile, "w")
  111.     pf.write("%s" % my_pid)
  112.     pf.close()
  113.  
  114. def cleanup():
  115.     global pidfile
  116.     log("Saliendo.")
  117.     os.remove(mypidfile)
  118.  
  119. def fibowait():
  120.     global fibo_c
  121.     tmp = fibo_c[0]
  122.     fibo_c[0] = fibo_c[1]
  123.     fibo_c[1] = fibo_c[1] + tmp
  124.     log("Retrying in %i seconds" % fibo_c[1])
  125.     sleep(fibo_c[1])
  126.  
  127. # Check if already an instance running
  128. own_name = inspect.getfile(inspect.currentframe())
  129. f_s = own_name.find("/")+1
  130. f_e = own_name.rfind(".")
  131. if (f_e <= f_s):
  132.     f_e = ""
  133. mypidfile = "" + own_name[f_s:f_e] + ".pid"
  134. pidfile(mypidfile)
  135.  
  136. # Register cleanup function on TERM signal
  137. signal.signal(signal.SIGTERM, cleanup)
  138.  
  139. l = open("out.txt","w")
  140.  
  141. # Browser
  142. br = mechanize.Browser()
  143.  
  144. # Cookie Jar
  145. cj = cookielib.LWPCookieJar()
  146. br.set_cookiejar(cj)
  147.  
  148. # Browser options
  149. br.set_handle_equiv(True)
  150. br.set_handle_gzip(False)
  151. br.set_handle_redirect(True)
  152. br.set_handle_referer(True)
  153. br.set_handle_robots(False)
  154.  
  155. # Follows refresh 0 but not hangs on refresh > 0
  156. br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
  157.  
  158. # Want debugging messages?
  159. #br.set_debug_http(True)
  160. #br.set_debug_redirects(True)
  161. #br.set_debug_responses(True)
  162.  
  163. # User-Agent (this is cheating, ok?)
  164. br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
  165.  
  166. hdr = { 'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1',
  167. 'Accept': 'application/json, text/javascript, */*; q=0.01',
  168. 'Referer': 'http://www.zombiepandemic.com/sitepages/Location.aspx',
  169. 'DNT': '1',
  170. 'X-Requested-With': 'XMLHttpRequest',
  171. 'Content-Type': 'application/json; charset=utf-8'}
  172.  
  173. d = { "skillCode":attr,"points":"10" }
  174. train_data = json.dumps(d)
  175.  
  176. url = 'http://www.zombiepandemic.com/SitePages/Services/ActionService.asmx/StartTraining'
  177.  
  178.  
  179. msg_array = []
  180. fibo_c = [ 0, 1 ]
  181.  
  182. # Counter; set to login on 1st time
  183. c = relog_freq +1
  184.  
  185. try:
  186.     while (True): # Go on forever
  187.         if (c >= relog_freq):
  188.             data = login(br)
  189.             c = 0
  190.  
  191.         if (data['SecondsLeft'] > 0):
  192.             log("Sleeping for " + str(data['SecondsLeft']+1) + " seconds to finish training")
  193.             sleep(data['SecondsLeft']+1)
  194.  
  195.         log("Sending training request...")
  196.  
  197.         req = mechanize.Request(url, train_data, hdr)
  198.  
  199.         html = ""
  200.         while (html == ""):
  201.             try:
  202.                 r = br.open(req)
  203.                 html = r.read()
  204.  
  205.                 c = c + 1
  206.             except HTTPError, e:
  207.                 log("Got error code " + str(e.code) + " on start training")
  208.                 fibowait()
  209.  
  210.         fibo_c = [ 0, 1 ]
  211.  
  212.         dumphtml(html)
  213.  
  214.         msg_array = json.loads(html)
  215.         data = json.loads(msg_array["d"])["Activity"]
  216.  
  217.         log("Request sent for " + str(data['JobCode']) + ". Current points: " + str(data['CurrentPoints']) + " (counter = " + str(c) + ")")
  218.  
  219. except KeyboardInterrupt:
  220.     print "\nGot Ctrl-C"
  221. finally:
  222.     cleanup()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement