Jump to content
Sign in to follow this  
islandspapand

Convert curl command to WinHttp

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

 

 

Share this post


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

 

Share this post


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

Share this post


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

Share this post


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

 

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 tarretarretarre
      About AutoIt-API-WS
      AutoIt-API-WS is a light weight web server with expressive syntax, with the sole purpose of wrapping your existing AutoIt app with little to no effort.
      With AutoIt-API-WS you can send and receive data between any application or framework, as long they can handle HTTP requests, which is an industry standard today.
      Like my other communcations UDF AutoIt-Socket-IO AutoIt-API-WS is heavily inspired from the big boys, but this time its Laravel and Ruby on Rails.
      Features Highlights
      No external or internal dependencies required RESTful mindset when designed Expressive syntax Small codebase Heavy use of Michelsofts Dictionary object Limitations
      Not complient with any RFC, so something important could be missing. Time will tell! One persons slow loris attack will kill the process forever. Example of implemetnation (With screenshots)
      This is a basic cRud operation with the RESTful mindset in use.
      #include "API.au3" #include <Array.au3> _API_MGR_SetName("My APP DB adapter") _API_MGR_SetVer("1.0 BETA") _API_MGR_SetDescription("This adapter allows you to get this n that") _API_MGR_Init(3000) _API_MGR_ROUTER_GET('/users', CB_GetUsers, 'string sortBy', 'Get all users, sortBy can be either asc or desc. asc is default') _API_MGR_ROUTER_GET('/users/{id}', CB_GetUsersById, 'int id*', 'Get user by id') While _API_MGR_ROUTER_HANDLE() WEnd Func DB_GetUsers() Local $userA = ObjCreate("Scripting.Dictionary") Local $userB = ObjCreate("Scripting.Dictionary") $userA.add('id', 1) $userA.add('name', 'TarreTarreTarre') $userA.add('age', 27) $userB.add('id', 2) $userB.add('name', @UserName) $userB.add('age', 22) Local $aRet = [$userA, $userB] Return $aRet EndFunc Func CB_GetUsers(Const $oRequest) Local $aUsers = DB_GetUsers() If $oRequest.exists('sortBy') Then Switch $oRequest.item('sortBy') Case Default Case 'asc' Case 'desc' _ArrayReverse($aUsers) EndSwitch EndIf Return $aUsers EndFunc Func CB_GetUsersById(Const $oRequest) Local Const $aUsers = DB_GetUsers() Local $foundUser = Null For $i = 0 To UBound($aUsers) -1 Local $curUser = $aUsers[$i] If $curUser.item('id') == $oRequest.item('#id') Then $foundUser = $curUser ExitLoop EndIf Next If Not IsObj($foundUser) Then Return _API_RES_NotFound(StringFormat("Could not find user with ID %d", $oRequest.item('#id'))) EndIf return $foundUser EndFunc When you visit http://localhost:3000 you are greeted with this pleasent view that will show you all your registred routes and some extra info you have provided.

      When you visit http://localhost:3000/users the UDF will return the array of objects as Json
       
      And here is an example of http://localhost:3000/users/1

       
      More examples can be found here
       
       (NEWEST 2020-09-21)
      Autoit-API-WS-1.0.3-beta.zip
      OLD VERSIONS
      Autoit-API-WS-1.0.0-beta.zip Autoit-API-WS-1.0.1-beta.zip
       
    • By Colduction
      Hi AutoIt Members and Programmers, i have a problem with Telegram UDF that does not work on some of my servers, Telegram is not restricted in these machines, here is console output in Windows 7 (Server):
      >"C:\Program Files (x86)\AutoIt3\SciTE\..\AutoIt3.exe" "C:\Program Files (x86)\AutoIt3\SciTE\AutoIt3Wrapper\AutoIt3Wrapper.au3" /run /prod /ErrorStdOut /in "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3" /UserParams +>20:20:40 Starting AutoIt3Wrapper (19.1127.1402.0} from:SciTE.exe (4.2.0.0) Keyboard:00000429 OS:WIN_7/Service Pack 1 CPU:X64 OS:X64 Environment(Language:0409) CodePage:0 utf8.auto.check:4 +> SciTEDir => C:\Program Files (x86)\AutoIt3\SciTE UserDir => C:\Users\.NetFramework\AppData\Local\AutoIt v3\SciTE\AutoIt3Wrapper SCITE_USERHOME => C:\Users\.NetFramework\AppData\Local\AutoIt v3\SciTE >Running AU3Check (3.3.14.5) from:C:\Program Files (x86)\AutoIt3 input:C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3 +>20:20:40 AU3Check ended.rc:0 >Running:(3.3.14.5):C:\Program Files (x86)\AutoIt3\autoit3.exe "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3" +>Setting Hotkeys...--> Press Ctrl+Alt+Break to Restart or Ctrl+BREAK to Stop. Test file for Telegram UDF (https://github.com/xLinkOut/telegram-udf-autoit). This file need a valid ChatID of a Telegram user who has already sent at least a message to the bot, and a valid token given by @BotFather. Insert this data in the source code. "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\src\Telegram.au3" (1098) : ==> The requested action with this object has failed.: $oHTTP.Send() $oHTTP^ ERROR ->20:20:41 AutoIt3.exe ended.rc:1 +>20:20:41 AutoIt3Wrapper Finished. >Exit code: 1 Time: 1.56 It's really annoying problem in WinHTTP
    • By nacerbaaziz
      goodmorning autoit team
      today am comming with some winhttp problems, i hope that you can help me to solve them.
      the first problem
      is when opening a request
      my forums api allow me to delete any post using the api key
      all functions work, i mean post / get
      but when i tried to use the delete verb it's gave me an html 404 error
      here is what am tried
      #include "WinHttp.au3" ; Open needed handles Global $hOpen = _WinHttpOpen() Global $hConnect = _WinHttpConnect($hOpen, "xxxxxxxx.com") ; Specify the reguest: Global $hRequest = _WinHttpOpenRequest($hConnect, "Delete", "/vb/Api/posts/10447/?hard_delete=true", default, default) _WinHttpAddRequestHeaders($hRequest, "XF-Api-Key:xxxxx") _WinHttpAddRequestHeaders($hRequest, "XF-Api-User:xxxxx") ; Send request _WinHttpSendRequest($hRequest) ; Wait for the response _WinHttpReceiveResponse($hRequest) Global $sHeader = 0, $sReturned = 0 ; If there is data available... If _WinHttpQueryDataAvailable($hRequest) Then $sHeader = _WinHttpQueryHeaders($hRequest, $WINHTTP_QUERY_CONTENT_DISPOSITION) ;Or maybe: ; $sHeader = _WinHttpQueryHeaders($hRequest, BitOR($WINHTTP_QUERY_RAW_HEADERS_CRLF, $WINHTTP_QUERY_CUSTOM), "Content-Disposition") Do $sReturned &= _WinHttpReadData($hRequest) Until @error msgBox(64, "", $sReturned) endIf ; Close handles _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen)  
      and here is the error message
      <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>403 Forbidden</title> </head><body> <h1>Forbidden</h1> <p>You don't have permission to access /vb/Api/posts/10447/ on this server.<br /> </p> </body></html>  
      i hope you can help me 
      thanks in advance
    • By argumentum
      I can TCP/IP in AutoIt, hence, make a HTTP deamon. Now, how can I HTTPS to use SSL !??
      Well, Apache has this "mod_proxy.so" module that can let me have SSL and what not is in Apache.
      All that is needed is to tell Apache what I wanna do by editing httpd.conf .
      # Implements a proxy/gateway for Apache. # 1. Open /Applications/XAMPP/etc/httpd.conf # 2. Enable the following Modules by removing the # at the front of the line. # - LoadModule rewrite_module modules/mod_rewrite.so # - LoadModule proxy_module modules/mod_proxy.so # - LoadModule proxy_http_module modules/mod_proxy_http.so # # 3. Copy and Paste below to the bottom of httpd.conf # <IfModule mod_proxy.c> ProxyRequests On <Proxy *> Order deny,allow Allow from all </Proxy> ProxyVia Off ProxyPreserveHost Off ProxyPass /home/ http://127.0.0.1:84/home/ ProxyPassReverse /home/ http://127.0.0.1:84/home/ SetEnv proxy-nokeepalive 1 # ..since we are not using "keep-alive", we are using "close" </IfModule> ...et voila  
      I'm using XAMPP ( https://www.apachefriends.org/download.html )
      and this is my solution to avoid coding in PHP, as I feel more comfortable coding in AutoIt.
      A "muli-thread or concurrency" can be done by forking the socket ( https://www.autoitscript.com/forum/topic/199177-fork-udf-ish/ )
      but responses are under 20 ms., so I feel fine with a single thread.
      I modified an example ( attached below ), so can try out the concept.
      PS: I am not an Apache guru. I just discovered this and it opens a world of possibilities. In my case, I'm thinking of an API to query SQLite 
      PS2: I'm not gonna make Poll but do click like if you do  
       
      201673-json-http-post-serverlistener.au3
×
×
  • Create New...