Jump to content

Recommended Posts

Hi All

i am currently trying to add a function to my project that can send SMS, i have gone with Twilio for the sms service that use a REST API.

I have never worked with an API before, and could use some help.

I can get my function working with using cURL.exe and copy past command from the website with the following code. And thats great unfortunately i am have issue with character like æøå when sending a SMS appears like a box or ?. this does not happen if i do it from the website so it looks like a Unicode issue in curl.exe.

I have done some searching on the forum and understand that i should be able to implement this curl command with the WinHTTP UDF from @trancexx so i don't need a third part exe and it might fix my charater issue.

Unfortunately i really don't understand how i am to change curl commands to the WinHTTP and i was hoping some good maybe give me an example i could learn from.

Thanks in advanced

i have removed the AuthToken number from the script.

_SendSMS("00000000","SomeOne","SMS body info")

Func _SendSMS($SendTo,$SendFrom,$Msgtxt)

    $AccountSID = "ACbb765b3180d5938229eff8b8f63ed1bc"
    $AuthToken = "Auth Token number" 

    $Data = '"https://api.twilio.com/2010-04-01/Accounts/'&$AccountSID&'/Messages.json"'& _
    '-X POST \ --data-urlencode "To=+45'&$SendTo&'" \ --data-urlencode "From='&$SendFrom&'" \ --data-urlencode "Body='&$Msgtxt&'" \ -u '&$AccountSID&':'&$AuthToken&''
    ShellExecute(@ScriptDir&"\curl.exe","-k "&$Data)

;~  curl 'https://api.twilio.com/2010-04-01/Accounts/ACbb765b3180d5938229eff8b8f63ed1bc/Messages.json' -X POST \
;~  --data-urlencode 'To=+4500000000' \
;~  --data-urlencode 'From=Reception' \
;~  --data-urlencode 'Body=Test Body' \
;~  -u ACbb765b3180d5938229eff8b8f63ed1bc:[AuthToken]

EndFunc

 

 

Link to post
Share on other sites

Hi @Danp2

Thanks allot for that have been looking through the help files and what i could find in the forum and google

Unfortunately my big problem is that it can find out how i am supposed to parse the commands needed.

This is how far i have gotten so far, but it mostly just a changed example, still very unsure on how to parse the request and the header.

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)


#Region ========= Info from twilio site
;======================================================= Twilio Info from site ==========================
;================ Responce Header
;~ Access-Control-Allow-Credentials: true
;~ Access-Control-Allow-Headers: Accept, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since
;~ Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS
;~ Access-Control-Allow-Origin: *
;~ Access-Control-Expose-Headers: ETag
;~ Connection: keep-alive
;~ Content-Length: 207
;~ Content-Type: application/json
;~ Date: Mon, 12 Feb 2018 11:47:43 GMT
;~ Twilio-Request-Duration: 0.002
;~ Twilio-Request-Id: %delete%
;~ X-Powered-By: AT-5000
;~ X-Shenanigans: none
;====================================
;================= Request Header
;~ Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
;~ Accept-Encoding: gzip, deflate, br
;~ Accept-Language: en-US,en;q=0.5
;~ Authorization: Basic %delete%
;~ Connection: keep-alive
;~ Cookie: notice_preferences=2:
;~ Host: api.twilio.com
;~ Upgrade-Insecure-Requests: 1
;~ User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0
;=================================================================
#EndRegion

#Region ============= How to from stackoverflow
;=================================Twilio help from stackoverflow ===============
; Twilio evangelist here.

; As you mention to make a raw request to the Twilio REST API without a helper library you need to craft your own HTTP request. The specific HTTP Method you use for the request (GET,POST,PUT,DELETE) depends on what you want the API to do.

;~ Twilio uses simple Basic authorization to authorize users of the API. To use Basic Authentication with HTTP you need to include in your HTTP request the Authorization header and pass as its value the authorization scheme (in Twilio case this is "Basic") and a Base64 encoded string containing your accountsid and authtoken seperated by a semi-colon:

;~ [AccountSid]:[AuthToken]

;~ The HTTP header would end up looking something like this:

;~ Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

;~ For example of you wanted to have Twilio send a text message you would craft an HTTP request using the POST method that looks like this:

;~ POST https://api.twilio.com/2010-04-01/Accounts/[YOUR_ACCOUNT_SID]/Messages HTTP/1.1
;~ Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
;~ Host: api.twilio.com
;~ Content-Type: application/x-www-form-urlencoded
;~ Content-Length: 50

;~ To=+15555555555&From=+16666666666&Body=Hello World

;~ Hope that helps.
;============================================================
#EndRegion

Global $AccountSID = "ACbb765b3180d5938229eff8b8f63ed1bc"
Global $AuthToken = "Auth Token number"
Global $sAddress = "https://api.twilio.com"

;~ Encode data to Base64 for auth?
;~ $Credentials = $AccountSID&":"&$AuthToken

; Post data:

; Initialize and get session handle
Global $hOpen = _WinHttpOpen("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0")

; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, $sAddress, $INTERNET_DEFAULT_HTTPS_PORT)

; Make a request
Global $hRequest = _WinHttpOpenRequest($hConnect, _
        "POST", _
        "2010-04-01/Accounts/"&$AccountSID&"/Messages.xml", _ ;~        "2010-04-01/Accounts/"&$AccountSID&"/Messages.json", _
        Default, _
        Default, _
        "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", _
        $WINHTTP_FLAG_SECURE)

