Jump to content
Sign in to follow this  
pete_wilde

Trying to convert a Python script to Autoit

Recommended Posts

Hi Guys,

I am trying to convert a python script to AutoIT, but it is not returning any data. :(

My aim is to eventually have a script which sends me an email whenever a goal is scored in the English Premiership.

Is there any guru who can have a quick look over the below script and see if there are any obvious errors?

To use a football analogy, I think that I have hit the bar a couple of times, but not yet found the back of the net! 

#cs ----------------------------------------------------------------------------
PYTHON CODE:
import requests
import json
endpoint = "https://api.betfair.com/exchange/betting/rest/v1.0/"
header = { 'X-Application' : 'APP_KEY_HERE', 'X-Authentication' : 'SESSION_TOKEN_HERE' ,'content-type' : 'application/json' }
json_req='{"filter":{ }}'
url = endpoint + "listEventTypes/"
response = requests.post(url, data=json_req, headers=header)
print json.dumps(json.loads(response.text), indent=3)
#ce ----------------------------------------------------------------------------

#include <WinHttp.au3>
Opt("MustDeclareVars", 1)
Opt("TrayIconDebug", 1)

 

Global $sAddress     = 'https://api.betfair.com/exchange/betting/json-rpc/v1/'
Global $sPostData    = 'https://api.betfair.com/exchange/betting/json-rpc/v1/listEventTypes/'
Global $sAppKey      = '4YpsEhdsgtedjd'     
Global $sSession_key = 'BhKl7Ijdu4E3pzHhKu7K5fQrvzf9p3wq/diRMt7bZka7'
Global $sjson_req    = '{"filter":{ }}'

 
Global $hOpen    = _WinHttpOpen()  ; Get Session handle 
; ##### CHECKED AND VALID HANDLE IS RETURNED #####

Global $hConnect = _WinHttpConnect($hOpen, $sAddress) ; Get connection handle
; ##### CHECKED AND VALID HANDLE IS RETURNED #####

Global $hRequest = _WinHttpOpenRequest($hConnect, 'POST') ; Make a request
; ##### CHECKED AND VALID HANDLE IS RETURNED #####

  
; Add header fields to the request
_WinHttpAddRequestHeaders($hRequest, 'X-Application: ' & $sAppKey)
_WinHttpAddRequestHeaders($hRequest, 'X-Authentication: ' & $sSession_key)
_WinHttpAddRequestHeaders($hRequest, 'Accept: application/json')
_WinHttpAddRequestHeaders($hRequest, 'Content-Type: application/json') 
_WinHttpSendRequest($sPostData, 'Data=' & $sjson_req, $hRequest) ; Send it
_WinHttpReceiveResponse($hRequest) ; Wait for the response

; Check if there is a response
Global $sHeader, $sReturned

If _WinHttpQueryDataAvailable($hRequest) Then
    $sHeader = _WinHttpQueryHeaders($hRequest)
    MsgBox(64, 'Header', $sHeader)
    Do
        $sReturned &= _WinHttpReadData($hRequest)
    Until @error
    ConsoleWrite($sReturned) ; Print returned
Else
    ConsoleWriteError('!No data available.' & @CRLF)
    MsgBox(48, 'Failure', 'No data available.')  ;##### <==== ALWAYS FAILS HERE! #####
EndIf

; Close handles
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

I am sure that I have probably missed out a vital line, but for the life of me I can't see the wood for the trees anymore.

Anyone got any suggestions?

Many thanks,

Pete

Share this post


Link to post
Share on other sites

Maybe like this:

#include "WinHttp.au3"

$sAddress = 'https://api.betfair.com/exchange/betting/json-rpc/v1/'
$sAppKey = '4YpsEhdsgtedjd'
$sSession_key = 'BhKl7Ijdu4E3pzHhKu7K5fQrvzf9p3wq/diRMt7bZka7'
$sjson_req = '{"filter":{ }}'

$hOpen = _WinHttpOpen()

$hConnect = _WinHttpConnect($hOpen, $sAddress)

$sReturned = _WinHttpSimpleSSLRequest($hConnect, "POST", "listEventTypes/", Default, $sjson_req, 'X-Application: ' & $sAppKey & @CRLF & 'X-Authentication: ' & $sSession_key & @CRLF & 'Content-Type: application/json', Default, Default, Default, Default, 1)

_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

ConsoleWrite($sReturned & @CRLF)

 

Edited by trancexx

♡♡♡

.

eMyvnE

Share this post


Link to post
Share on other sites

Hi Trancexx,

Many thanks for your quick response.

I have actually seen your solutions posted on many queries. You are seriously knowledgable my friend.

The script now returns the message:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Service not Found</title>  
    </head>
    <body>
        <b>The URL you specified did not correspond to a service.x</b>
    </body>
</html>

Normally, it should return a JSON string which the user then decodes.

It is much better than anything which I have got so far.

I will have a play about with it 🙂

Many thanks for your help.

Best regards,

Pete

 

Share this post


Link to post
Share on other sites

Any reason your code needs to be in AutoIt? You could run your python script and get the results in AutoIt through the command line (since your python code already works)

#include <AutoItConstants.au3>

; Start your python code
Local $iPID = Run('"C:\python\path\python.exe"' & '"C:\other\path\script.py"', @SW_HIDE, $STDOUT_CHILD)

; Wait for the python code to end
ProcessWaitClose($iPID)

; Read the results
Local $sResults = StdoutRead($iPID)

Edit: This would read everything you "print" out in your python script. Alternately, you could have your python write the results to a file

Edited by seadoggie01

All my code provided is Public Domain... but it may not work. ;) Use it, change it, break it, whatever you want.

