Google Translator as Tooltip - Script not working any more

Get help with using AutoHotkey and its commands and hotkeys
tmplinshi
Posts: 1412
Joined: 01 Oct 2013, 14:57

Re: Google Translator as Tooltip - Script not working any more

07 Oct 2015, 13:21

How about http://www.bing.com/translator?

Code: Select all

mTranslate(str, tolang := "zh-CHS", switchLang := "en") {
	static appid

	; -------- Get appId
	If !appid {
		url := "http://www.bing.com/translator/"
		WinHttpRequest(url, ioData := "", ioHdr := hdr())
		If !RegExMatch(ioData, "i)(?<=src=['""])dynamic/.*?(?=['""])", url_js) {
			MsgBox, 48, Error, Get url_js failed.
			Return
		}

		url     := "http://www.bing.com/translator/" . url_js
		referer := "http://www.bing.com/translator/"
		While, !WinHttpRequest(url, ioData := "", ioHdr := hdr(referer))
			Sleep, 1000
		If !RegExMatch(ioData, "i)appId:""\K[^""]+", appid) {
			MsgBox, 48, Error, Failed to getting appid.
			Return
		}
	}

	; -------- Format input string
	texts := RegExReplace(str, "\R+", "`n")
	texts := Trim(texts, "`n")
	texts := JSON_FromObj( StrSplit(texts, "`n") )
	texts := UriEncode(texts)

	; -------- Translate...
	url := "
	(LTrim Join&
		http://api.microsofttranslator.com/v2/ajax.svc/TranslateArray2?appId=" appid "
		texts=" texts "
		from=%22%22
		to=%22" tolang "%22
		options=%7B%7D
		oncomplete=onComplete_1
		onerror=onError_1
		_=" unixNow() "
	)"
	
	referer := "http://www.bing.com/translator/?ref=SALL"
	While, !WinHttpRequest(url, ioData := "", ioHdr := hdr(referer))
		Sleep, 1000

	; -------- Parse result data
	If InStr(ioData, "onError_1(""ArgumentException: The token has expired") {
		appid := ""
		Return %A_ThisFunc%(str, tolang, switchLang)
	}

	RegExMatch(ioData, "\[.*\]", ioData)
	result := JSON_ToObj(ioData)
	If (result[1]["from"] = tolang) && switchLang
		Return %A_ThisFunc%(str, switchLang)

	For i, obj in result
		out .= obj.TranslatedText . "`n"

	Return Trim(out, "`n")
}
Bing Translator as Tooltip.zip
Last edited by tmplinshi on 22 Oct 2015, 01:17, edited 1 time in total.
translate

Re: Google Translator as Tooltip - Script not working any more

08 Oct 2015, 02:56

The Big G works again (for now) - Good to have the Bing alternative that also works.

Pricing doesn't seem to be that expensive "$20 per 1 million characters of text" https://cloud.google.com/translate/v2/pricing
woshichuanqilz72
Posts: 113
Joined: 05 Oct 2015, 21:23

Re: Google Translator as Tooltip - Script not working any mo

08 Oct 2015, 03:38

tmplinshi wrote:Try this:

Code: Select all

~^C::
	If isDoublePress() {
		ToolTip, Translating...
		ToolTip, % gTranslate(Clipboard, "ru")
		KeyWait, LButton, Down
		ToolTip
	}
Return

gTranslate(string, tl = "", sl = "") {
	static whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	url := "https://translate.google.com/translate_a/single?client=t&sl=" sl "&tl=" tl
	     . "&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&otf=2&srcrom=0&ssel=0&tsel=3&q=" string
	whr.Open("GET", url, true)
	whr.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko)")
	whr.Send()
	whr.WaitForResponse()
	Return RegExReplace(whr.ResponseText, "^.*?""(.*?)"".*$", "$1")
}