; Add header fields to the request
_WinHttpAddRequestHeaders($hRequest, "Authorization: Basic %deleted%")
_WinHttpAddRequestHeaders($hRequest, "Accept-Encoding: gzip, deflate, br")
_WinHttpAddRequestHeaders($hRequest, "Accept-Language: en-US,en;q=0.5")
_WinHttpAddRequestHeaders($hRequest, "Content-Type: application/x-www-form-urlencoded")
;~ _WinHttpAddRequestHeaders($hRequest, "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7")
_WinHttpAddRequestHeaders($hRequest, "Connection: keep-alive")
_WinHttpAddRequestHeaders($hRequest, "Keep-Alive: 300")
;~ _WinHttpAddRequestHeaders($hRequest, "Host: api.twilio.com")
;~ _WinHttpAddRequestHeaders($hRequest, "Upgrade-Insecure-Requests: 1")
;~ _WinHttpAddRequestHeaders($hRequest, "Content-Length: 50")

Global $sPostData = 'To=+4500000000&From=SomeOne&Body=Hello World'

; Send it
_WinHttpSendRequest($hRequest, -1, $sPostData)
; Wait for the response
_WinHttpReceiveResponse($hRequest)
; 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
    ; Print returned
    ConsoleWrite($sReturned)
Else
    ConsoleWriteError("!No data available." & @CRLF)
    MsgBox(48, "Failure", "No data available.")
EndIf

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








;~ _SendSMS("00000000","SomeOne","SMS body info")

Func _SendSMS($SendTo,$SendFrom,$Msgtxt)

    Local $AccountSID = "ACbb765b3180d5938229eff8b8f63ed1bc"
    Local $AuthToken = "Auth Token number"

    Local $Data = '"https://api.twilio.com/2010-04-01/Accounts/'&$AccountSID&'/Messages.json"'& _
    '-X POST \ --data-urlencode "To=+45'&$SendTo&'" \ --data-urlencode "From='&$SendFrom&'" \ --data-urlencode "Body='&$Msgtxt&'" \ -u '&$AccountSID&':'&$AuthToken&''
    ShellExecute(@ScriptDir&"\curl.exe","-k "&$Data)

;~  curl 'https://api.twilio.com/2010-04-01/Accounts/ACbb765b3180d5938229eff8b8f63ed1bc/Messages.json' -X POST \
;~  --data-urlencode 'To=+4500000000' \
;~  --data-urlencode 'From=Reception' \
;~  --data-urlencode 'Body=Test Body' \
;~  -u ACbb765b3180d5938229eff8b8f63ed1bc:[AuthToken]

EndFunc

 

Link to post
Share on other sites

Don't know if it would help you, but there is a curl udf written by ward

https://www.autoitscript.com/forum/topic/173067-curl-udf-autoit-binary-code-version-of-libcurl-with-ssl-support/

I use it for my Imgur udf.

 

Func _Imgur($dImg)
    
    Local $sLink
    Local $Curl = Curl_Easy_Init()
    If Not $Curl Then Return SetError(8, 0, -1)
    Local $sHtml = $Curl
    Local $sHeader = $Curl + 1 ; any number as identify
    Local $sList = Curl_Slist_Append(0, "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:34.0) Gecko/20100101 Firefox/34.0")
    $sList = Curl_Slist_Append($sList, 'Referer: http://imgur.com/')
    $sList = Curl_Slist_Append($sList, 'Type: Base64')
    $sList = Curl_Slist_Append($sList, "Authorization: client-ID MYID")
    Curl_Easy_Setopt($Curl, $CURLOPT_HTTPHEADER, $sList)
    Local $dBase64Image = _Base64Encode($dImg) ; Convert the image to Base64
    Curl_Easy_Setopt($Curl, $CURLOPT_URL, "https://api.imgur.com/3/upload/") ; If we wants to uploade an image
    Curl_Easy_Setopt($Curl, $CURLOPT_POST, 1)
    Curl_Easy_Setopt($Curl, $CURLOPT_COPYPOSTFIELDS, 'image=' & $dBase64Image)
    
    ; Checks use this to see the respons from server, and get img url/delete hash ect.
    Curl_Easy_Setopt($Curl, $CURLOPT_WRITEFUNCTION, Curl_DataWriteCallback())
    Curl_Easy_Setopt($Curl, $CURLOPT_WRITEDATA, $sHtml)
    Curl_Easy_Setopt($Curl, $CURLOPT_SSL_VERIFYPEER, 0)
    Local $Code = Curl_Easy_Perform($Curl)
    If $Code <> $CURLE_OK Then Return SetError(9, 0, Curl_Easy_StrError($Code))
    
    ; Decode the json returned from imgur
    Local $sJson = Json_Decode(BinaryToString(Curl_Data_Get($sHtml)))
    ; Image link
    $sLink = Json_Get($sJson, '["data"]["link"]')
    $sLink = BinaryToString(Curl_Data_Get($sHtml))
    Curl_Easy_Cleanup($Curl)
    Curl_Data_Cleanup($Curl)
    Curl_Slist_Free_All($sList)
    
    Return $sLink
EndFunc   ;==>_Imgur

Cheers

/Rex

Link to post
Share on other sites

@islandspapand

This code should works if you pass good params.