Spoiler

My Humble Contributions:
Personal Function Documentation - A personal HelpFile for your functions
Acro.au3 UDF - Automating Acrobat Pro
ToDo Finder - Find #ToDo: lines in your scripts

Share this post


Link to post
Share on other sites
4 hours ago, pete_wilde said:

Hi Trancexx,

Many thanks for your quick response.

I have actually seen your solutions posted on many queries. You are seriously knowledgable my friend.

The script now returns the message:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Service not Found</title>  
    </head>
    <body>
        <b>The URL you specified did not correspond to a service.x</b>
    </body>
</html>

Normally, it should return a JSON string which the user then decodes.

It is much better than anything which I have got so far.

I will have a play about with it 🙂

Many thanks for your help.

Best regards,

Pete

 

Maybe besause it shoud be like in your original code unlike your AutoIt one: "https://api.betfair.com/exchange/betting/rest/v1.0/"


♡♡♡

.

eMyvnE

Share this post


Link to post
Share on other sites
19 hours ago, trancexx said:

Maybe besause it shoud be like in your original code unlike your AutoIt one: "https://api.betfair.com/exchange/betting/rest/v1.0/" 

Tried the alternative URL and got the same result.

Might just need something else added to the URL.

I will play about with it and see what happens.


You have definitely got me much further than I previously was, so many thanks for that. It is much appreciated 🙂

 

Share this post


Link to post
Share on other sites

Hello. If you want to use the JSON-RPC protocol endpoint you need to define your json correclty "method,params ,id." Otherwise you could use regular JSON REST endpoints and send just parameters.

Check Doc Table:

Interface
Endpoint
JSON-RPC Prefix
<method> Example
JSON-RPC https://api.betfair.com/exchange/betting/json-rpc/v1 <method> SportsAPING/v1.0/listMarketBook
JSON REST https://api.betfair.com/exchange/betting/rest/v1.0/   listMarketBook/