isDoublePress(ms = 300) {
	Return (A_ThisHotKey = A_PriorHotKey) && (A_TimeSincePriorHotkey <= ms)
}
hi, thanks for your script. I get some problem with it.
if i copy the url in the firefox, I can get the text about the translate result.
url := "https://translate.google.com/translate_ ... ient=t&sl=" sl "&tl=" tl
. "&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&otf=2&srcrom=0&ssel=0&tsel=3&q=" string

But when I run the script, the script will suspend on the line 'whr.WaitForResponse()', untill it report timeout. What the problem could be?
translate

Re: Google Translator as Tooltip - Script not working any more

08 Oct 2015, 03:51

Is AutoHotkey.exe allowed to access the Internet? Perhaps your firewall is blocking it, might be worth looking into.
User avatar
fump2000
Posts: 313
Joined: 04 Oct 2013, 17:31

Re: Google Translator as Tooltip - Script not working any more

08 Oct 2015, 03:55

Bing works properly only google makes problems
tmplinshi
Posts: 1412
Joined: 01 Oct 2013, 14:57

Re: Google Translator as Tooltip - Script not working any mo

08 Oct 2015, 05:04

woshichuanqilz wrote:
tmplinshi wrote: if i copy the url in the firefox, I can get the text about the translate result.
url := "https://translate.google.com/translate_ ... ient=t&sl=" sl "&tl=" tl
. "&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&otf=2&srcrom=0&ssel=0&tsel=3&q=" string

But when I run the script, the script will suspend on the line 'whr.WaitForResponse()', untill it report timeout. What the problem could be?
Is your network under Great Firewall? If so you'll need a VPN.
This script does not use the IE browser's proxy settings. If you want to use http proxy, add one line to the script:
...
whr.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko)")
whr.SetProxy(2, "133.130.113.162:3128") ; Modify 133.130.113.162:3128 to your proxy.
woshichuanqilz72
Posts: 113
Joined: 05 Oct 2015, 21:23

Re: Google Translator as Tooltip - Script not working any mo

08 Oct 2015, 08:55

tmplinshi wrote:
woshichuanqilz wrote:
tmplinshi wrote: if i copy the url in the firefox, I can get the text about the translate result.
url := "https://translate.google.com/translate_ ... ient=t&sl=" sl "&tl=" tl
. "&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&otf=2&srcrom=0&ssel=0&tsel=3&q=" string

But when I run the script, the script will suspend on the line 'whr.WaitForResponse()', untill it report timeout. What the problem could be?
Is your network under Great Firewall? If so you'll need a VPN.
This script does not use the IE browser's proxy settings. If you want to use http proxy, add one line to the script:
...
whr.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko)")
whr.SetProxy(2, "133.130.113.162:3128") ; Modify 133.130.113.162:3128 to your proxy.
tnx a lot for your help

When I append the line 'SetProxy', I get the page about this.
This page appears when Google automatically detects requests coming from your computer network which appear to be in violation of the <a href="//www.google.com/policies/terms/">Terms of Service</a>. The block will expire shortly after those requests stop.<br><br>This traffic may have been sent by malicious software, a browser plug-in, or a script that sends automated requests. If you share your network connection, ask your administrator for help &mdash; a different computer using the same IP address may be responsible. <a href="//support.google.com/websearch/answer/86640">Learn more</a><br><br>Sometimes you may see this page if you are using advanced terms that robots are known to use, or sending requests very quickly.

However the last problem have been solved for that I find my IE and firefox use the different proxy.
Tnx lot
MJs
Posts: 454
Joined: 23 Sep 2014, 03:29

Re: Google Translator as Tooltip - Script not working any more

08 Oct 2015, 15:12

have you tried supplying headers for the request? may be if you change the User-Agent or other headers, it may not think of it as an "unusual traffic"

I'm using HTTPRequest function, without setting the headers I get this problem, otherwise it works fine
woshichuanqilz72
Posts: 113
Joined: 05 Oct 2015, 21:23