;==============================================================================================================================
; Function:         twilioSendSms($sAccountSid, $sAuthToken, $sTo, $sFrom, $sMessage)
;
; Description:      Send sms via Twilio Rest API. Requied paid account
;
; Parameter(s):     $sAccountSid -  string | Your account Sid.
;                   $sAuthToken -   string | Your account Authorization Token.
;                   $sTo -          string | Phone number 10 digits example "+14158675310"
;                   $sFrom -        string | Alphanumeric Sender ID supports up to 11 characters from the following categories:
;                                               Upper-case letters A-Z
;                                               Lower-case letters a-z
;                                               Numbers 0-9
;                                               Spaces
;                   $sMessage       string | Message to send.
;
; Return Value(s):  On Success - Set error to 200 and returns output data
;                   On Failure - Set error to 1 - failed to create object winhttp.
;                                             Any other error from Twilio web.
;
; Author (s):       Ascer
;===============================================================================================================================
Func twilioSendSms($sAccountSid, $sAuthToken, $sTo, $sFrom, $sMessage)

    Local $oHttp = ObjCreate("winhttp.winhttprequest.5.1")

    If Not IsObj($oHttp) Then Return SetError(1, 0, 1)

    Local $sStruct = "https://api.twilio.com/2010-04-01/Accounts/"
    $sStruct &= $sAccountSid & "/Messages"

    $oHttp.Open("POST", $sStruct, False)

    Local $sBase64 = StringReplace(base64($sAccountSid & ":" & $sAuthToken), @LF, "")

    $oHTTP.SetRequestHeader("Authorization", "Basic " & $sBase64)
    $oHTTP.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
    $oHTTP.SetRequestHeader("Content-Length", "50")

    Local $sRequest = "To=" & $sTo
    $sRequest &= "&From=" & $sFrom
    $sRequest &= "&Body=" & $sMessage

    $oHttp.Send($sRequest)

    Local $sOutput = $oHttp.ResponseText
    Local $iStatus = $oHttp.Status

    ConsoleWrite("iStatus: " & $iStatus & @CRLF)
    ConsoleWrite("$sOutput: " & $sOutput & @CRLF)

    Return SetError($iStatus, 0, $sOutput)

EndFunc

;==============================================================================================================================
; Function:         base64($vCode [, $bEncode = True [, $bUrl = False]])
;
; Description:      Decode or Encode $vData using Microsoft.XMLDOM to Base64Binary or Base64Url.
;                   IMPORTANT! Encoded base64url is without @LF after 72 lines. Some websites may require this.
;
; Parameter(s):     $vData      - string or integer | Data to encode or decode.
;                   $bEncode    - boolean           | True - encode, False - decode.
;                   $bUrl       - boolean           | True - output is will decoded or encoded using base64url shema.
;
; Return Value(s):  On Success - Returns output data
;                   On Failure - Returns 1 - Failed to create object.
;
; Author (s):       (Ghads on Wordpress.com), Ascer
;===============================================================================================================================
Func base64($vCode, $bEncode = True, $bUrl = False)

    Local $oDM = ObjCreate("Microsoft.XMLDOM")
    If Not IsObj($oDM) Then Return SetError(1, 0, 1)

    Local $oEL = $oDM.createElement("Tmp")
    $oEL.DataType = "bin.base64"

    If $bEncode then
        $oEL.NodeTypedValue = Binary($vCode)
        If Not $bUrl Then Return $oEL.Text
        Return StringReplace(StringReplace(StringReplace($oEL.Text, "+", "-"),"/", "_"), @LF, "")
    Else
        If $bUrl Then $vCode = StringReplace(StringReplace($vCode, "-", "+"), "_", "/")
        $oEL.Text = $vCode
        Return $oEL.NodeTypedValue
    EndIf

EndFunc ;==>base64

 

Edited by Ascer
Link to post
Share on other sites

 

Hi @Rex Thanks allot i will look into this as possibility our for future use :) looks interesting

Hi @Ascer  This is great just what i was looking for and with the Base64 that i could get my head around. i will test straight away.

After some playing around i finally got my script working but nowhere as nice/clean as yours. Found the encode Base64 credential on the Twilio account but would prefere to do it my self with the SID and Auth token

Thanks so much for the Help you guys very much appreciated

 

#include "WinHttp.au3"

;~ Opt("MustDeclareVars", 1)


#Region ========= Info from Twilio site ==========

;================= Request Header ===============================
;~ Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
;~ Accept-Encoding: gzip, deflate, br
;~ Accept-Language: en-US,en;q=0.5
;~ Authorization: Basic %delete%
;~ Connection: keep-alive
;~ Cookie: notice_preferences=2:
;~ Host: api.twilio.com
;~ Upgrade-Insecure-Requests: 1
;~ User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0
;=================================================================

;~ For special charater = https://www.w3schools.com/tags/ref_urlencode.asp

#EndRegion ===========================


Func _SendSMS($SendTo="",$SendFrom="",$MsgTxt="")

Local $Credentials = "$AccountSID&":"&$AuthToken  Encode data to Base64 for auth?"
Local $AccountSID = "Account SID"
Local $AuthToken = "Auth Token"
Local $sAddress = "https://api.twilio.com"

;~ æ = %C3%A6 | Æ = %C3%86
;~ ø = %C3%B8 | Ø = %C3%98
;~ å = %C3%A5 | Å = %C3%85