Saludos

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By MiKa666
      Hi all,
      I'm developing a tool for exploratively testing another software. For that I wanna cover all the GUI functionality from that software and verify everything works as intended. But now I've a problem which I couldnt solve so far.
      One thing that software I'm testing does, is to load up either a single picture or a series of pictures. Depending on how much pictures got loaded, further actions will be proceeded...
      This loaded pictures are schon within a ToolbarWindow and they're clickable. What I need to know is, how much pictures are in this ToolbarWindow...
      Can anybody provide me a tip on how to achive this?
      Would be amazing!!
      BR,
      Mic
    • By meety
      Hello!
      wingettext function can get the text content of the IE browser page, but the text content of the page cannot be obtained in the chrome browser? What should I do?
    • By DirtyJohny
      Hi everyone.Need rewrite this function how in еxample.
      Original:
      #RequireAdmin #NoTrayIcon Opt("MustDeclareVars",1) Func _a() Local $sls=ObjGet("winmgmts:{impersonationLevel=impersonate," _ &"authenticationLevel=Pkt}!\\"& _ @ComputerName&'\root\wmi'),$lss=$sls.ExecQuery _ ('SELECT * FROM WmiMonitorID'), _ $lll,$sll,$sss="",$lsl,$lls,$i,$z For $z In $lss $lsl=$z.UserFriendlyName For $i=0 To Ubound($lsl)-1 if ($lsl[$i]) Then $lll&=Chr($lsl[$i]) Next $lls=$z.SerialNumberID For $i=0 To Ubound($lls)-1 if ($lls[$i]) Then $sll&=Chr($lls[$i]) Next $sss&="Model"&@TAB&@TAB&": "&$lll&@CR&"Serial Number"&@TAB&": "&$sll&@CR&@CR $lll="" $sll="" Next MsgBox(262144,'Monitors '&$lss.Count,$sss&" "&@CR) $lss=Null $sls=Null EndFunc _a() Example:
      Func _InfoPC() Local $ObjService = ObjGet('winmgmts:{impersonationLevel = impersonate}!\\' & @ComputerName & '\root\cimv2') Local $ObjMB = $ObjService.ExecQuery('SELECT * FROM Win32_BaseBoard', 'WQL', 0x30) If IsObj($ObjService) Then For $objItemMB In $ObjMB $sInfo &= @TAB & 'Motherboard: ...... ' & $objItemMB.Product & @CRLF I'm beginner in this sphere and need  you all speak easy and simply because i'm Russian.Thanks)
    • By Deshanur
      Am trying to automate injecting credential on the login form for all kind of Web application for IE. I know how to identify the form name by viewing the source code and using the method - _IEFormGetObjByName($ie, $form_Name).
      I would like to know how to identify or get the form object for the web app where there is no form name tag for example below, for the is I have used - _IEFormGetCollection($ie, 0) to get the form object.
      My Question is does it work for all kind of application "_IEFormGetCollection($ie, 0)" how to identify Index value? is it always 0? is there any better solution?
      The final solution am looking for is find out form object, get the username, password field and inject credential and submit the form.
      How to find out index value? for the forms which does not have form name field.
      $login_form = _IEFormGetCollection($ie, 0) $email_field = _IEFormElementGetObjByName($login_form, $form_UserName) $pass_field = _IEFormElementGetObjByName($login_form, $form_password) $login_button = _IEFormElementGetObjByName($login_form, $form_submitbutton) _IEFormElementSetValue($email_field, $CmdLine[2]) _IEFormElementSetValue($pass_field, $CmdLine[3]) ControlSend($hwnd, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]","{Enter}") OR This works fine if the form has form name. $login_form = _IEFormGetObjByName($ie, $form_Name) $email_field = _IEFormElementGetObjByName($login_form, $form_UserName) $pass_field = _IEFormElementGetObjByName($login_form, $form_password) $login_button = _IEFormElementGetObjByName($login_form, $form_submitbutton) _IEFormElementSetValue($email_field, $CmdLine[2]) _IEFormElementSetValue($pass_field, $CmdLine[3]) ControlSend($hwnd, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]","{Enter}")
    • By JuanFelipe
      Hello guys!
      I have a problem with a script, in the past I made a program and it worked perfect, I recently used it again and it already stands still in one step, the problem is a Javascript event that changed but now I cannot execute it.
       
      <td colspan="2" align="center"><input type="button" id="Buscar" name="Buscar" value="Buscar" onclick="javascript:enviarForma(document.obtenercasosPersonaPorDocumento,'0');" class="boton"></td>  
      Previously I used this code and it worked, but now it does nothing
      $botonconsulta = _IEGetObjByName($oIE,"Buscar") _IEAction($botonconsulta, 'click') _IELoadWait($oIE)  
      Now I have tried the following codes but none works.
       
      ;==================== 1 _IEHeadInsertEventScript($oIE, "document", "onclick", "javascript:enviarForma(document.obtenercasosPersonaPorDocumento,'0');") ControlClick("SUPER CELAC", "", "[CLASS:Internet Explorer_Server; INSTANCE:1]") _IELoadWait($oIE) ;==================== 2 $forma = $oIE.document.obtenercasosPersonaPorDocumento $oIE.Navigate("JavaScript:enviarForma("&$forma&",""0"");") _IELoadWait($oIE) ;==================== 3 $boton = _IEGetObjById($oIE, "Buscar") $boton.document.parentwindow.execScript("enviarForma(document.obtenercasosPersonaPorDocumento,'0');", "javascript") I hope you can guide me, because I think the error is in the parameters that the javascript function receives but I don't know how to send it, here I leave the first part of the JavaScript function.
      function enviarForma(frm,tipoForma){ var bExisteDatoConsulta = false; var bError=true; var mensajeError=""; switch (tipoForma) { //--Forma documento case "0": if (validar_campo_no_vacio_no_print(frm.numeroDocumento)) { if (!isNum(frm.numeroDocumento.value)) { bError = false; mensajeError += "El número de documento debe ser un valor numérico\n"; } bExisteDatoConsulta = true; } else { mensajeError += "Debe digitar un número de documento\n"; } break;  Thanks!
×
×
  • Create New...