Microsoft Translator API

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
dubdub
Posts: 2
Joined: 09 Oct 2015, 08:07

Microsoft Translator API

Post by dubdub » 09 Oct 2015, 08:20

So I've been trying to translate text with AHK using the Microsoft Translator API

I already registered and subscribed to the free 2mil character translation subscription, I have my Client-ID and the Clientsecret (which is I assume like a Username and Password)

So far so good, but here is where it all starts falling apart.

To use the online API you need to request an Acces Token using your Client-ID and Clientsecret
https://msdn.microsoft.com/en-us/library/hh454950.aspx
I don't understand the documentation (specifically Step 3: Make an HTTP POST but... where? and where do I add the parameters?)

After receiving the token this is how to request translations https://msdn.microsoft.com/en-us/library/ff512387.aspx
Which also is not going into a lot of detail.


I am new to COM objects and I've got that very basic template:

Code: Select all

WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")
WebRequest.Open("GET", "api url")
WebRequest.Send()

MsgBox % WebRequest.ResponseText
WebRequest := ""

Any help would be appreciated, What I dont understand: How to get the Access Token and how to use the Translation API

tmplinshi
Posts: 1604
Joined: 01 Oct 2013, 14:57

Re: Microsoft Translator API

Post by tmplinshi » 09 Oct 2015, 22:54

Code: Select all

; Get access_token
client_id := "Your Registered Application client_id"
client_secret := "Your Registered Application client_secret"

url := "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"
postData := "client_id=" . client_id
          . "&client_secret=" . UriEncode(client_secret)
          . "&scope=http://api.microsofttranslator.com"
          . "&grant_type=client_credentials"

whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
whr.Open("POST", url, True)
whr.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
whr.Send(postData)
whr.WaitForResponse()

If !RegExMatch(whr.ResponseText, "i)""access_token"":""\K[^""]+", access_token)
    Throw, Get access_token failed

; Translate
text := "test string"
from := "en"
to   := "zh-CHS"

url := "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" . UriEncode(text) . "&from=" . from . "&to=" . to
authToken := "Bearer " . access_token

whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
whr.Open("GET", url, True)
whr.SetRequestHeader("Authorization", authToken)
whr.Send()
whr.WaitForResponse()

MsgBox, % whr.ResponseText
Return

; ==============================================================================================
; http://www.autohotkey.com/board/topic/75390-ahk-l-unicode-uri-encode-url-encode-function/?p=480216
UriEncode(Uri, Enc = "UTF-8")
{
   StrPutVar(Uri, Var, Enc)
   f := A_FormatInteger
   SetFormat, IntegerFast, H
   Loop
   {
      Code := NumGet(Var, A_Index - 1, "UChar")
      If (!Code)
         Break
      If (Code >= 0x30 && Code <= 0x39 ; 0-9
         || Code >= 0x41 && Code <= 0x5A ; A-Z
         || Code >= 0x61 && Code <= 0x7A) ; a-z
         Res .= Chr(Code)
      Else
         Res .= "%" . SubStr(Code + 0x100, -1)
   }
   SetFormat, IntegerFast, %f%
   Return, Res
}

