Skip to main content

Sending request using request library

Using request library for Pirates

 Few years ago using urllib2 was a simplest way for sending and receiving  HTTP Request. But now I'm using  Request library . This  is more simple and powerful. Unfortunately Request is not include in default install and Pip  should be used . 

Installation

 Procedure is really simple  and near to standard :

MacBook-Pro-Hohlov:pirates skhohlov$ virtualenv ./env
New python executable in ./env/bin/python2.7
Also creating executable in ./env/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-Hohlov:pirates skhohlov$ source ./env/bin/activate
(env)MacBook-Pro-Hohlov:pirates skhohlov$ 
(env)MacBook-Pro-Hohlov:pirates skhohlov$ 
(env)MacBook-Pro-Hohlov:pirates skhohlov$ pip install requests
Collecting requests
  Using cached requests-2.13.0-py2.py3-none-any.whl
Installing collected packages: requests
Successfully installed requests-2.13.0
You are using pip version 7.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.


Few lines of code. 

 Request has a good documentation at : http://docs.python-requests.org/en/master/   It will be nice to check it if you have any misunderstanding.   Lets back to pirates game.  One of the first request is three  requests for selecting  correct segment for playing. List   is a powerful and very important  feature of the python  language.  If you  have worked  with C or C++  you should  know  how  much time requires understanding of pointers and correct using. Python  is doing this in  light and easy to understand way. Good tutorial  is here : https://www.tutorialspoint.com/python/python_lists.htm    
I've created a function  hot to send requests and select proper segment for  future requests: 



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def detectdefaultsegment(gamesession, config):
    """ function for detecting default user segment"""
    BaseSegmentURLList = [
    'https://kpppen3s00.plrm.zone/PiratesPpEng3/Segment00/segment.ashx',
    'https://kpppen2s00.plrm.zone/PiratesPpEng2/Segment00/segment.ashx',
    'https://kpppen1s01.plrm.zone/PiratesPPeng/Segment00/segment.ashx']
        
    gamesession.headers.update({'sign-code':config['sign-code'], 'server-method':'GetTouch','client-ver':config['client-ver']})
    for  BUrl in BaseSegmentURLList:        
        answer=gamesession.post(BUrl,data="[\""+config['userid']+"\"]")
        if answer.text[0] is not '!':
            segmenturl = BUrl
    return segmenturl

How its works ?
 Lines  3-6 are  our python list  of the  url.
 Line 8 is adding some header to the request  such as client version , sever method etc.
 Lines 9-12 are python loop:  request is send to each url .  Correct answer is started from  digits (timestamp),  incorrect is started from symbol "!".  Correct URL is returned.
All script code are placed at : https://pastebin.com/ZB4LiXuw 

Looks like I will write only SignIn function. Other part is not interested for me.

Generating Signature and Sign in function. 

Article about  swf working with swf shows how to application "crypting" request  again bad guys. 


def generateSignature(jsonstring, servercommand,config ):
    """Generate checksum for sign-code header.
    Each POST request has this one."""
    matrix_string = "The Matrix has you..."    
    return hashlib.md5((matrix_string+jsonstring+servercommand+config['userid']+config['authkey']).encode('ascii')).hexdigest()

and our first  Sign in function  is look like :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def SignIn(gamesession, config, mainurl):
   """ function for SignIn. This not auth function,
   this function is used for marking for setting up flag
   for first signing in per day. """        
   JSON_STRING = """{"s":{"x":null,"gr":null,"l":"en-US","I'm":false,"s":null,"tg":0,"m":"myemail","ar":null,"de":null,"t":0,"a":false,"n":"nickname","vk":{"b":false},"u":"//cdn01.x-plarium.com/browser/content/portal/common/avatars/default_avatar.jpg","i":"pp24685509","fl":false,"np":false,"p":null,"d":"nickname;null;null;en_US;0;;","tip":null},"mr":"","l":"","i":"0","f":[""],"c":{"ht":"Portal","put":null,"i":1,"v":"1.0"},"t":-180,"rr":"https://plarium.com/en/strategy-games/pirates-tides-of-fortune/"}"""
   parsed_string = json.loads(JSON_STRING)
   print("email:{c[m]}, username:{c[n]}, userid:{c[i]}".format(c=parsed_string["s"]))
   print json.dumps(parsed_string)
   sign =  generateSignature(JSON_STRING, 'SignIn', config)
   gamesession.headers.update({'sign-code':sign, 'server-method':'SignIn','client-ver':config['client-ver'], 'signin-authSeed':config['authSeed'], 'signin-authKey':config['authkey'], 'signin-userId':config['userid']})
   answer = gamesession.post(mainurl,data=JSON_STRING)
   return answer


Main problem is understanding a string "JSON_STRING".  I've sorted out that this string contains nickname , email, link to photo etc.   Everyone  can get this string from  checking headers procedure, I've informed about this one or two weeks ago. Strings #6-8 print  this information.  Those string have debuging purpose only.  Strings #10-12 are preparing request  and sending it to server.
Other server command requires a similar job to our SignIn  function.
I have no interest for this and  I would like to do something  funny and smart  (Ex: Arduino or AI )

Comments

Popular posts from this blog

Upgrade postgres 9.4 to 9.6 at Debian linux

I'm using virtual server based on Debian Linux for some my free projects.  One of them is based on Postgres with PostGIS extension.   This windy rainy day is a good time for executing some upgrade. Also I would like to add partman extension for partituoning.
Checking new version. Update package list :
aptitude update Get: 1 http://ftp.debian.org/debian jessie-updates InRelease [145 kB] Get: 2 http://security.debian.org stretch/updates InRelease [62.9 kB] Get: 3 http://security.debian.org jessie/updates InRelease [63.1 kB]
 Check for new version:


dpkg-query -l postgresql* Desired=Unknown/Install/Remove/Purge/Hold| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)||/ Name Version Ar…

Small script for one of the plarium game

few notes about google games.
Goggle informed that access to the all games be closed after June, 30. I played "Pirates: Tides of fortune" and decided to limit my game time using small script. Detail is below.
Some history
First internet games were updated network games only. 15 years ago internet connection requires a lot of money and nobody had a problem with lagging of the other players. Usually games uses personal communication protocol. Warbirds, Aces High and Eve online use this way.
Next part use a browser and trivial HTTP protocol. One of the popular game in this area is travian . Travian player uses browser and every browser (PC, cell phone, tablet) can be used for playing. Of course, popularity of the game is related to graphics. Trivial HTTP does not have good power in this and other technology is used for this side. One of them is Flash . Unfortunately flash requires a lot of CPU : "Pirates" was near to froze at my old celeron with 512M…

Small python script for monitoring MySQL performance

I have few services which use MySQL as database server. I would like to have information about load in PNG  image  or  in Cacti app.
MySQL   has  performance information at 'SHOW STATUS' command.

Values  which  are monitored : 
 threads_running, threads_connected, thread_cached, slow_queries
 Of course,  it is really easy to add more variables.

Connection to MySQL is accomplished by MySQLdb  module. Typical example of usage is below :
import MySQLdb mydb = MySQLdb.connect(host = 'hostname', user = 'username', password = 'secret', database = 'mysatabase' ) mycursor = mydb.cursor() mycursor.execute('SQL command') sqlresult = cur.fetchall()
Storing data in rrd file is aviable via rrdtools package. This one is present in debian and Centos OS. example of creating file is below: import rrdtool rrdtool.create("myfile.rrd" , "DS:value1:datatype:hea…