Re: Google Translator as Tooltip - Script not working any more

21 Oct 2015, 23:07

tmplinshi wrote:How about http://www.bing.com/translator?

Code: Select all

mTranslate(str, tolang := "zh-CHS", switchLang := "en") {
	static appid

	; -------- Get appId
	If !appid {
		url     := "http://www.bing.com/translator/dynamic/223578/js/LandingPage.js?phenabled=&rttenabled=&v=223578"
		referer := "http://www.bing.com/translator/"
		While, !WinHttpRequest(url, ioData := "", ioHdr := hdr(referer))
			Sleep, 1000
		If !RegExMatch(ioData, "i)appId:""\K[^""]+", appid) {
			MsgBox, 48, , Failed to getting appid.
			Return
		}
	}

	; -------- Format input string
	texts := RegExReplace(str, "\R+", "`n")
	texts := Trim(texts, "`n")
	texts := JSON_FromObj( StrSplit(texts, "`n") )
	texts := UriEncode(texts)

	; -------- Translate...
	url := "
	(LTrim Join&
		http://api.microsofttranslator.com/v2/ajax.svc/TranslateArray2?appId=" appid "
		texts=" texts "
		from=%22%22
		to=%22" tolang "%22
		options=%7B%7D
		oncomplete=onComplete_1
		onerror=onError_1
		_=" unixNow() "
	)"
	
	referer := "http://www.bing.com/translator/?ref=SALL"
	While, !WinHttpRequest(url, ioData := "", ioHdr := hdr(referer))
		Sleep, 1000

	; -------- Parse result data
	If InStr(ioData, "onError_1(""ArgumentException: The token has expired") {
		appid := ""
		Return %A_ThisFunc%(str, tolang, switchLang)
	}

	RegExMatch(ioData, "\[.*\]", ioData)
	result := JSON_ToObj(ioData)
	If (result[1]["from"] = tolang) && switchLang
		Return %A_ThisFunc%(str, switchLang)

	For i, obj in result
		out .= obj.TranslatedText . "`n"

	Return Trim(out, "`n")
}

tnx a lot for your script, at first it works fine, but today I use this and a error came out said "failed to get appid", how can I fix it, it's need the knowledage for json?
tmplinshi
Posts: 1412
Joined: 01 Oct 2013, 14:57

Re: Google Translator as Tooltip - Script not working any more

22 Oct 2015, 01:22

@woshichuanqilz
Yes, same problem here. It's because of the website updated their js file to http://www.bing.com/translator/dynamic/225277/js/LandingPage.js?phenabled=&rttenabled=&v=225277.
I've modified the script, to extract the js file url from http://www.bing.com/translator.

Download here: Bing Translator as Tooltip.zip
User avatar
fump2000
Posts: 313
Joined: 04 Oct 2013, 17:31

Re: Google Translator as Tooltip - Script not working any more

09 Mar 2016, 03:00

Hi tmplinshi,

now comes errors with Bing and Google is not working also.

Can you fix it again please? :)

thx
fump
im2hard2resist

Re: Google Translator as Tooltip - Script not working any more

20 Jan 2017, 02:05

Works like a charm for Bing translator...You need to register first @ microsoft site to get the API
https://msdn.microsoft.com/en-us/library/hh847649.aspx
And then this code should work.

However I got a mail from Bing that there are changing the API from March 2017.

Code: Select all

#NoEnv
#Persistent
#SingleInstance force
SetWorkingDir %A_ScriptDir%

;--------------------------------------------------
; Translate text using translate.google.com
; after Google Translate API deprecation
;
; Ctrl+C, Ctrl+C
; Author: Anand Gadre 
;             
;--------------------------------------------------

~^C:: DoublePress()