;======= Change Special Charaters in Text ======
$MsgTxt = StringReplace($MsgTxt, "æ", "%C3%A6", 0, 1)
$MsgTxt = StringReplace($MsgTxt, "Æ", "%C3%86", 0, 1)
$MsgTxt = StringReplace($MsgTxt, "ø", "%C3%B8", 0, 1)
$MsgTxt = StringReplace($MsgTxt, "Ø", "%C3%98", 0, 1)
$MsgTxt = StringReplace($MsgTxt, "å", "%C3%A5", 0, 1)
$MsgTxt = StringReplace($MsgTxt, "Å", "%C3%85", 0, 1)
;===============================================
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $MsgTxt = ' & $MsgTxt & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

; Error 1 = Missing Text, Phone or From Info
If BitOR($SendTo="",$SendFrom="",$MsgTxt="") Then Return SetError(1,0,False)

; Initialize and get session handle
Local $hOpen = _WinHttpOpen("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0")

; Get connection handle
Local $hConnect = _WinHttpConnect($hOpen, $sAddress, $INTERNET_DEFAULT_HTTPS_PORT)

; Make a request
Local $hRequest = _WinHttpOpenRequest($hConnect, _
        "POST", _
        "2010-04-01/Accounts/"&$AccountSID&"/Messages.json", _
        Default, _
        Default, _
        "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", _
        $WINHTTP_FLAG_SECURE)

; Add header fields to the request
_WinHttpAddRequestHeaders($hRequest, "Authorization: Basic "&$Credentials)
_WinHttpAddRequestHeaders($hRequest, "Accept-Encoding: gzip, deflate, br")
_WinHttpAddRequestHeaders($hRequest, "Accept-Language: en-US,en;q=0.5")
_WinHttpAddRequestHeaders($hRequest, "Content-Type: application/x-www-form-urlencoded")
_WinHttpAddRequestHeaders($hRequest, "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7")
_WinHttpAddRequestHeaders($hRequest, "Connection: keep-alive")
_WinHttpAddRequestHeaders($hRequest, "Keep-Alive: 300")

Local $sPostData = 'To=%2B'&$SendTo&'&From='&$SendFrom&'&Body='&$MsgTxt&''

; Send it
_WinHttpSendRequest($hRequest, Default, $sPostData)

; Wait for the response
_WinHttpReceiveResponse($hRequest)

; Check if there is a response
Local $sHeader, $sReturned
If _WinHttpQueryDataAvailable($hRequest) Then
    $sHeader = _WinHttpQueryHeaders($hRequest)
;~  MsgBox(64, "Header", $sHeader)
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $sHeader = ' & $sHeader & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    Do
        $sReturned &= _WinHttpReadData($hRequest)
    Until @error
    ; Print returned
    ConsoleWrite($sReturned & @CRLF)
    If StringInStr($sHeader,"201 CREATED") <> 0 Then
        _WinHttpCloseHandle($hRequest)
        _WinHttpCloseHandle($hConnect)
        _WinHttpCloseHandle($hOpen)
        Return True
    Else
        _WinHttpCloseHandle($hRequest)
        _WinHttpCloseHandle($hConnect)
        _WinHttpCloseHandle($hOpen)
        Return False
    EndIf
Else
    ConsoleWriteError("!No data available." & @CRLF)
    _WinHttpCloseHandle($hRequest)
    _WinHttpCloseHandle($hConnect)
    _WinHttpCloseHandle($hOpen)
    Return False
EndIf