UriDecode(Uri, Enc = "UTF-8")
{
   Pos := 1
   Loop
   {
      Pos := RegExMatch(Uri, "i)(?:%[\da-f]{2})+", Code, Pos++)
      If (Pos = 0)
         Break
      VarSetCapacity(Var, StrLen(Code) // 3, 0)
      StringTrimLeft, Code, Code, 1
      Loop, Parse, Code, `%
         NumPut("0x" . A_LoopField, Var, A_Index - 1, "UChar")
      StringReplace, Uri, Uri, `%%Code%, % StrGet(&Var, Enc), All
   }
   Return, Uri
}

StrPutVar(Str, ByRef Var, Enc = "")
{
   Len := StrPut(Str, Enc) * (Enc = "UTF-16" || Enc = "CP1200" ? 2 : 1)
   VarSetCapacity(Var, Len, 0)
   Return, StrPut(Str, &Var, Enc)
}
"Short" version:
TEST_Microsoft Translator API.7z
"Short" version, containing several libraries files.
(4.48 KiB) Downloaded 82 times

Code: Select all

MSTrans.Get_AccessToken(client_id, client_secret)
MsgBox, % MSTrans.Translate("Getting Started with Microsoft Translator")

Class MSTrans
{
	Get_AccessToken(client_id, client_secret) {
		url  := "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"
		data := "client_id=" . client_id
		      . "&client_secret=" . UriEncode(client_secret)
		      . "&scope=http://api.microsofttranslator.com"
		      . "&grant_type=client_credentials"
		WinHttpRequest(url, ioData := data)
		Return this.authToken := "Bearer " . JSON_ToObj(ioData).access_token
	}

	Translate(text, from := "en", to := "zh-CHS") {
		url := "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" . UriEncode(text) . "&from=" . from . "&to=" . to
		WinHttpRequest(url, ioData := "", ioHdr := "Authorization: " this.authToken)
		Return RegExReplace(ioData, "<.*?>")
	}
}
Without need client_id and client_secret:
http://ahkscript.org/boards/viewtopic.p ... 115#p54115

dubdub
Posts: 2
Joined: 09 Oct 2015, 08:07

Re: Microsoft Translator API

Post by dubdub » 10 Oct 2015, 08:43

tmplinshi wrote:

Code: Select all

; Get access_token
client_id := "Your Registered Application client_id"
client_secret := "Your Registered Application client_secret"

url := "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"
postData := "client_id=" . client_id
          . "&client_secret=" . UriEncode(client_secret)
          . "&scope=http://api.microsofttranslator.com"
          . "&grant_type=client_credentials"

whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
whr.Open("POST", url, True)
whr.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
whr.Send(postData)
whr.WaitForResponse()

If !RegExMatch(whr.ResponseText, "i)""access_token"":""\K[^""]+", access_token)
    Throw, Get access_token failed

; Translate
text := "test string"
from := "en"
to   := "zh-CHS"

url := "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" . UriEncode(text) . "&from=" . from . "&to=" . to
authToken := "Bearer " . access_token

whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
whr.Open("GET", url, True)
whr.SetRequestHeader("Authorization", authToken)
whr.Send()
whr.WaitForResponse()

MsgBox, % whr.ResponseText
Return

; ==============================================================================================
; http://www.autohotkey.com/board/topic/75390-ahk-l-unicode-uri-encode-url-encode-function/?p=480216
UriEncode(Uri, Enc = "UTF-8")
{
   StrPutVar(Uri, Var, Enc)
   f := A_FormatInteger
   SetFormat, IntegerFast, H
   Loop
   {
      Code := NumGet(Var, A_Index - 1, "UChar")
      If (!Code)
         Break
      If (Code >= 0x30 && Code <= 0x39 ; 0-9
         || Code >= 0x41 && Code <= 0x5A ; A-Z
         || Code >= 0x61 && Code <= 0x7A) ; a-z
         Res .= Chr(Code)
      Else
         Res .= "%" . SubStr(Code + 0x100, -1)
   }
   SetFormat, IntegerFast, %f%
   Return, Res
}

UriDecode(Uri, Enc = "UTF-8")
{
   Pos := 1
   Loop
   {
      Pos := RegExMatch(Uri, "i)(?:%[\da-f]{2})+", Code, Pos++)
      If (Pos = 0)
         Break
      VarSetCapacity(Var, StrLen(Code) // 3, 0)
      StringTrimLeft, Code, Code, 1
      Loop, Parse, Code, `%
         NumPut("0x" . A_LoopField, Var, A_Index - 1, "UChar")
      StringReplace, Uri, Uri, `%%Code%, % StrGet(&Var, Enc), All
   }
   Return, Uri
}

StrPutVar(Str, ByRef Var, Enc = "")
{
   Len := StrPut(Str, Enc) * (Enc = "UTF-16" || Enc = "CP1200" ? 2 : 1)
   VarSetCapacity(Var, Len, 0)
   Return, StrPut(Str, &Var, Enc)
}
"Short" version:
TEST_Microsoft Translator API.7z

Code: Select all

MSTrans.Get_AccessToken(client_id, client_secret)
MsgBox, % MSTrans.Translate("Getting Started with Microsoft Translator")

Class MSTrans
{
	Get_AccessToken(client_id, client_secret) {
		url  := "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"
		data := "client_id=" . client_id
		      . "&client_secret=" . UriEncode(client_secret)
		      . "&scope=http://api.microsofttranslator.com"
		      . "&grant_type=client_credentials"
		WinHttpRequest(url, ioData := data)
		Return this.authToken := "Bearer " . JSON_ToObj(ioData).access_token
	}

	Translate(text, from := "en", to := "zh-CHS") {
		url := "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" . UriEncode(text) . "&from=" . from . "&to=" . to
		WinHttpRequest(url, ioData := "", ioHdr := "Authorization: " this.authToken)
		Return RegExReplace(ioData, "<.*?>")
	}
}
Without need client_id and client_secret:
http://ahkscript.org/boards/viewtopic.p ... 115#p54115

Thank you so much!! I would kiss your feet if I could!

xuxinliang
Posts: 1
Joined: 03 Dec 2021, 23:17

Re: Microsoft Translator API

Post by xuxinliang » 27 Nov 2022, 07:48

Now the Microsoft translate had updated to 3.0
Content-type: application/json

Could you update your translate ahk code to adapt the 3.0
tmplinshi wrote:
09 Oct 2015, 22:54

Code: Select all

; Get access_token
client_id := "Your Registered Application client_id"
client_secret := "Your Registered Application client_secret"

url := "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"
postData := "client_id=" . client_id
          . "&client_secret=" . UriEncode(client_secret)
          . "&scope=http://api.microsofttranslator.com"
          . "&grant_type=client_credentials"

whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
whr.Open("POST", url, True)
whr.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
whr.Send(postData)
whr.WaitForResponse()

If !RegExMatch(whr.ResponseText, "i)""access_token"":""\K[^""]+", access_token)
    Throw, Get access_token failed

; Translate
text := "test string"
from := "en"
to   := "zh-CHS"

url := "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" . UriEncode(text) . "&from=" . from . "&to=" . to
authToken := "Bearer " . access_token

whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
whr.Open("GET", url, True)
whr.SetRequestHeader("Authorization", authToken)
whr.Send()
whr.WaitForResponse()

MsgBox, % whr.ResponseText
Return

; ==============================================================================================
; http://www.autohotkey.com/board/topic/75390-ahk-l-unicode-uri-encode-url-encode-function/?p=480216
UriEncode(Uri, Enc = "UTF-8")
{
   StrPutVar(Uri, Var, Enc)
   f := A_FormatInteger
   SetFormat, IntegerFast, H
   Loop
   {
      Code := NumGet(Var, A_Index - 1, "UChar")
      If (!Code)
         Break
      If (Code >= 0x30 && Code <= 0x39 ; 0-9
         || Code >= 0x41 && Code <= 0x5A ; A-Z
         || Code >= 0x61 && Code <= 0x7A) ; a-z
         Res .= Chr(Code)
      Else
         Res .= "%" . SubStr(Code + 0x100, -1)
   }
   SetFormat, IntegerFast, %f%
   Return, Res
}

UriDecode(Uri, Enc = "UTF-8")
{
   Pos := 1
   Loop
   {
      Pos := RegExMatch(Uri, "i)(?:%[\da-f]{2})+", Code, Pos++)
      If (Pos = 0)
         Break
      VarSetCapacity(Var, StrLen(Code) // 3, 0)
      StringTrimLeft, Code, Code, 1
      Loop, Parse, Code, `%
         NumPut("0x" . A_LoopField, Var, A_Index - 1, "UChar")
      StringReplace, Uri, Uri, `%%Code%, % StrGet(&Var, Enc), All
   }
   Return, Uri
}

StrPutVar(Str, ByRef Var, Enc = "")
{
   Len := StrPut(Str, Enc) * (Enc = "UTF-16" || Enc = "CP1200" ? 2 : 1)
   VarSetCapacity(Var, Len, 0)
   Return, StrPut(Str, &Var, Enc)
}
"Short" version:TEST_Microsoft Translator API.7z

Code: Select all

MSTrans.Get_AccessToken(client_id, client_secret)
MsgBox, % MSTrans.Translate("Getting Started with Microsoft Translator")

Class MSTrans
{
	Get_AccessToken(client_id, client_secret) {
		url  := "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"
		data := "client_id=" . client_id
		      . "&client_secret=" . UriEncode(client_secret)
		      . "&scope=http://api.microsofttranslator.com"
		      . "&grant_type=client_credentials"
		WinHttpRequest(url, ioData := data)
		Return this.authToken := "Bearer " . JSON_ToObj(ioData).access_token
	}

	Translate(text, from := "en", to := "zh-CHS") {
		url := "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" . UriEncode(text) . "&from=" . from . "&to=" . to
		WinHttpRequest(url, ioData := "", ioHdr := "Authorization: " this.authToken)
		Return RegExReplace(ioData, "<.*?>")
	}
}
Without need client_id and client_secret:
http://ahkscript.org/boards/viewtopic.php?p=54115#p54115

Post Reply

Return to “Ask for Help (v1)”