DoublePress()
{
   static pressed1 = 0
   if pressed1 and A_TimeSincePriorHotkey <= 500
   {
      pressed1 = 0
     ; Translate from any language to Russian and from Russian to English if source was in Russian
     ; Tooltip, % Translate("sv","en")
      GUIit(Translate("da","en"),Clipboard)
   }
   else
      pressed1 = 1
   
}

; translate to "to" language,
; if source language is "to"
; translate to "anti" language

Translate(To,Anti)
{
   UseAnti = 0
   TranslateTo := To
   if Clipboard =
       return
	FileRead, OutputVar, C:\Anand\authkey.txt   
	AccessPos := InStr(OutputVar,"access_token") + 15
	ExpirePos := InStr(OutputVar,"expires_in") - 3
	AccessToken := Substr(OutputVar,AccessPos,ExpirePos-AccessPos)
		
	;Accesstoken := ;"http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=Translate-DKMS&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityp;rovider=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&Audience=http%3a%2f%2fapi.microsofttranslator.com&ExpiresOn=1451548006&Issuer=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&;HMACSHA256=g2Nbxe8URYN3kR11nBAwHl2VIj7xlYsvKbVHIIU%2fnDA%3d"    
	ExpireTimePos := InStr(Accesstoken,"ExpiresOn=") + 10
	ExpireTim := Substr(Accesstoken,ExpireTimePos,10)
	ExpireTime := Unix2Human(ExpireTim)
    If ExpireTime - A_now < 0 
	{
	 VBSScript := "C:\Anand\Mstrans.vbs"
	 ;RunWait, cscript.exe //nologo "%VBSScript%" ,,Hide
	 RunWait, c:\windows\system32\cscript.exe c:\Anand\Mstrans.vbs ,,Hide
     FileRead, OutputVar, C:\Anand\authkey.txt   
	 AccessPos := InStr(OutputVar,"access_token") + 15
	 ExpirePos := InStr(OutputVar,"expires_in") - 3
	 AccessToken := Substr(OutputVar,AccessPos,ExpirePos-AccessPos) 	 
     }	
	
	
   XCli := UriEncode(Clipboard)  	
   ;xyz = % "appId=""Bearer " . Accesstoken . """&text=""" . XCli . """&from=""da""&to=""en"""
   ;xyz = % "appId=""Bearer " . Accesstoken . """&text=""" . XCli . """&to=""en"""
   Appid := % "Bearer " . Accesstoken 
   App := UriEncode(Appid)
   xyza = % "appId=""Bearer " . Accesstoken 
   xyz  = % "appId=" . App . "&text=""" . XCli . """&from=da&to=en&contentType=text/html"
   ;MsgBox % App
   ;MsgBox % xyz
   ;MsgBox % "The value in the variable named Var is " . Clipboard . "."
   ;UriCli := UriEncode(xyz)
   ;MsgBox % UriCli

anti_translate:
   ;Url := "http://translate.google.com/translate_a/t?client=x&text=" original
   ;         . UriCli . "&tl=" . TranslateTo
   Url := "http://api.microsofttranslator.com/V2/Http.svc/Translate?" original . xyz
   ;MsgBox % Url
   ;Url := "https://www.bing.com/translator/t?client=x&text="
   ;         . UriCli . "&tl=" . TranslateTo
   ;Url := "http://translate.google.com/#da/en/&text="
   ;         . UriCli . "&tl=" . TranslateTo
   ;http://translate.google.com/translate_a/t?client=x&text="DER ER ALIAS FRA LSYSFP TIL LFPRO"
   ; Simulate Google Chrome
   ;JsonTrans := UrlDownloadToVar(Url,"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/18.6.872.0 Safari/535.2")
   JsonTrans := UrlDownloadToVar(Url,"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/535.2")
   ;MsgBox % JsonTrans
   ; thanks to Grey (http://forum.script-coding.com/profile.php?id=25792)
   StringReplace, JsonTrans, JsonTrans, \r\n,`r`n, All
   StringReplace, JsonTrans, JsonTrans, \", ", All
   JsonTrans := Substr(JsonTrans,InStr(JsonTrans,"microsoft.com"))
   JsonTrans := Substr(JsonTrans,InStr(JsonTrans,">")+2)
   JsonTrans := Substr(JsonTrans,1,InStr(JsonTrans,"</string>")-2)
   ;MsgBox % JsonTrans
   ;FromLang:=JSON(JsonTrans, "src")
   FromLang:= "da"
   ElapsedTime:=JSON(JsonTrans, "server_time")

   ;if (FromLang == To and TranslateTo <> Anti)
   ;{
   ;   TranslateTo := Anti
      ;MsgBox % FromLang . " " . To . " " TranslateTo . " " . Anti
   ;   goto anti_translate
   ;}

   ;Loop
   ;{
   ;  Sentence:=JSON(JsonTrans, "sentences["(A_Index-1)"].trans")
   ;  If Sentence
   ;    TransText.=Sentence
   ;  Else
   ;    Break
   ;}
   TransText := JsonTrans
   ;MsgBox % TransText
   ; Convert To UTF-8
   BaseFileEnc := A_FileEncoding
   FileEncoding
   FileDelete, %A_ScriptDir%\Convert.html
   FileAppend, %TransText%, %A_ScriptDir%\Convert.html
   FileEncoding, UTF-8
   FileRead TransText, %A_ScriptDir%\Convert.html
   FileDelete, %A_ScriptDir%\Convert.html
   FileEncoding, %BaseFileEnc%
   
   ; split long line to smaller lines about 40-50 symbols length
   t := RegExReplace(transText,".{200,210}(\s)","$0`n")
   
   Loop
   {
    posand := inStr(t,"&#xD")
    if posand > 0 
      t := substr(t,1,posand-1) . substr(t,posand+6)
	else 
      Break	
   } 
   ; ToolTip %FromLang%: %t%
   ; copy result to clipboard
   ; clipboard := t
   Return FromLang ": " t
   
}



~LButton::
ToolTip
return



UrlDownloadToVar(URL, UserAgent = "", Proxy = "", ProxyBypass = "") {
    ; Requires Windows Vista, Windows XP, Windows 2000 Professional, Windows NT Workstation 4.0,
    ; Windows Me, Windows 98, or Windows 95.
    ; Requires Internet Explorer 3.0 or later.
    pFix:=a_isunicode ? "W" : "A"
    hModule := DllCall("LoadLibrary", "Str", "wininet.dll")

    AccessType := Proxy != "" ? 3 : 0
    ;INTERNET_OPEN_TYPE_PRECONFIG                    0   // use registry configuration
    ;INTERNET_OPEN_TYPE_DIRECT                       1   // direct to net
    ;INTERNET_OPEN_TYPE_PROXY                        3   // via named proxy
    ;INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY  4   // prevent using java/script/INS

    io := DllCall("wininet\InternetOpen" . pFix
    , "Str", UserAgent ;lpszAgent
    , "UInt", AccessType
    , "Str", Proxy
    , "Str", ProxyBypass
    , "UInt", 0) ;dwFlags

    iou := DllCall("wininet\InternetOpenUrl" . pFix
    , "UInt", io
    , "Str", url
    , "Str", "" ;lpszHeaders
    , "UInt", 0 ;dwHeadersLength
    , "UInt", 0x80000000 ;dwFlags: INTERNET_FLAG_RELOAD = 0x80000000 // retrieve the original item
    , "UInt", 0) ;dwContext

    If (ErrorLevel != 0 or iou = 0) {
        DllCall("FreeLibrary", "UInt", hModule)
        return 0
    }

    VarSetCapacity(buffer, 10240, 0)
    VarSetCapacity(BytesRead, 4, 0)

    Loop
    {
        ;http://msdn.microsoft.com/library/en-us/wininet/wininet/internetreadfile.asp
        irf := DllCall("wininet\InternetReadFile", "UInt", iou, "UInt", &buffer, "UInt", 10240, "UInt", &BytesRead)
        VarSetCapacity(buffer, -1) ;to update the variable's internally-stored length

        BytesRead_ = 0 ; reset
        Loop, 4  ; Build the integer by adding up its bytes. (From ExtractInteger-function)
            BytesRead_ += *(&BytesRead + A_Index-1) << 8*(A_Index-1) ;Bytes read in this very DllCall

        ; To ensure all data is retrieved, an application must continue to call the
        ; InternetReadFile function until the function returns TRUE and the lpdwNumberOfBytesRead parameter equals zero.
        If (irf = 1 and BytesRead_ = 0)
            break
        Else ; append the buffer's contents
        {
            a_isunicode ? buffer:=StrGet(&buffer, "CP0")
            Result .= SubStr(buffer, 1, BytesRead_ * (a_isunicode ? 2 : 1))
        }

        /* optional: retrieve only a part of the file
        BytesReadTotal += BytesRead_
        If (BytesReadTotal >= 30000) ; only read the first x bytes
        break                      ; (will be a multiple of the buffer size, if the file is not smaller; trim if neccessary)
        */
    }

    DllCall("wininet\InternetCloseHandle",  "UInt", iou)
    DllCall("wininet\InternetCloseHandle",  "UInt", io)
    DllCall("FreeLibrary", "UInt", hModule)
   Return Result
}

JSON(ByRef js, s, v = "") {
   j = %js%
   Loop, Parse, s, .
   {
      p = 2
      RegExMatch(A_LoopField, "([+\-]?)([^[]+)((?:\[\d+\])*)", q)
      Loop {
         If (!p := RegExMatch(j, "(?<!\\)(""|')([^\1]+?)(?<!\\)(?-1)\s*:\s*((\{(?:[^{}]++|(?-1))*\})|(\[(?:[^[\]]++|(?-1))*\])|"
            . "(?<!\\)(""|')[^\7]*?(?<!\\)(?-1)|[+\-]?\d+(?:\.\d*)?|true|false|null?)\s*(?:,|$|\})", x, p))
            Return
         Else If (x2 == q2 or q2 == "*") {
            j = %x3%
            z += p + StrLen(x2) - 2
            If (q3 != "" and InStr(j, "[") == 1) {
               StringTrimRight, q3, q3, 1
               Loop, Parse, q3, ], [
               {
                  z += 1 + RegExMatch(SubStr(j, 2, -1), "^(?:\s*((\[(?:[^[\]]++|(?-1))*\])|(\{(?:[^{\}]++|(?-1))*\})|[^,]*?)\s*(?:,|$)){" . SubStr(A_LoopField, 1) + 1 . "}", x)
                  j = %x1%
               }
            }
            Break
         }
         Else p += StrLen(x)
      }
   }
   If v !=
   {
      vs = "
      If (RegExMatch(v, "^\s*(?:""|')*\s*([+\-]?\d+(?:\.\d*)?|true|false|null?)\s*(?:""|')*\s*$", vx)
         and (vx1 + 0 or vx1 == 0 or vx1 == "true" or vx1 == "false" or vx1 == "null" or vx1 == "nul"))
         vs := "", v := vx1
      StringReplace, v, v, ", \", All
      js := SubStr(js, 1, z := RegExMatch(js, ":\s*", zx, z) + StrLen(zx) - 1) . vs . v . vs . SubStr(js, z + StrLen(x3) + 1)
   }
   Return, j == "false" ? 0 : j == "true" ? 1 : j == "null" or j == "nul"
      ? "" : SubStr(j, 1, 1) == """" ? SubStr(j, 2, -1) : j
}