EndFunc

 

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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Danyfirex
      Hello guys.  I recently saw some posts that Windows 10 provides OCR API. So I decided to create a UDF.
       
       
      What's UWPOCR?
      UWPOCR UDF is a simple library to use Universal Windows Platform Optical character recognition API.
      Features.
      Get Text From Image File. Get Text From GDI+ Bitmap. Easy to use.  Usage:
      #include "..\UWPOCR.au3" _Example() Func _Example() Local $sOCRTextResult = _UWPOCR_GetText(FileOpenDialog("Select Image", @ScriptDir & "\", "Images (*.jpg;*.bmp;*.png;*.tif;*.gif)")) MsgBox(0,"",$sOCRTextResult) EndFunc Get Words Rect(Example):

       
      More examples here.
       
      Check UWPOCR UDF on GitHub.
       
      Saludos
    • By mLipok
      I try to download some file with winhttp.au3
      I use code from here:

      My code looks like:
      #include <FileConstants.au3> #include "WinHttp.au3" #AutoIt3Wrapper_Run_AU3Check=N _Example() Func _Example() ; Initialize and get session handle Local $hOpen = _WinHttpOpen() ; Get connection handle Local $hConnect = _WinHttpConnect($hOpen, "https://MY_URL") Local $CurrentOption = _WinHttpQueryOption($hConnect, $WINHTTP_OPTION_SECURITY_FLAGS) Local $Options = BitOR($CurrentOption, _ $SECURITY_FLAG_IGNORE_UNKNOWN_CA, _ $SECURITY_FLAG_IGNORE_CERT_CN_INVALID, _ $SECURITY_FLAG_IGNORE_CERT_DATE_INVALID) _WinHttpSetOption($hConnect, $WINHTTP_OPTION_SECURITY_FLAGS, $Options) If @error Then ConsoleWrite("! ---> @error=" & @error & " @extended=" & @extended & _ " : _WinHttpSetOption" & @CRLF) ; Specify the reguest Local $hRequest = _WinHttpOpenRequest($hConnect, Default, "MY_FILE") ; Send request _WinHttpSendRequest($hRequest) ; Wait for the response _WinHttpReceiveResponse($hRequest) ProgressOn("Downloading", "In Progress...") Progress(_WinHttpQueryHeaders($hRequest, $WINHTTP_QUERY_CONTENT_LENGTH)) Local $sData ; Check if there is data available... If _WinHttpQueryDataAvailable($hRequest) Then While 1 $sChunk = _WinHttpReadData_Ex($hRequest, Default, Default, Default, Progress) If @error Then ExitLoop $sData &= $sChunk Sleep(20) WEnd Else MsgBox(48, "Error", "Site is experiencing problems (or you).") EndIf Sleep(1000) ProgressOff() ; Close handles _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) Local $hFile = FileOpen(@ScriptDir & "\MY_FILE", $FO_OVERWRITE + $FO_CREATEPATH + $FO_BINARY) FileWrite($hFile, $sData) FileClose($hFile) EndFunc ;==>_Example Func Progress($iSizeAll, $iSizeChunk = 0) Local Static $iMax, $iCurrentSize If $iSizeAll Then $iMax = $iSizeAll $iCurrentSize += $iSizeChunk Local $iPercent = Round($iCurrentSize / $iMax * 100, 0) ProgressSet($iPercent, $iPercent & " %") EndFunc ;==>Progress Func _WinHttpReadData_Ex($hRequest, $iMode = Default, $iNumberOfBytesToRead = Default, $pBuffer = Default, $vFunc = Default) __WinHttpDefault($iMode, 0) __WinHttpDefault($iNumberOfBytesToRead, 8192) __WinHttpDefault($vFunc, 0) Local $tBuffer, $vOutOnError = "" If $iMode = 2 Then $vOutOnError = Binary($vOutOnError) Switch $iMode Case 1, 2 If $pBuffer And $pBuffer <> Default Then $tBuffer = DllStructCreate("byte[" & $iNumberOfBytesToRead & "]", $pBuffer) Else $tBuffer = DllStructCreate("byte[" & $iNumberOfBytesToRead & "]") EndIf Case Else $iMode = 0 If $pBuffer And $pBuffer <> Default Then $tBuffer = DllStructCreate("char[" & $iNumberOfBytesToRead & "]", $pBuffer) Else $tBuffer = DllStructCreate("char[" & $iNumberOfBytesToRead & "]") EndIf EndSwitch Local $sReadType = "dword*" If BitAND(_WinHttpQueryOption(_WinHttpQueryOption(_WinHttpQueryOption($hRequest, $WINHTTP_OPTION_PARENT_HANDLE), $WINHTTP_OPTION_PARENT_HANDLE), $WINHTTP_OPTION_CONTEXT_VALUE), $WINHTTP_FLAG_ASYNC) Then $sReadType = "ptr" Local $aCall = DllCall($hWINHTTPDLL__WINHTTP, "bool", "WinHttpReadData", _ "handle", $hRequest, _ "struct*", $tBuffer, _ "dword", $iNumberOfBytesToRead, _ $sReadType, 0) If @error Or Not $aCall[0] Then Return SetError(1, 0, "") If Not $aCall[4] Then Return SetError(-1, 0, $vOutOnError) If IsFunc($vFunc) Then $vFunc(0, $aCall[4]) If $aCall[4] < $iNumberOfBytesToRead Then Switch $iMode Case 0 Return SetExtended($aCall[4], StringLeft(DllStructGetData($tBuffer, 1), $aCall[4])) Case 1 Return SetExtended($aCall[4], BinaryToString(BinaryMid(DllStructGetData($tBuffer, 1), 1, $aCall[4]), 4)) Case 2 Return SetExtended($aCall[4], BinaryMid(DllStructGetData($tBuffer, 1), 1, $aCall[4])) EndSwitch Else Switch $iMode Case 0, 2 Return SetExtended($aCall[4], DllStructGetData($tBuffer, 1)) Case 1 Return SetExtended($aCall[4], BinaryToString(DllStructGetData($tBuffer, 1), 4)) EndSwitch EndIf EndFunc ;==>_WinHttpReadData_Ex
      As a result I get file with this contents:
       
      As so far I found this:
        

      So I even with added:
      Local $CurrentOption = _WinHttpQueryOption($hConnect, $WINHTTP_OPTION_SECURITY_FLAGS) Local $Options = BitOR($CurrentOption, _ $SECURITY_FLAG_IGNORE_UNKNOWN_CA, _ $SECURITY_FLAG_IGNORE_CERT_CN_INVALID, _ $SECURITY_FLAG_IGNORE_CERT_DATE_INVALID) _WinHttpSetOption($hConnect, $WINHTTP_OPTION_SECURITY_FLAGS, $Options) If @error Then ConsoleWrite("! ---> @error=" & @error & " @extended=" & @extended & _ " : _WinHttpSetOption" & @CRLF)
      I still get the same errors.

      Anyone know a way how to fix this problem?

      Regards,
      mLipok
       
    • By mLipok
      This is TeamViewer.au3 UDF for TeamViewer API.
      ; #INDEX# ======================================================================== ; Title .........: TeamViewer.au3 ; AutoIt Version : 3.3.10.2++ ; Language ......: English ; Description ...: A collection of function for use with TeamViewer API ; Author ........: mLipok ; Modified ......: ; URL ...........: ; URL ...........: https://www.teamviewer.com/ ; URL ...........: https://www.teamviewer.com/en/integrations/ ; URL ...........: https://integrate.teamviewer.com/en/develop/api/get-started/ ; URL ...........: https://downloadeu1.teamviewer.com/integrate/TeamViewer_API_Documentation.pdf ; Remarks .......: This UDF was created based on TeamViewer_API_Documentation.pdf v 1.4.1 ; Remarks .......: This UDF is using Free Chilkat component look here https://www.autoitscript.com/forum/files/file/433-chilkat-udf/ ; Remarks .......: Documentation is "work in progress" ; Date ..........: 2017/02/08 ; Version .......: 0.1.1 BETA - Work in progress ; ================================================================================ in TeamViewer_Example.au3 you can see few examples:

       
      Func _Example() ; If not exist then create new INI file from template If Not FileExists('TeamViewer_Example.ini') Then FileCopy('TeamViewer_Example — Template.ini', 'TeamViewer_Example.ini') ; Read Access Token from INI Local $sTV_AccessToken = IniRead('TeamViewer_Example.ini', 'Settings', 'AccessToken', '') If $sTV_AccessToken = '' Then ; Your Access Token, can be left empty when OAuth (below) is configured. ; ClientId = <----------------- Create an app in your TeamViewer Management Console and insert the client ID to the INI ; ClientSecret = <------------- Insert your client secret to the INI ; AuthorizationCode = <-------- Visit https://webapi.teamviewer.com/api/v1/oauth2/authorize?response_type=code&client_id=YOUR$i_ClientIdHERE ; Login, grant the permissions (popup) and put the code shown in the AuthorizationCode variable to the INI Local $sTVOAuth_ClientID = IniRead('TeamViewer_Example.ini', 'OAuth2', 'ClientID', '') Local $sTVOAuth_ClientSecret = IniRead('TeamViewer_Example.ini', 'OAuth2', 'ClientSecret', '') _IECreate('https://webapi.teamviewer.com/api/v1/oauth2/authorize?response_type=code&client_id=' & $sTVOAuth_ClientID) ; Local $sTVOAuth_AuthorizationCode = IniRead('TeamViewer_Example.ini', 'OAuth2', 'authorizationCode', '') Local $sTVOAuth_AuthorizationCode = InputBox('AuthorizationCode', 'Please provide TV OAuth2 AuthorizationCode') If @error Then Return If $sTVOAuth_ClientID Then $sTV_AccessToken = _TVAPI_RequestOAuth2_AccessToken($sTVOAuth_ClientID, $sTVOAuth_ClientSecret, $sTVOAuth_AuthorizationCode) EndIf If $sTV_AccessToken Then _TVAPI_AccessToken($sTV_AccessToken) If _TVAPI_Ping() = True Then ; ping API to check connection and $sTV_AccessToken _Example_TeamViewer__1_Devices_SaveToFile() ;~ _Example_TeamViewer__2_Devices_ChangeDetails() ;~ _Example_TeamViewer__3_Devices_GetDevicesSingleID() ;~ _Example_TeamViewer__4_Reports_GetAllConnections() ;~ _Example_TeamViewer__5_Users_GetUserInfomation() ;~ _Example_TeamViewer__6_Groups_ListGroups() ;~ _Example_TeamViewer__7_Devices_AddDeleteDevice() Else MsgBox(0, '_TVAPI_Ping', "$v_Token or connection problem.") EndIf EndFunc ;==>_Example You can download it here:
      I'm using TeamViewer_Example.ini to store my secret tokens/keys.
      [Settings] AccessToken= [OAuth2] ClientID= ClientSecret= authorizationCode=  
    • By adityaparakh
      Hello ,
      I am trying to use Websockets in AutoIt.
      It is to fetch live stock market prices , API is provided and documentation available for python language.
      The link for the code snippet is :
      https://symphonyfintech.com/xts-market-data-front-end-api-v2/#tag/Introduction
      https://symphonyfintech.com/xts-market-data-front-end-api-v2/#tag/Instruments/paths/~1instruments~1subscription/post
       
      https://github.com/symphonyfintech/xts-pythonclient-api-sdk
       
      Second Link is to subscribe to a list of ExchangeInstruments.
      Now I would like to get live stock ltp (LastTradedPrice) for a few stocks whose "ExchangeInstrumentID" I know.
      I am able to use the WinHttp object to perform actions using simple codes like below :
      I have the secretKey and appkey and can generate the needed token. And get the unique ExchangeInstrumentID.

      Below code is just for example of how I am using WinHttp. Unrelated to socket part.
      Global $InteractiveAPItoken = IniRead(@ScriptDir & "\Config.ini", "token", "InteractiveAPItoken", "NA") $baseurl = "https://brokerlink.com/interactive/" $functionurl = "orders" $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("POST", $baseurl & $functionurl, False) $oHTTP.SetRequestHeader("Content-Type", "application/json;charset=UTF-8") $oHTTP.SetRequestHeader("authorization", $InteractiveAPItoken) $pD = '{ "exchangeSegment": "NSEFO", "exchangeInstrumentID": ' & $exchangeInstrumentID & ', "productType": "' & $producttype & '", "orderType": "MARKET", "orderSide": "' & $orderside & '", "timeInForce": "DAY", "disclosedQuantity": 0, "orderQuantity": ' & $qty & ', "limitPrice": 0, "stopPrice": 0, "orderUniqueIdentifier": "' & $orderidentifier & '"}' $oHTTP.Send($pD) $oReceived = $oHTTP.ResponseText $oStatusCode = $oHTTP.Status
          
          
      But am struggling to understand and use socket.
      Would be of great help if you can have a look at the link mentioned above and help with the code sample for AutoIt.
      To connect and listen to a socket.
      Thanks a lot
       
    • By Mr_Microphone
      Alright, I may be an idiot.
      Three years ago, I wrote a program that pushed component information to a secure site via their API. I went back to add some attributes and (here's the idiot part) ended up losing the  source code and my modified code does not quite work. I have the compiled version that works minus the new attributes, so I know that their system has not changed. I stripped the larger program down from 3,000 lines to the part that is broken, but I am stumped. This was one of my first scripts, so it heavily leverages examples and isn't as pretty as I'd like it to be.
      Be gentle. 
      The program / script creates a new records as expected, but for some reason, I cannot access information in the response, which I need for a later step.
      I use Charles, a web debugging proxy tool so I can see the request and the response and both are as expected. Also, when I write to log file, the JSON reply is exactly what I expect and need, but when I try to do anything with the http body, it seems to be blank. 
      Here is the script minus  the URL and token:
      #include <Array.au3> #include <Curl.au3> #include <MsgBoxConstants.au3> #include <json.au3>  ; this was added as an alternate way to read the data Global $WM_serial_number = "WM20745001" Global $wm_component_status_id = "10" Global $wm_manufacturer ="Multi-Tech" Global $wm_model = "MTR-LAT1-B07" Global $cellular_carrier_id = "3" Global $iccid_esn = "89010303300012345678" Global $ip_address = "192.168.2.11" Global $NewIDNumber     Local $Curl = Curl_Easy_Init()     Local $Html = $Curl ; any number as identify     Local $Header = $Curl + 1 ; any number as identify     Local $HtmlFile = "cURL_Request.html"     Local $File = FileOpen($HtmlFile, 2 + 16)     Local $Slist = Curl_Slist_Append(0, "content-type: multipart/form-data; boundary=---011000010111000001101001")     $Slist = Curl_Slist_Append($Slist, "authorization: Token token=" & $Token)     Curl_Easy_Setopt($Curl, $CURLOPT_PROXY, "127.0.0.1") ; needed to use Charles web debugging proxy     Curl_Easy_Setopt($Curl, $CURLOPT_PROXYPORT, 8888) ; needed to use Charles     Curl_Easy_Setopt($Curl, $CURLOPT_HTTPHEADER, $Slist) ;     Curl_Easy_Setopt($Curl, $CURLOPT_URL, $Server & "wireless_module" & "s")     Curl_Easy_Setopt($Curl, $CURLOPT_SSL_VERIFYPEER, 0)     Curl_Easy_Setopt($Curl, $CURLOPT_TIMEOUT, 30)     Curl_Easy_Setopt($Curl, $CURLOPT_WRITEDATA, $Html)     Curl_Easy_Setopt($Curl, $CURLOPT_WRITEFUNCTION, Curl_FileWriteCallback())     Curl_Easy_Setopt($Curl, $CURLOPT_WRITEDATA, $File)     Local $HttpPost = ""     Local $LastItem = ""         Curl_FormAdd($HttpPost, $LastItem, $CURLFORM_COPYNAME, "wireless_module" & "[serial_number]", $CURLFORM_COPYCONTENTS, $WM_serial_number, $CURLFORM_END)         Curl_FormAdd($HttpPost, $LastItem, $CURLFORM_COPYNAME, "wireless_module" & "[component_status_id]", $CURLFORM_COPYCONTENTS, $wm_component_status_id, $CURLFORM_END)         Curl_FormAdd($HttpPost, $LastItem, $CURLFORM_COPYNAME, "wireless_module" & "[manufacturer]", $CURLFORM_COPYCONTENTS, $wm_manufacturer, $CURLFORM_END)         Curl_FormAdd($HttpPost, $LastItem, $CURLFORM_COPYNAME, "wireless_module" & "[model]", $CURLFORM_COPYCONTENTS, $wm_model, $CURLFORM_END)         Curl_FormAdd($HttpPost, $LastItem, $CURLFORM_COPYNAME, "wireless_module" & "[cellular_carrier_id]", $CURLFORM_COPYCONTENTS, $cellular_carrier_id, $CURLFORM_END)         Curl_FormAdd($HttpPost, $LastItem, $CURLFORM_COPYNAME, "wireless_module" & "[iccid_esn]", $CURLFORM_COPYCONTENTS, $iccid_esn, $CURLFORM_END)         Curl_FormAdd($HttpPost, $LastItem, $CURLFORM_COPYNAME, "wireless_module" & "[ip_address]", $CURLFORM_COPYCONTENTS, $ip_address, $CURLFORM_END)         ; submit         Curl_Easy_Setopt($Curl, $CURLOPT_HTTPPOST, $HttpPost)         Local $Code = Curl_Easy_Perform($Curl)         If $Code = $CURLE_OK Then         ConsoleWrite("Content Type: " & Curl_Easy_GetInfo($Curl, $CURLINFO_CONTENT_TYPE) & @LF)         ConsoleWrite("Download Size: " & Curl_Easy_GetInfo($Curl, $CURLINFO_SIZE_DOWNLOAD) & @LF)         MsgBox(0, 'Html', BinaryToString(Curl_Data_Get($Html))) ; this is something I threw in for debugging, expecting to see SOMETHING. Returns nothing         MsgBox(0, 'Header', BinaryToString(Curl_Data_Get($Header))) ; this is something I threw in for debugging, expecting to see SOMETHING. Returns nothing         Local $response = Curl_Easy_GetInfo($Curl, $CURLINFO_RESPONSE_CODE)             If $response = "409" Then $response = "Failed due to a conflict."             If $response = "200" Then $response = "Was NOT created."             If $response = "201" Then $response = "Was created."             ; read the ID that was assigned and store it         $NewIDNumber = StringRight(StringLeft(BinaryToString(Curl_Data_Get($Html)), 10), 4) ; this DID work, but now it doesn't. An old compiled version still works ;~         Global $JsonObject = json_decode($Html); another debugging attempt. Did not use json functions previously and the program worked without it. ;~         Global $NewIDNumber = json_get($JsonObject, '.id')         ConsoleWrite(@CRLF &'! id:' & $NewIDNumber & @CRLF & @CRLF)    ; debugging feedback         MsgBox(0, $response, $wm_serial_number & " new ID = " & $NewIDNumber); debugging feedback         If $Code <> $CURLE_OK Then ConsoleWrite(Curl_Easy_StrError($Code) & @LF)             Local $Data = BinaryToString(Curl_Data_Get($Curl))             Curl_Easy_Cleanup($Curl)             Curl_Data_Cleanup($Curl)             Curl_Data_Cleanup($Header)             Curl_Data_Cleanup($Html)             Curl_FormFree($HttpPost)             Curl_slist_free_all($Slist)             curl_easy_reset($Curl)             FileClose($File)             ConsoleWrite(@LF)         EndIf  This is the captured request (minus the host and token)
      POST /api/v2/wireless_modules HTTP/1.1 Host: api. Accept: */* authorization: Token token= Content-Length: 942 Expect: 100-continue content-type: multipart/form-data; boundary=---011000010111000001101001; boundary=------------------------9adb0d87c7ea5061 --------------------------9adb0d87c7ea5061 Content-Disposition: form-data; name="wireless_module[serial_number]" WM20745001 --------------------------9adb0d87c7ea5061 Content-Disposition: form-data; name="wireless_module[component_status_id]" 10 --------------------------9adb0d87c7ea5061 Content-Disposition: form-data; name="wireless_module[manufacturer]" Multi-Tech --------------------------9adb0d87c7ea5061 Content-Disposition: form-data; name="wireless_module[model]" MTR-LAT1-B07 --------------------------9adb0d87c7ea5061 Content-Disposition: form-data; name="wireless_module[cellular_carrier_id]" 3 --------------------------9adb0d87c7ea5061 Content-Disposition: form-data; name="wireless_module[iccid_esn]" 89010303300012345678 --------------------------9adb0d87c7ea5061 Content-Disposition: form-data; name="wireless_module[ip_address]" 192.168.2.11 --------------------------9adb0d87c7ea5061-- and the captured response
      HTTP/1.1 201 Created Date: Sun, 04 Apr 2021 00:12:18 GMT Server: Apache Cache-Control: max-age=0, private, must-revalidate Access-Control-Allow-Origin: not-allowed Vary: Accept-Encoding Access-Control-Max-Age: 1728000 X-XSS-Protection: 1; mode=block X-Request-Id: 71cfcf36-6020-48a6-a822-d2b393a27b69 Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: PUT, OPTIONS, GET, POST ETag: W/"25d97fe8a9387cb4b9029a9e62b0bfa2" X-Frame-Options: SAMEORIGIN, SAMEORIGIN X-Runtime: 0.344005 X-Content-Type-Options: nosniff Access-Control-Request-Method: * X-Powered-By: Phusion Passenger 5.2.1 Strict-Transport-Security: max-age=63072000; includeSubDomains; preload Location: /wireless_modules/3195 Status: 201 Created Connection: close Transfer-Encoding: chunked Content-Type: application/json; charset=utf-8 X-Charles-Received-Continue: HTTP/1.1 100 Continue {"id":3195,"model":"MTR-LAT1-B07","serial_number":"WM20745001","manufacturer":"Multi-Tech","mfg_date":null,"iccid_esn":"89010303300012345678","ip_address":"192.168.2.11","purchase_order":null,"supplier":null,"cellular_carrier_id":3,"component_status_id":10,"component_status":{"id":10,"name":"Hold","description":"Available- Held for specific use"},"custom_attributes":[{"name":"Deactivated","type":"Boolean","value":false},{"name":"Port 3001","type":"Boolean","value":false}],"comments":[]}  
      Also attached is the log file. I need to read the id value. Clearly, it is arriving back to cURL, since it is being written out to the log, but I cannot seem to get to it within the code. 
      It is established that I may be an idiot, but this idiot has wasted days in non-billable hours trying to figure out what should be a simple glitch.
      Help???
       
      cURL_Request.html
×
×
  • Create New...