;-------------------------------------------------
; HTML encode/decode
;------------------------------------------------

StrPutVar(string, ByRef var, encoding)
{
    ; Ensure capacity.
    SizeInBytes := VarSetCapacity( var, StrPut(string, encoding)
        ; StrPut returns char count, but VarSetCapacity needs bytes.
        * ((encoding="utf-16"||encoding="cp1200") ? 2 : 1) )
    ; Copy or convert the string.
    StrPut(string, &var, encoding)
   Return SizeInBytes
}


unix2Human(unixTimestamp) {
	returnDate = 19700101080000
	returnDate += unixTimestamp, s
	return returnDate
}


UriEncode(str)
{
   b_Format := A_FormatInteger
   data := ""
   SetFormat,Integer,H
   SizeInBytes := StrPutVar(str,var,"utf-8")
   Loop, %SizeInBytes%
   {
   ch := NumGet(var,A_Index-1,"UChar")
   If (ch=0)
      Break
   if ((ch>0x7f) || (ch<0x30) || (ch=0x3d))
      s .= "%" . ((StrLen(c:=SubStr(ch,3))<2) ? "0" . c : c)
   Else
      s .= Chr(ch)
   }   
   SetFormat,Integer,%b_format%
   return s
}

GUIit(Text,Clipbord) {
	static Close
	Gui,99: Destroy
	Gui,99: +LastFound -border +AlwaysOnTop +ToolWindow -Caption
	Gui,99: Color,black
	Gui,99: Font, s20, Calibri
        Language :=  substr(Text,1,3)  
        Text := Substr(Text,5)
      	Gui,99: Font, s15, Calibri 
        Gui,99: Add, Edit, % "x100 y65  w900 H30  cRed   ReadOnly Uppercase -E0x200 -VScroll",%Language% 
        Gui,99: Add, Edit, % "x100 y100 w900 H300 cWhite ReadOnly -E0x200 -VScroll",%Clipbord%
        Language :=  "en:"  
        Gui,99: Add, Edit, % "x100 y465 w900 H30  cRed   ReadOnly Uppercase -E0x200 -VScroll",%Language% 
        Gui,99: Add, Edit, % "x100 y500 w900 H300 cWhite ReadOnly -E0x200 -VScroll",%Text%
        Gui,99: Font, s30, Calibri
	Gui,99: Add, Text, % "x1600 y40 vClose g99GuiEscape cC23B22", ⓧ
	GuiControl, 99: Focus, Close 
	WinSet, Transparent, 200
        Gui,99: Show, x0 y0 W%A_ScreenWidth% H%A_ScreenHeight%
	}

99GuiEscape:
	Gui,99: Destroy
	Return
im2hard2resist

Re: Google Translator as Tooltip - Script not working any more

20 Jan 2017, 02:35

I am getting the authkey using a vbs script -
You need to set your client id and client secret after your register from the microsoft site.

The AHK code will check if the code needs to be renewed (every 10 mins), if yes it shall execute this VBS to get the new access code.

Code: Select all

'Dim aRequest
'Set aRequest = CreateObject ("Microsoft.XMLHTTP")
'aRequest.Open "GET","http://www.microsoft.com/",False
'aRequest.Send
'Wscript.Echo aRequest.responseText

url = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13" 
set xmlhttp = CreateObject("Microsoft.XMLHTTP") 
xmlhttp.open "POST", url, false 
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded" 
xmlhttp.send "grant_type=client_credentials&client_id=xxxxx&client_secret=xxxxxxx&scope=http://api.microsofttranslator.com"
strHtml = xmlhttp.responseText 
set xmlhttp = nothing
Wscript.Echo strHtml
'Start saving 
Dim fso, fl
Set fso = CreateObject("Scripting.FileSystemObject")
Set fl = fso.OpenTextFile("C:\Anand\authkey.txt", 2, True)
fl.Write strHtml
fl.Close
Set fl = Nothing
Set fso = Nothing

Return to “Ask For Help”

Who is online

Users browsing this forum: Dumitas, TAC109, teadrinker and 237 guests