filter photo - error

filter photo - error

#region ====INIT ===============================================================
	Func _ConfigInitial()
;~ 		ConsoleWrite('++ConfigDBInitial() = ' & @CRLF)
		_SQLite_down()
;~ 		_DBvarInit()
		; -------check if SQLIte SubteBA db exist
		SQLite_init()
		$SQLq = "SELECT name FROM sqlite_temp_master WHERE type='table';"
		_SQLITErun($SQLq, $dbfullPath, $quietSQLQuery)
	;~ 	;-------- Init Log
	;~ 	_initLog()
		;------------------------------------------------------------------------------
	EndFunc   ;==>_ConfigDBInitial
#endregion
#region  ==== SQL functions =======================================================================
	Func SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
;~ 		ConsoleWrite('++InsertMessageSQL() = '& @crlf)
		$query='INSERT INTO messages VALUES (' & $TweetID & ',"' & $TweeMsg & '" ,' & $TweeDate & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting mesages ErrNo 1010" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLInsertUserMessage($TweetID,$TweeMsg,$UserID,$Fname,$Lname,$TweeDate)
;~ 		ConsoleWrite('++InsertMessageSQL() = '& @crlf)
		$query='INSERT INTO UserMessages VALUES (' & $TweetID & ',"' & _
		$TweeMsg & '" ,' & $UserID & ',"' & $Fname &"_"& $Lname & '",' & $TweeDate & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting mesages ErrNo 1010" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLGetUsers()
;~ 		ConsoleWrite('++SQLGetUsers() = '& @crlf)
		$query='SELECT * FROM Users ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetActiveUsers()
;~ 		ConsoleWrite('++SQLGetActiveUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetDevUsers()
;~ 		ConsoleWrite('++SQLGetDevUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 AND Dev=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLExist_Message($TweetID)
;~ 		ConsoleWrite('++Exist_Message() = '&$TweetID& @crlf)
		$query='SELECT id FROM messages WHERE id="'&$TweetID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
#endregion
#region  ==== send messages =======================================================================
	Func TelegramInitialMessage($UserID)
;~ 	ConsoleWrite('++TelegramInitialMessage() = '& @crlf)
		$message ="SubteBA BOT , lee los informes de Subte BA en Twitter, y los manda por este canal. "
		$message&='Este canal no es official del subte de Buenos Aires Ni de Metrovias.'  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Commandos:'  & $nuevaLinea
		$message&='/START -> Activa alertas. '  & $nuevaLinea
		$message&='/STOP  -> Desactiva alertas. '  & $nuevaLinea
		$message&='/INFO   -> Este mensaje'  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Futuros Comandos:'  & $nuevaLinea
		$message&='/ACTIVAR -> Alertas de lineas elegidas.'  & $nuevaLinea
		$message&='/DESACTIVAR -> Alertas de lineas elegidas.'  & $nuevaLinea
		$message&='/CERCANA -> Estacion mas cercana.'  & $nuevaLinea
		$message&='/ESTACIONES -> lista de estaciones por linea.'  & $nuevaLinea
		$message&='/HORARIOS -> Horarios de actividad'  & $nuevaLinea
		$message&='/MAPA -> Mapa de lineas de subte'  & $nuevaLinea
		$message&='/PROPUESTA -> Enviar propuestas'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
	EndFunc
	Func TelegramSTOPMessage($UserID)
		$message ="Los mensajes de alertas han sido deshabilitados" & $nuevaLinea
		$message&='/START -> Para habilitar la recepcion de alertas'  & $nuevaLinea
		$message&='/INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
	EndFunc
	Func TelegramSTARTMessage($UserID)
		$message ="Los mensajes de alertas han sido habilitados" & $nuevaLinea
		$message&='/STOP-> Para deshabilitar la recepcion de alertas'  & $nuevaLinea
		$message&='/INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
	EndFunc
	Func TelegramErrorMessage($UserID)
		$message ="No se ha registrado el cambio requerido." & $nuevaLinea
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
	EndFunc
	Func TelegramBaseMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		$message ="No logro entender el mensaje."
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='/INFO -> para mas informacion.'& $nuevaLinea & $nuevaLinea
;~ 		$message&="Su mensage:" & $nuevaLinea & $USRmsg
		$respuesta = SendTelegramexec($UserID,$message)
		SQLInsertUserMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		return $respuesta
	EndFunc
	Func TelegramInformNewUser($UserID,$Fname,$Lname)
		$message ="Nunevo usuario:" & $nuevaLinea
		$message&=$Fname & "  " & $Lname
		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
	EndFunc
	Func TelegramLocationMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		$message ="La Funcion de Informacion sobre las estaciones mas cercanas "
		$message&='No esta implementado en este momento.'  & $nuevaLinea
		$message&='/INFO -> para mas informacion.'& $nuevaLinea & $nuevaLinea
;~ 		$message&="Su mensage:" & $nuevaLinea & $USRmsg
		$respuesta = SendTelegramexec($UserID,$message)
		SQLInsertUserMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		return $respuesta
	EndFunc
	Func TelegramActivateMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		$message ="La Funcion de Activacion de alertas por linea, "
		$message&='No esta implementado en este momento.'  & $nuevaLinea
		$message&='/INFO -> para mas informacion.'& $nuevaLinea & $nuevaLinea
;~ 		$message&=$USRmsg& $nuevaLinea
;~ 		$message&="Su mensage:" & $nuevaLinea & $USRmsg
		$respuesta = SendTelegramexec($UserID,$message)
		SQLInsertUserMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		return $respuesta
	EndFunc
	Func ReformatMessage($message)
;~ 	ConsoleWrite('++ReformatMessage() = '& @crlf)
		$msgArr=StringSplit($message,"Actualizado",1)
		$diaHoraArr=stringsplit(StringStripWS($msgArr[2],1+2)," ")
		$hora=$diaHoraArr[2]
		$dia=$diaHoraArr[1]
		$msg=""&$hora&""&"     " & $dia & $nuevaLinea & StringStripWS($msgArr[1],1+2)
		return $msg
	EndFunc
	Func sendmessages($message)
		$message=ReformatMessage($message)
		SQLGetActiveUsers()
		If  IsArray($qryResult) Then
			for $i=1 to UBound($qryResult)-1
				$isDev = $qryResult[$i][4]
				$chatid = $qryResult[$i][0]
				$ChatUser = $qryResult[$i][1] & " " & $qryResult[$i][2]
				if $chatID<>"" then
					select
						Case $SendToAll = 1
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
						Case $isDev = 1 AND $SendToAll = 0
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
					endSelect
					;~ $respuesta  0 is ok
				endif
			next
			return true
		endif
		Return false
	EndFunc   ;==>_sendmessages
	Func SendTelegramexec($chatid,$msgtext="testeo harcoded",$DisableNotification=True)
		$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & _
		"&text=" & $msgtext & "&parse_mode=HTML"
		If $DisableNotification = True Then $urlMSG &= "&disable_notification=True"
		$sGet = HttpGet($urlMSG)

		if $sget<>"0"  then
			ConsoleWrite('Tlgm sent = ' & $msgtext & @crlf )
			return 0
		Else
			$s_text="Error sending message to Telegram = " & $sGet
			ConsoleWrite('!! ' & $s_text & @crlf )
			return 1
		endif
	EndFunc
#endregion
#region  ==== Tweeter scrapping ===================================================================
	Func TweeterMessages($Username)
		ConsoleWrite('++TweeterMessages() = '& $Username &@crlf)
		$htmltxt=_ScrapTweetMessages($Username)
		if $htmltxt<>"" then
			$TweetArr = _gettweetArr($htmltxt)
			if IsArray($TweetArr) then
				$newMessagesFlag=0
				_ArraySort($TweetArr, 0, 0, 0, 2)
				For $i = 0 To UBound($TweetArr) -1
					$TweetID = $TweetArr[$i][0]
					$TweeMsg = $TweetArr[$i][1]
					$TweeDate = $TweetArr[$i][2]
					if not SQLExist_Message($TweetID) then
						SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
						$TweetMinOld= (_GetUnixTime() - $TweeDate)/60
						if $TweetMinOld < 60 then
							sendmessages($TweeMsg)
							$newMessagesFlag=1
							ConsoleWrite('+ New messages ' & _NowTime(4) & "   ")
						Else
							ConsoleWrite('+ Old messages ' & Sec2Time($TweetMinOld*60) & @crlf)
						endif
					endif
					sleep(2000)
				Next
				if $newMessagesFlag=0 then ConsoleWrite('  No new messages ' & _NowTime(4) & @CRLF)
			endif
		endif
	EndFunc
	func _ScrapTweetMessages($Username)
		Local $sData = InetRead("https://twitter.com/"&$Username)
		Local $nBytesRead = @extended
		ConsoleWrite('@@ BytesRead = ' & $nBytesRead &"   ")
		$htmltxt = BinaryToString($sData)
		If $nBytesRead < 100000 or StringInStr($htmltxt,"subteba")<1 Then
			ConsoleWrite('  Connection issue contacting  ' & "https://twitter.com/"&$Username& @crlf)
			$htmltxt=""
			Return $htmltxt
		endif
		return $htmltxt
	EndFunc
	Func _gettweetArr($htmltxt)
		$MSGArr = StringRegExp($htmltxt, '(?s)(?i)
(.*?)
', 3)
		if IsArray($MSGArr) then
			dim  $TweetMSGArr[UBound($MSGArr)]
			For $i = 0 To UBound($MSGArr) -1
				$TweetMessage = StringRegExp($MSGArr[$i], '(?s)(?i)
(.*?)
', 1)
				$mensaje = clearstring($TweetMessage[1])
				$TweetMSGArr[$i]=$mensaje
			Next
			$TweetDate = StringRegExp($htmltxt, '(?s)(?i)data-time="(.*?)"', 3)
			$TweetIDArr = StringRegExp($htmltxt, '(?s)(?i)data-tweet-id="(.*?)"', 3)
			$TweetArrAux = _mergeArray($TweetIDArr, $TweetMSGArr)
			$TweetArr = _mergeArray($TweetArrAux, $TweetDate)
			return $TweetArr
		Else
			ConsoleWrite('!!!(' &  @ScriptLineNumber & ') : Error on  $MSGArr = ' & $MSGArr & @crlf )
			return 0
		endif
	EndFunc
#endregion
#region  ==== Bot Messages handeling ===================================================================
	Func Get_BotOffSet()
;~ 		ConsoleWrite('++Get_BotOffSet() = '& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 1.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,0)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 2.' & $OffsetFile )
			return 0
		endif
		Local $offset = FileReadLine($fileh)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("Get OffSet:"& $offset)
		FileClose($fileh)
		return $offset
	EndFunc
	Func Set_BotOffSet($offset)
		ConsoleWrite('++Set_BotOffSet() = '&$offset& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 3.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,2)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 4.' & $OffsetFile )
			return 0
		endif
		FileWriteLine($fileh,$offset)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("    Set OffSet:"& $offset &@crlf)
		FileClose($fileh)
		return 1
	EndFunc
	func UpdateUsers()
		ConsoleWrite('  '&@HOUR & ':' & @MIN&  ':' & @sec & '  Update users.  ' )
		local $s=GetBotUpdates()
		if $s then
			initMsgClass()
			$s=ParseForUserUpdate($s)
;~ 			ConsoleWrite('  $s = ' & $s & @crlf )
			if $s then
				$oJSON = _OO_JSON_Init()
				$jsonObj = $oJSON.parse($s)
				if $jsonObj.ok  then
					if $jsonObj.jsonPath( "$.result").stringify() = "[[]]" then
						ConsoleWrite(' No Bot data ' & @crlf)
					Else
						ConsoleWrite('  Updating... ' & @crlf)
						$UpdateIDArr = StripIntJS($jsonObj.jsonPath( "$.result..update_id").stringify()  )
						$MSGIDArr =   StripIntJS($jsonObj.jsonPath( "$.result..message.message_id").stringify())
						$UserIDArr =   StripIntJS($jsonObj.jsonPath( "$.result..message.from.id").stringify())
						$FnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.first_name").stringify())
						$LnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.last_name").stringify())
						$ChatIDArr =   StripIntJS($jsonObj.jsonPath( "$.result..message.chat.id").stringify())
						$ChatFnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.first_name").stringify())
						$ChatLnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.last_name").stringify())
						$epochArr =    StripIntJS($jsonObj.jsonPath( "$.result..message.date").stringify())
						$menssageArr = StripStrJS($jsonObj.jsonPath( "$.result..message.text").stringify())
						$IsBot =       StripIntJS($jsonObj.jsonPath( "$.result..message.from.is_bot").stringify())

						if $UserIDArr[0] = $UpdateIDArr[0] AND  $UserIDArr[0] = $FnameArr[0] AND _
							$UserIDArr[0] = $LnameArr[0]    AND  $UserIDArr[0] = $epochArr[0] AND _
							$UserIDArr[0] = $menssageArr[0] AND  $UserIDArr[0] = $IsBot[0]  then
							$retBad=0
							for $i=1 to $UserIDArr[0]
								if $IsBot[$i] <> "true" then
									$ret=SQLregister($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i],$menssageArr[$i])
									$ret1=ParseBotMessage($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i],$menssageArr[$i],$UpdateIDArr[$i],$MSGIDArr[$i])
									ConsoleWrite('>> $ret1 = ' & $ret1 & @crlf )
									if (Not $ret) or (Not $ret1)  then	$retBad+=1
									$UpdateID=$UpdateIDArr[$i]
								Else
									ConsoleWrite('+(' & @ScriptLineNumber & ') : $menssageArr[$i] = ' & $menssageArr[$i] & @crlf )
									ConsoleWrite('+(' & @ScriptLineNumber & ') : $IsBot[$i] = ' & $IsBot[$i] & @crlf )
									if AImessage($menssageArr[$i],"callback_query") then
										if AImessage($menssageArr[$i],"CLOSE_O") then
											TelegramActivateMessage($UpdateIDArr[$i],$menssageArr[$i],$ChatIDArr[$i],$ChatFnameArr[$i],$ChatLnameArr[$i],$epochArr[$i])
											_DeleteMsg($ChatIDArr[$i], $MSGIDArr[$i])
										else
											SQLUpdateUserAlerts($ChatIDArr[$i],$menssageArr[$i])
										endif
										$UpdateID=$UpdateIDArr[$i]
										$ahora=0
									Else
										$retBad=1
									endif
								endif
							next
							if $retBad=0 then Set_BotOffSet($UpdateID+1)
						Else
							_printFromArray($ChatIDArr,"$ChatIDArr")
							_printFromArray($ChatFnameArr,"$ChatFnameArr")
							_printFromArray($ChatLnameArr,"$ChatLnameArr")
							_printFromArray($MSGIDArr,"$MSGIDArr")
							_printFromArray($UserIDArr,"UserIDArr")
							_printFromArray($FnameArr,"FnameArr")
							_printFromArray($LnameArr,"LnameArr")
							_printFromArray($epochArr,"epochArr")
							_printFromArray($menssageArr,"menssageArr")
							_printFromArray($UpdateIDArr,"UpdateIDArr")
							_printFromArray($IsBot,"IsBot")
							ConsoleWrite('  Error in JS array . exiting..... ' & @crlf)
							exit 29
						endif
					endif
				endif
			endif
		endif
		ClearKeyBoards()
	EndFunc
	Func GetBotUpdates()
		$offset=Get_BotOffSet()
		$urlMSG="https://api.telegram.org/" & $token & "/getUpdates?offset="&$offset
		$sGet = HttpGetJson1($urlMSG)
;~ 		ConsoleWrite('@@ $sGet = ' & $sGet & @crlf )
		if $sGet<>"" then
			return $sGet
		Else
			$s_text="  Error getUpdates from Telegram = "
			ConsoleWrite('!! ' & $s_text & @crlf & "! " & $sGet)
			return false
		endif
	EndFunc
	Func StripStrJS($st)
		$st=StringReplace($st,'","',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func StripIntJS($st)
		$st=StringReplace($st,',',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func ParseForUserUpdate($s)
;~ 		eliminate "edited_message":{"
		$s=StringReplace($s,'"edited_message":{','"message":{')

;     check lastname
		$LNarr=StringRegExp($s,'"first_name":"(.*?)","language_code":"',1)
		if IsArray($LNarr) then
			for $r=0 to UBound($LNarr)-1
				$donde='"first_name":"[a-zA-Z]*","language_code":"'
				$pat='"first_name":"' & $LNarr[$r] & '","last_name":"xxx","language_code":"'
				$s=StringRegExpReplace($s,$donde,$pat)

				$donde='"first_name":"[a-zA-Z]*","type":"'
				$pat='"first_name":"' & $LNarr[$r] & '","last_name":"xxx","type":"'
				$s=StringRegExpReplace($s,$donde,$pat)
			next
		endif

;~ 		eliminate "callback_query":{"
		if StringInStr($s,'"callback_query":')> 0 then
			$s=StringRegExpReplace($s,'(?s)(?i)"callback_query":(.*?)"from":(.*?)},',"")
			$s=StringRegExpReplace($s,'},"chat_instance":"(.*?)"',"")
			$s=StringRegExpReplace($s,',"text":"(.*?)",',",")
			$s=StringRegExpReplace($s,',"data":"',',"text":"callback_query ')
		endif
;~ 		eliminate location info
;~ "location":{"latitude":-34.631010,"longitude":-58.469731}}
		if StringInStr($s,'"location":{')> 0 then
			$MsgClass[0]="Location"
				$posini=StringInStr($s,'{"latitude":')+12
				$posend=StringInStr($s,'"longitude":')-$posini-1
			$MsgClass[1]=StringMid($s,$posini,$posend)
				$posini=StringInStr($s,'"longitude":')+12
			$MsgClass[2]=StringMid($s,$posini,$posend)
			$s=StringRegExpReplace($s,'(?s)(?i)"location":{"latitude":(.*?),"longitude":(.*?)}' , '"text": "' & $MsgClass[0] & ":" & $MsgClass[1] & ":" & $MsgClass[2] & '"' )
		endif

;~ 		eliminate contact info
		$s=StringRegExpReplace($s,'(?s)(?i)"contact":(.*?)}'  ,  '"text": ""' )

;~ 		eliminate photo info
		$s=StringRegExpReplace($s,'(?s)(?i)"photo":\[(.*?)\]'  ,  '"text": ""' )

;~ 		replace username last-name
		$s=StringReplace($s,'"username":','"last_name":')

;~ 		eliminate sticker info
		$s=StringRegExpReplace($s,'(?s)(?i)"sticker":(.*?)}(.*?)}'  ,  '"text": ""' )
		return $s
	EndFunc
	Func SQLregister($UserID,$Fname,$Lname,$epoch,$mensage)
;~ 	ConsoleWrite('++SQLregister() = '& @crlf)
		$existUser=0
		If SQLExistUser($UserID)=$userID then $existUser=1
		if $existUser=0 then
			$setactive=1
			$ret=SQLInsertUser($UserID,$Fname,$Lname,$epoch,$setactive)
			if $ret then
				TelegramInformNewUser($DEVChatID,$Fname,$Lname)
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			else
				$ret=TelegramErrorMessage($UserID)
				if $ret=0 then return true
			endif
			return false
		endif

		$setactive=-1
		if AIMessage($mensage,"/START") then $setactive=1
		if AIMessage($mensage,"/STOP") then $setactive=0
		if $existUser=1 AND $setactive<>-1 then
			$ret=SQLUpdateUserActive($UserID,$Fname,$Lname,$setactive)
			if $ret and $setactive=0 then
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			endif
			if $ret and $setactive=1 then
				$ret=TelegramSTARTMessage($UserID)
				if $ret=0 then return true
			endif
			if NOT $ret then TelegramErrorMessage($UserID)
			return false
		endif

		return true
	EndFunc
	Func SQLInsertUser($UserID,$Fname,$Lname,$epoch,$active=1)
		ConsoleWrite('  Nuevo usuario = '& $Fname & "  "  & $Lname  & @crlf)
		$query='INSERT INTO Users VALUES (' & $UserID & ',"' & $Fname & '","' & $Lname & '",' & $active &',0,' & $epoch & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting User ErrNo 1011" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLUpdateUserActive($UserID,$Fname,$Lname,$active=1)
		ConsoleWrite('    Usuario Activo 1/Start 0/Stop= '&$active& "  " & $Fname & "  "  & $Lname  & @crlf)
		$query='UPDATE  Users SET Active=' & $active &' WHERE UserID='& $UserID & ' ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			ConsoleWrite("       Error updating active user User ErrNo 1012" & @CRLF & $query& @crlf)
			Return false
		EndIf
	EndFunc
	Func SQLExistUser($UserID)
;~ 	ConsoleWrite('++SQLExistUser() = '& @crlf)
		$query='SELECT UserID FROM Users WHERE UserID="'&$UserID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
	Func SQLUpdateUserAlerts($UserID,$mensage,$active=1)
		$msgArr=StringSplit($mensage,"_")
		if $msgArr[2]="ON" then

		endif
;~ 		$query='UPDATE  Users SET Active=' & $active &' WHERE UserID='& $UserID & ' ;'
;~ 		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
;~ 			return true
;~ 		Else
;~ 			ConsoleWrite("       Error updating active user User ErrNo 1012" & @CRLF & $query& @crlf)
;~ 			Return false
;~ 		EndIf
	EndFunc
#endregion
#region   ===================================   keyboard   ==========================
	Func SQLregisterKeyboard($UserID,$MsgID,$epoch)
		$query='INSERT INTO Keyboard VALUES (' & $UserID & ',' & $MsgID  & ',' & $epoch & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then return true
		Return false
	EndFunc
	Func SQLUnRegisterKeyboard($UserID,$MsgID)
		$query='DELETE FROM Keyboard WHERE UserID=' & $UserID & ' AND MsgID=' & $MsgID & ' ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then return true
		Return false
	EndFunc
	Func ClearKeyBoards()
		$query='SELECT UserID,MsgID FROM Keyboard WHERE Timestamp < ' & _GetUnixTime()-60 & ';'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
;~ 			_printFromArray($qryResult)
			if UBound($qryResult)>1 then
				for $i=1 to UBound($qryResult)-1
					_DeleteMsg( $qryResult[$i][0],$qryResult[$i][1])
					SQLUnRegisterKeyboard($qryResult[$i][0],$qryResult[$i][1])
				next
			EndIf
		endif
	EndFunc
	func KeyboardActivate($UserID)
		$keybrd =  '{"inline_keyboard":['
		$keybrd &= '['
		$keybrd &= '{"text":"Linea A","callback_data":"A_ON"},'
		$keybrd &= '{"text":"Linea B","callback_data":"B_ON"},'
		$keybrd &= '{"text":"Linea C","callback_data":"C_ON"}'
		$keybrd &= '],['
		$keybrd &= '{"text":"Linea D","callback_data":"D_ON"},'
		$keybrd &= '{"text":"Linea E","callback_data":"E_ON"},'
		$keybrd &= '{"text":"Linea H","callback_data":"H_ON"}'
		$keybrd &= '],['
		$keybrd &= '{"text":"Linea P","callback_data":"P_ON"},'
		$keybrd &= '{"text":"Linea U","callback_data":"U_ON"},'
		$keybrd &= '{"text":"Listo","callback_data":"CLOSE_ON"}'
		$keybrd &= '],['
		$keybrd &= ']'
		$keybrd &= ']}'
		$res=_SendMsg($UserID,"Sus alertas activas son:"& "" & $nuevaLinea & "Cual desea activar?","HTML",$keybrd)
		$MSGID=StringRegExp($res,'"message_id":(.*?),"from":',1)
		$UsrID=StringRegExp($res,',"chat":{"id":(.*?),"first_name":',1)
		$utime=StringRegExp($res,',"date":(.*?),"text":',1)
		if IsArray($MSGID) then
			SQLregisterKeyboard($UsrID[0],$MsgID[0],$utime[0])
		endif
		if $res then return True
		return false
	EndFunc
	func KeyboardDesActivate($UserID)
		$keybrd =  '{"inline_keyboard":['
		$keybrd &= '['
		$keybrd &= '{"text":"Linea A","callback_data":"A_OFF"},'
		$keybrd &= '{"text":"Linea B","callback_data":"B_OFF"},'
		$keybrd &= '{"text":"Linea C","callback_data":"C_OFF"}'
		$keybrd &= '],['
		$keybrd &= '{"text":"Linea D","callback_data":"D_OFF"},'
		$keybrd &= '{"text":"Linea E","callback_data":"E_OFF"},'
		$keybrd &= '{"text":"Linea H","callback_data":"H_OFF"}'
		$keybrd &= '],['
		$keybrd &= '{"text":"Linea P","callback_data":"P_OFF"},'
		$keybrd &= '{"text":"Linea U","callback_data":"U_OFF"},'
		$keybrd &= '{"text":"Listo","callback_data":"CLOSE_OFF"}'
		$keybrd &= '],['
		$keybrd &= ']'
		$keybrd &= ']}'
		$res=_SendMsg($UserID,"Sus alertas activas son:"& "" & $nuevaLinea & "Cual desea desactivar?","HTML",$keybrd)
		$MSGID=StringRegExp($res,'"message_id":(.*?),"from":',1)
		$UsrID=StringRegExp($res,',"chat":{"id":(.*?),"first_name":',1)
		if IsArray($MSGID) then
			SQLunregisterKeyboard($UsrID[0],$MsgID[0])
		endif
		if $res then return True
		return false
	EndFunc
#endregion
#region   ===========================================================================
	func closeall()
		_SQLite_Close()
		_SQLite_Shutdown()
		exit 30
	EndFunc
#endregion
#region =====================================   Helpers functions  ===============================
	Func _mergeArray($array1, $array2)
		$array1 = _ArrayAdd_Column($array1)
		$size = UBound($array1)
		$newCol = UBound($array1, 2) - 1
		For $i = 0 To $size - 1
			$array1[$i][$newCol] = $array2[$i]
		Next
		Return $array1
	EndFunc   ;==>_mergeArray
	Func _ArrayAdd_Column($Array)
		Local $aTemp[UBound($Array)][UBound($Array, 0) + 1]
		For $i = 0 To UBound($Array) - 1

			For $j = 0 To UBound($Array, 0) - 1
				If UBound($Array, 0) = 1 Then $aTemp[$i][0] = $Array[$i]
				If UBound($Array, 0) > 1 Then $aTemp[$i][$j] = $Array[$i][$j]
			Next
		Next
		Return $aTemp
	EndFunc   ;==>_ArrayAdd_Column
	Func _ClearSciteConsole()
		ConsoleWrite('!!!!!!!!!!!_ClearSciteConsole Func General 92!!!!!!!!!!!!  ' & @CRLF)
		ControlSend("[CLASS:SciTEWindow]", "", "Scintilla2", "+{F5}")
	EndFunc   ;==>_ClearSciteConsole
	Func _GetDOSOutput($sCommand)
	 ConsoleWrite('++_GetDOSOutput $sCommand = ' & $sCommand & @crlf )
		Local $iPID, $sOutput = ""
		$iPID = Run('"' & @ComSpec & '" /c ' & $sCommand, "", @SW_HIDE, 2 + 4)
		While 1
			$sOutput &= StdoutRead($iPID, False, False)
			$err=@error
			If $err Then
				ConsoleWrite('!!  _GetDOSOutput $err = ' & $err & @crlf )
				ExitLoop
			EndIf
	;~ 	Sleep(10)
		WEnd
		ConsoleWrite('>> 	Output = ' & $sOutput & @crlf )
		Return $sOutput
	EndFunc   ;==>_GetDOSOutput
	Func _timeBetween($cTime, $sTime, $eTime)
		 If Not _DateIsValid('2000/01/01 ' & $cTime) Then Return -1
		 If Not _DateIsValid('2000/01/01 ' & $sTime) Then Return -2
		 If Not _DateIsValid('2000/01/01 ' & $eTime) Then Return -3
		 If _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') < 0 And _
			 _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') > 0 Then
			  Return 1
		 Else
			  Return 0
		 EndIf
	EndFunc  ; ==>_timeBetween
#endregion
#region time
	Func  Sec2Time($nr_sec)
		$sec2time_hour = Int($nr_sec / 3600)
		$sec2time_min = Int(($nr_sec - $sec2time_hour * 3600) / 60)
		$sec2time_sec = $nr_sec - $sec2time_hour * 3600 - $sec2time_min * 60
		Return StringFormat('%02d:%02d:%02d', $sec2time_hour, $sec2time_min, $sec2time_sec)
	EndFunc   ;==>Sec2Time
	Func _GetUnixTime($sDate = 0);Date Format: 2013/01/01 00:00:00 ~ Year/Mo/Da Hr:Mi:Se
		Local $aSysTimeInfo = _Date_Time_GetTimeZoneInformation()
		Local $utcTime = ""
		If Not $sDate Then $sDate = _NowCalc()
		If Int(StringLeft($sDate, 4)) < 1970 Then Return ""
		If $aSysTimeInfo[0] = 2 Then
			$utcTime = _DateAdd('n', $aSysTimeInfo[1] + $aSysTimeInfo[7], $sDate)
		Else
			$utcTime = _DateAdd('n', $aSysTimeInfo[1], $sDate)
		EndIf
		Return _DateDiff('s', "1970/01/01 00:00:00", $utcTime)
	EndFunc   ;==>_GetUnixTime
#endregion

#region ====INIT ===============================================================
	Func _ConfigInitial()
;~ 		ConsoleWrite('++ConfigDBInitial() = ' & @CRLF)
		_SQLite_down()
;~ 		_DBvarInit()
		; -------check if SQLIte SubteBA db exist
		SQLite_init()
		$SQLq = "SELECT name FROM sqlite_temp_master WHERE type='table';"
		_SQLITErun($SQLq, $dbfullPath, $quietSQLQuery)
	;~ 	;-------- Init Log
	;~ 	_initLog()
		;------------------------------------------------------------------------------
	EndFunc   ;==>_ConfigDBInitial
#endregion
#region  ==== SQL functions =======================================================================
	Func SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
;~ 		ConsoleWrite('++InsertMessageSQL() = '& @crlf)
		$query='INSERT INTO messages VALUES (' & $TweetID & ',"' & $TweeMsg & '" ,' & $TweeDate & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting mesages ErrNo 1010" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLInsertUserMessage($TweetID,$TweeMsg,$UserID,$Fname,$Lname,$TweeDate)
;~ 		ConsoleWrite('++InsertMessageSQL() = '& @crlf)
		$query='INSERT INTO UserMessages VALUES (' & $TweetID & ',"' & _
		$TweeMsg & '" ,' & $UserID & ',"' & $Fname &"_"& $Lname & '",' & $TweeDate & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting mesages ErrNo 1010" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLGetUsers()
;~ 		ConsoleWrite('++SQLGetUsers() = '& @crlf)
		$query='SELECT * FROM Users ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetActiveUsers()
;~ 		ConsoleWrite('++SQLGetActiveUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetDevUsers()
;~ 		ConsoleWrite('++SQLGetDevUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 AND Dev=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLExist_Message($TweetID)
;~ 		ConsoleWrite('++Exist_Message() = '&$TweetID& @crlf)
		$query='SELECT id FROM messages WHERE id="'&$TweetID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
#endregion
#region  ==== send messages =======================================================================
	Func TelegramInitialMessage($UserID)
;~ 	ConsoleWrite('++TelegramInitialMessage() = '& @crlf)
		$message ="SubteBA BOT , lee los informes de Subte BA en Twitter, y los manda por este canal. "
		$message&='Este canal no es official del subte de Buenos Aires Ni de Metrovias.'  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Commandos:'  & $nuevaLinea
		$message&='/START -> Activa alertas. '  & $nuevaLinea
		$message&='/STOP  -> Desactiva alertas. '  & $nuevaLinea
		$message&='/INFO   -> Este mensaje'  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Futuros Comandos:'  & $nuevaLinea
		$message&='/ACTIVAR -> Alertas de lineas elegidas.'  & $nuevaLinea
		$message&='/DESACTIVAR -> Alertas de lineas elegidas.'  & $nuevaLinea
		$message&='/CERCANA -> Estacion mas cercana.'  & $nuevaLinea
		$message&='/ESTACIONES -> lista de estaciones por linea.'  & $nuevaLinea
		$message&='/HORARIOS -> Horarios de actividad'  & $nuevaLinea
		$message&='/MAPA -> Mapa de lineas de subte'  & $nuevaLinea
		$message&='/PROPUESTA -> Enviar propuestas'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
	EndFunc
	Func TelegramSTOPMessage($UserID)
		$message ="Los mensajes de alertas han sido deshabilitados" & $nuevaLinea
		$message&='/START -> Para habilitar la recepcion de alertas'  & $nuevaLinea
		$message&='/INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
	EndFunc
	Func TelegramSTARTMessage($UserID)
		$message ="Los mensajes de alertas han sido habilitados" & $nuevaLinea
		$message&='/STOP-> Para deshabilitar la recepcion de alertas'  & $nuevaLinea
		$message&='/INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
	EndFunc
	Func TelegramErrorMessage($UserID)
		$message ="No se ha registrado el cambio requerido." & $nuevaLinea
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
	EndFunc
	Func TelegramBaseMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		$message ="No logro entender el mensaje."
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='/INFO -> para mas informacion.'& $nuevaLinea & $nuevaLinea
;~ 		$message&="Su mensage:" & $nuevaLinea & $USRmsg
		$respuesta = SendTelegramexec($UserID,$message)
		SQLInsertUserMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		return $respuesta
	EndFunc
	Func TelegramInformNewUser($UserID,$Fname,$Lname)
		$message ="Nunevo usuario:" & $nuevaLinea
		$message&=$Fname & "  " & $Lname
		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
	EndFunc
	Func TelegramLocationMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		$message ="La Funcion de Informacion sobre las estaciones mas cercanas "
		$message&='No esta implementado en este momento.'  & $nuevaLinea
		$message&='/INFO -> para mas informacion.'& $nuevaLinea & $nuevaLinea
;~ 		$message&="Su mensage:" & $nuevaLinea & $USRmsg
		$respuesta = SendTelegramexec($UserID,$message)
		SQLInsertUserMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		return $respuesta
	EndFunc
	Func TelegramActivateMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		$message ="La Funcion de Activacion de alertas por linea, "
		$message&='No esta implementado en este momento.'  & $nuevaLinea
		$message&='/INFO -> para mas informacion.'& $nuevaLinea & $nuevaLinea
;~ 		$message&=$USRmsg& $nuevaLinea
;~ 		$message&="Su mensage:" & $nuevaLinea & $USRmsg
		$respuesta = SendTelegramexec($UserID,$message)
		SQLInsertUserMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		return $respuesta
	EndFunc
	Func ReformatMessage($message)
;~ 	ConsoleWrite('++ReformatMessage() = '& @crlf)
		$msgArr=StringSplit($message,"Actualizado",1)
		$diaHoraArr=stringsplit(StringStripWS($msgArr[2],1+2)," ")
		$hora=$diaHoraArr[2]
		$dia=$diaHoraArr[1]
		$msg=""&$hora&""&"     " & $dia & $nuevaLinea & StringStripWS($msgArr[1],1+2)
		return $msg
	EndFunc
	Func sendmessages($message)
		$message=ReformatMessage($message)
		SQLGetActiveUsers()
		If  IsArray($qryResult) Then
			for $i=1 to UBound($qryResult)-1
				$isDev = $qryResult[$i][4]
				$chatid = $qryResult[$i][0]
				$ChatUser = $qryResult[$i][1] & " " & $qryResult[$i][2]
				if $chatID<>"" then
					select
						Case $SendToAll = 1
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
						Case $isDev = 1 AND $SendToAll = 0
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
					endSelect
					;~ $respuesta  0 is ok
				endif
			next
			return true
		endif
		Return false
	EndFunc   ;==>_sendmessages
	Func SendTelegramexec($chatid,$msgtext="testeo harcoded",$DisableNotification=True)
		$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & _
		"&text=" & $msgtext & "&parse_mode=HTML"
		If $DisableNotification = True Then $urlMSG &= "&disable_notification=True"
		$sGet = HttpGet($urlMSG)

		if $sget<>"0"  then
			ConsoleWrite('Tlgm sent = ' & $msgtext & @crlf )
			return 0
		Else
			$s_text="Error sending message to Telegram = " & $sGet
			ConsoleWrite('!! ' & $s_text & @crlf )
			return 1
		endif
	EndFunc
#endregion
#region  ==== Tweeter scrapping ===================================================================
	Func TweeterMessages($Username)
		ConsoleWrite('++TweeterMessages() = '& $Username &@crlf)
		$htmltxt=_ScrapTweetMessages($Username)
		if $htmltxt<>"" then
			$TweetArr = _gettweetArr($htmltxt)
			if IsArray($TweetArr) then
				$newMessagesFlag=0
				_ArraySort($TweetArr, 0, 0, 0, 2)
				For $i = 0 To UBound($TweetArr) -1
					$TweetID = $TweetArr[$i][0]
					$TweeMsg = $TweetArr[$i][1]
					$TweeDate = $TweetArr[$i][2]
					if not SQLExist_Message($TweetID) then
						SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
						$TweetMinOld= (_GetUnixTime() - $TweeDate)/60
						if $TweetMinOld < 60 then
							sendmessages($TweeMsg)
							$newMessagesFlag=1
							ConsoleWrite('+ New messages ' & _NowTime(4) & "   ")
						Else
							ConsoleWrite('+ Old messages ' & Sec2Time($TweetMinOld*60) & @crlf)
						endif
					endif
					sleep(2000)
				Next
				if $newMessagesFlag=0 then ConsoleWrite('  No new messages ' & _NowTime(4) & @CRLF)
			endif
		endif
	EndFunc
	func _ScrapTweetMessages($Username)
		Local $sData = InetRead("https://twitter.com/"&$Username)
		Local $nBytesRead = @extended
		ConsoleWrite('@@ BytesRead = ' & $nBytesRead &"   ")
		$htmltxt = BinaryToString($sData)
		If $nBytesRead < 100000 or StringInStr($htmltxt,"subteba")<1 Then
			ConsoleWrite('  Connection issue contacting  ' & "https://twitter.com/"&$Username& @crlf)
			$htmltxt=""
			Return $htmltxt
		endif
		return $htmltxt
	EndFunc
	Func _gettweetArr($htmltxt)
		$MSGArr = StringRegExp($htmltxt, '(?s)(?i)
(.*?)
', 3)
		if IsArray($MSGArr) then
			dim  $TweetMSGArr[UBound($MSGArr)]
			For $i = 0 To UBound($MSGArr) -1
				$TweetMessage = StringRegExp($MSGArr[$i], '(?s)(?i)
(.*?)
', 1)
				$mensaje = clearstring($TweetMessage[1])
				$TweetMSGArr[$i]=$mensaje
			Next
			$TweetDate = StringRegExp($htmltxt, '(?s)(?i)data-time="(.*?)"', 3)
			$TweetIDArr = StringRegExp($htmltxt, '(?s)(?i)data-tweet-id="(.*?)"', 3)
			$TweetArrAux = _mergeArray($TweetIDArr, $TweetMSGArr)
			$TweetArr = _mergeArray($TweetArrAux, $TweetDate)
			return $TweetArr
		Else
			ConsoleWrite('!!!(' &  @ScriptLineNumber & ') : Error on  $MSGArr = ' & $MSGArr & @crlf )
			return 0
		endif
	EndFunc
#endregion
#region  ==== Bot Messages handeling ===================================================================
	Func Get_BotOffSet()
;~ 		ConsoleWrite('++Get_BotOffSet() = '& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 1.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,0)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 2.' & $OffsetFile )
			return 0
		endif
		Local $offset = FileReadLine($fileh)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("Get OffSet:"& $offset)
		FileClose($fileh)
		return $offset
	EndFunc
	Func Set_BotOffSet($offset)
		ConsoleWrite('++Set_BotOffSet() = '&$offset& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 3.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,2)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 4.' & $OffsetFile )
			return 0
		endif
		FileWriteLine($fileh,$offset)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("    Set OffSet:"& $offset &@crlf)
		FileClose($fileh)
		return 1
	EndFunc
	func UpdateUsers()
		ConsoleWrite('  '&@HOUR & ':' & @MIN&  ':' & @sec & '  Update users.  ' )
		local $s=GetBotUpdates()
		if $s then
			initMsgClass()
			$s=ParseForUserUpdate($s)
;~ 			ConsoleWrite('  $s = ' & $s & @crlf )
			if $s then
				$oJSON = _OO_JSON_Init()
				$jsonObj = $oJSON.parse($s)
				if $jsonObj.ok  then
					if $jsonObj.jsonPath( "$.result").stringify() = "[[]]" then
						ConsoleWrite(' No Bot data ' & @crlf)
					Else
						ConsoleWrite('  Updating... ' & @crlf)
						$UpdateIDArr = StripIntJS($jsonObj.jsonPath( "$.result..update_id").stringify()  )
						$MSGIDArr =   StripIntJS($jsonObj.jsonPath( "$.result..message.message_id").stringify())
						$UserIDArr =   StripIntJS($jsonObj.jsonPath( "$.result..message.from.id").stringify())
						$FnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.first_name").stringify())
						$LnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.last_name").stringify())
						$ChatIDArr =   StripIntJS($jsonObj.jsonPath( "$.result..message.chat.id").stringify())
						$ChatFnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.first_name").stringify())
						$ChatLnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.last_name").stringify())
						$epochArr =    StripIntJS($jsonObj.jsonPath( "$.result..message.date").stringify())
						$menssageArr = StripStrJS($jsonObj.jsonPath( "$.result..message.text").stringify())
						$IsBot =       StripIntJS($jsonObj.jsonPath( "$.result..message.from.is_bot").stringify())

						if $UserIDArr[0] = $UpdateIDArr[0] AND  $UserIDArr[0] = $FnameArr[0] AND _
							$UserIDArr[0] = $LnameArr[0]    AND  $UserIDArr[0] = $epochArr[0] AND _
							$UserIDArr[0] = $menssageArr[0] AND  $UserIDArr[0] = $IsBot[0]  then
							$retBad=0
							for $i=1 to $UserIDArr[0]
								if $IsBot[$i] <> "true" then
									$ret=SQLregister($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i],$menssageArr[$i])
									$ret1=ParseBotMessage($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i],$menssageArr[$i],$UpdateIDArr[$i],$MSGIDArr[$i])
									ConsoleWrite('>> $ret1 = ' & $ret1 & @crlf )
									if (Not $ret) or (Not $ret1)  then	$retBad+=1
									$UpdateID=$UpdateIDArr[$i]
								Else
									ConsoleWrite('+(' & @ScriptLineNumber & ') : $menssageArr[$i] = ' & $menssageArr[$i] & @crlf )
									ConsoleWrite('+(' & @ScriptLineNumber & ') : $IsBot[$i] = ' & $IsBot[$i] & @crlf )
									if AImessage($menssageArr[$i],"callback_query") then
										if AImessage($menssageArr[$i],"CLOSE_O") then
											TelegramActivateMessage($UpdateIDArr[$i],$menssageArr[$i],$ChatIDArr[$i],$ChatFnameArr[$i],$ChatLnameArr[$i],$epochArr[$i])
											_DeleteMsg($ChatIDArr[$i], $MSGIDArr[$i])
										else
											SQLUpdateUserAlerts($ChatIDArr[$i],$menssageArr[$i])
										endif
										$UpdateID=$UpdateIDArr[$i]
										$ahora=0
									Else
										$retBad=1
									endif
								endif
							next
							if $retBad=0 then Set_BotOffSet($UpdateID+1)
						Else
							_printFromArray($ChatIDArr,"$ChatIDArr")
							_printFromArray($ChatFnameArr,"$ChatFnameArr")
							_printFromArray($ChatLnameArr,"$ChatLnameArr")
							_printFromArray($MSGIDArr,"$MSGIDArr")
							_printFromArray($UserIDArr,"UserIDArr")
							_printFromArray($FnameArr,"FnameArr")
							_printFromArray($LnameArr,"LnameArr")
							_printFromArray($epochArr,"epochArr")
							_printFromArray($menssageArr,"menssageArr")
							_printFromArray($UpdateIDArr,"UpdateIDArr")
							_printFromArray($IsBot,"IsBot")
							ConsoleWrite('  Error in JS array . exiting..... ' & @crlf)
							exit 29
						endif
					endif
				endif
			endif
		endif
		ClearKeyBoards()
	EndFunc
	Func GetBotUpdates()
		$offset=Get_BotOffSet()
		$urlMSG="https://api.telegram.org/" & $token & "/getUpdates?offset="&$offset
		$sGet = HttpGetJson1($urlMSG)
;~ 		ConsoleWrite('@@ $sGet = ' & $sGet & @crlf )
		if $sGet<>"" then
			return $sGet
		Else
			$s_text="  Error getUpdates from Telegram = "
			ConsoleWrite('!! ' & $s_text & @crlf & "! " & $sGet)
			return false
		endif
	EndFunc
	Func StripStrJS($st)
		$st=StringReplace($st,'","',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func StripIntJS($st)
		$st=StringReplace($st,',',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func ParseForUserUpdate($s)
;~ 		eliminate "edited_message":{"
		$s=StringReplace($s,'"edited_message":{','"message":{')

;     check lastname
		$LNarr=StringRegExp($s,'"first_name":"(.*?)","language_code":"',1)
		if IsArray($LNarr) then
			for $r=0 to UBound($LNarr)-1
				$donde='"first_name":"[a-zA-Z]*","language_code":"'
				$pat='"first_name":"' & $LNarr[$r] & '","last_name":"xxx","language_code":"'
				$s=StringRegExpReplace($s,$donde,$pat)

				$donde='"first_name":"[a-zA-Z]*","type":"'
				$pat='"first_name":"' & $LNarr[$r] & '","last_name":"xxx","type":"'
				$s=StringRegExpReplace($s,$donde,$pat)
			next
		endif

;~ 		eliminate "callback_query":{"
		if StringInStr($s,'"callback_query":')> 0 then
			$s=StringRegExpReplace($s,'(?s)(?i)"callback_query":(.*?)"from":(.*?)},',"")
			$s=StringRegExpReplace($s,'},"chat_instance":"(.*?)"',"")
			$s=StringRegExpReplace($s,',"text":"(.*?)",',",")
			$s=StringRegExpReplace($s,',"data":"',',"text":"callback_query ')
		endif
;~ 		eliminate location info
;~ "location":{"latitude":-34.631010,"longitude":-58.469731}}
		if StringInStr($s,'"location":{')> 0 then
			$MsgClass[0]="Location"
				$posini=StringInStr($s,'{"latitude":')+12
				$posend=StringInStr($s,'"longitude":')-$posini-1
			$MsgClass[1]=StringMid($s,$posini,$posend)
				$posini=StringInStr($s,'"longitude":')+12
			$MsgClass[2]=StringMid($s,$posini,$posend)
			$s=StringRegExpReplace($s,'(?s)(?i)"location":{"latitude":(.*?),"longitude":(.*?)}' , '"text": "' & $MsgClass[0] & ":" & $MsgClass[1] & ":" & $MsgClass[2] & '"' )
		endif

;~ 		eliminate contact info
		$s=StringRegExpReplace($s,'(?s)(?i)"contact":(.*?)}'  ,  '"text": ""' )

;~ 		replace username last-name
		$s=StringReplace($s,'"username":','"last_name":')

;~ 		eliminate sticker info
		$s=StringRegExpReplace($s,'(?s)(?i)"sticker":(.*?)}(.*?)}'  ,  '"text": ""' )
		return $s
	EndFunc
	Func SQLregister($UserID,$Fname,$Lname,$epoch,$mensage)
;~ 	ConsoleWrite('++SQLregister() = '& @crlf)
		$existUser=0
		If SQLExistUser($UserID)=$userID then $existUser=1
		if $existUser=0 then
			$setactive=1
			$ret=SQLInsertUser($UserID,$Fname,$Lname,$epoch,$setactive)
			if $ret then
				TelegramInformNewUser($DEVChatID,$Fname,$Lname)
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			else
				$ret=TelegramErrorMessage($UserID)
				if $ret=0 then return true
			endif
			return false
		endif

		$setactive=-1
		if AIMessage($mensage,"/START") then $setactive=1
		if AIMessage($mensage,"/STOP") then $setactive=0
		if $existUser=1 AND $setactive<>-1 then
			$ret=SQLUpdateUserActive($UserID,$Fname,$Lname,$setactive)
			if $ret and $setactive=0 then
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			endif
			if $ret and $setactive=1 then
				$ret=TelegramSTARTMessage($UserID)
				if $ret=0 then return true
			endif
			if NOT $ret then TelegramErrorMessage($UserID)
			return false
		endif

		return true
	EndFunc
	Func SQLInsertUser($UserID,$Fname,$Lname,$epoch,$active=1)
		ConsoleWrite('  Nuevo usuario = '& $Fname & "  "  & $Lname  & @crlf)
		$query='INSERT INTO Users VALUES (' & $UserID & ',"' & $Fname & '","' & $Lname & '",' & $active &',0,' & $epoch & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting User ErrNo 1011" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLUpdateUserActive($UserID,$Fname,$Lname,$active=1)
		ConsoleWrite('    Usuario Activo 1/Start 0/Stop= '&$active& "  " & $Fname & "  "  & $Lname  & @crlf)
		$query='UPDATE  Users SET Active=' & $active &' WHERE UserID='& $UserID & ' ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			ConsoleWrite("       Error updating active user User ErrNo 1012" & @CRLF & $query& @crlf)
			Return false
		EndIf
	EndFunc
	Func SQLExistUser($UserID)
;~ 	ConsoleWrite('++SQLExistUser() = '& @crlf)
		$query='SELECT UserID FROM Users WHERE UserID="'&$UserID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
	Func SQLUpdateUserAlerts($UserID,$mensage,$active=1)
		$msgArr=StringSplit($mensage,"_")
		if $msgArr[2]="ON" then

		endif
;~ 		$query='UPDATE  Users SET Active=' & $active &' WHERE UserID='& $UserID & ' ;'
;~ 		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
;~ 			return true
;~ 		Else
;~ 			ConsoleWrite("       Error updating active user User ErrNo 1012" & @CRLF & $query& @crlf)
;~ 			Return false
;~ 		EndIf
	EndFunc
#endregion
#region   ===================================   keyboard   ==========================
	Func SQLregisterKeyboard($UserID,$MsgID,$epoch)
		$query='INSERT INTO Keyboard VALUES (' & $UserID & ',' & $MsgID  & ',' & $epoch & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then return true
		Return false
	EndFunc
	Func SQLUnRegisterKeyboard($UserID,$MsgID)
		$query='DELETE FROM Keyboard WHERE UserID=' & $UserID & ' AND MsgID=' & $MsgID & ' ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then return true
		Return false
	EndFunc
	Func ClearKeyBoards()
		$query='SELECT UserID,MsgID FROM Keyboard WHERE Timestamp < ' & _GetUnixTime()-60 & ';'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
;~ 			_printFromArray($qryResult)
			if UBound($qryResult)>1 then
				for $i=1 to UBound($qryResult)-1
					_DeleteMsg( $qryResult[$i][0],$qryResult[$i][1])
					SQLUnRegisterKeyboard($qryResult[$i][0],$qryResult[$i][1])
				next
			EndIf
		endif
	EndFunc
	func KeyboardActivate($UserID)
		$keybrd =  '{"inline_keyboard":['
		$keybrd &= '['
		$keybrd &= '{"text":"Linea A","callback_data":"A_ON"},'
		$keybrd &= '{"text":"Linea B","callback_data":"B_ON"},'
		$keybrd &= '{"text":"Linea C","callback_data":"C_ON"}'
		$keybrd &= '],['
		$keybrd &= '{"text":"Linea D","callback_data":"D_ON"},'
		$keybrd &= '{"text":"Linea E","callback_data":"E_ON"},'
		$keybrd &= '{"text":"Linea H","callback_data":"H_ON"}'
		$keybrd &= '],['
		$keybrd &= '{"text":"Linea P","callback_data":"P_ON"},'
		$keybrd &= '{"text":"Linea U","callback_data":"U_ON"},'
		$keybrd &= '{"text":"Listo","callback_data":"CLOSE_ON"}'
		$keybrd &= '],['
		$keybrd &= ']'
		$keybrd &= ']}'
		$res=_SendMsg($UserID,"Sus alertas activas son:"& "" & $nuevaLinea & "Cual desea activar?","HTML",$keybrd)
		$MSGID=StringRegExp($res,'"message_id":(.*?),"from":',1)
		$UsrID=StringRegExp($res,',"chat":{"id":(.*?),"first_name":',1)
		$utime=StringRegExp($res,',"date":(.*?),"text":',1)
		if IsArray($MSGID) then
			SQLregisterKeyboard($UsrID[0],$MsgID[0],$utime[0])
		endif
		if $res then return True
		return false
	EndFunc
	func KeyboardDesActivate($UserID)
		$keybrd =  '{"inline_keyboard":['
		$keybrd &= '['
		$keybrd &= '{"text":"Linea A","callback_data":"A_OFF"},'
		$keybrd &= '{"text":"Linea B","callback_data":"B_OFF"},'
		$keybrd &= '{"text":"Linea C","callback_data":"C_OFF"}'
		$keybrd &= '],['
		$keybrd &= '{"text":"Linea D","callback_data":"D_OFF"},'
		$keybrd &= '{"text":"Linea E","callback_data":"E_OFF"},'
		$keybrd &= '{"text":"Linea H","callback_data":"H_OFF"}'
		$keybrd &= '],['
		$keybrd &= '{"text":"Linea P","callback_data":"P_OFF"},'
		$keybrd &= '{"text":"Linea U","callback_data":"U_OFF"},'
		$keybrd &= '{"text":"Listo","callback_data":"CLOSE_OFF"}'
		$keybrd &= '],['
		$keybrd &= ']'
		$keybrd &= ']}'
		$res=_SendMsg($UserID,"Sus alertas activas son:"& "" & $nuevaLinea & "Cual desea desactivar?","HTML",$keybrd)
		$MSGID=StringRegExp($res,'"message_id":(.*?),"from":',1)
		$UsrID=StringRegExp($res,',"chat":{"id":(.*?),"first_name":',1)
		if IsArray($MSGID) then
			SQLunregisterKeyboard($UsrID[0],$MsgID[0])
		endif
		if $res then return True
		return false
	EndFunc
#endregion
#region   ===========================================================================
	func closeall()
		_SQLite_Close()
		_SQLite_Shutdown()
		exit 30
	EndFunc
#endregion
#region =====================================   Helpers functions  ===============================
	Func _mergeArray($array1, $array2)
		$array1 = _ArrayAdd_Column($array1)
		$size = UBound($array1)
		$newCol = UBound($array1, 2) - 1
		For $i = 0 To $size - 1
			$array1[$i][$newCol] = $array2[$i]
		Next
		Return $array1
	EndFunc   ;==>_mergeArray
	Func _ArrayAdd_Column($Array)
		Local $aTemp[UBound($Array)][UBound($Array, 0) + 1]
		For $i = 0 To UBound($Array) - 1

			For $j = 0 To UBound($Array, 0) - 1
				If UBound($Array, 0) = 1 Then $aTemp[$i][0] = $Array[$i]
				If UBound($Array, 0) > 1 Then $aTemp[$i][$j] = $Array[$i][$j]
			Next
		Next
		Return $aTemp
	EndFunc   ;==>_ArrayAdd_Column
	Func _ClearSciteConsole()
		ConsoleWrite('!!!!!!!!!!!_ClearSciteConsole Func General 92!!!!!!!!!!!!  ' & @CRLF)
		ControlSend("[CLASS:SciTEWindow]", "", "Scintilla2", "+{F5}")
	EndFunc   ;==>_ClearSciteConsole
	Func _GetDOSOutput($sCommand)
	 ConsoleWrite('++_GetDOSOutput $sCommand = ' & $sCommand & @crlf )
		Local $iPID, $sOutput = ""
		$iPID = Run('"' & @ComSpec & '" /c ' & $sCommand, "", @SW_HIDE, 2 + 4)
		While 1
			$sOutput &= StdoutRead($iPID, False, False)
			$err=@error
			If $err Then
				ConsoleWrite('!!  _GetDOSOutput $err = ' & $err & @crlf )
				ExitLoop
			EndIf
	;~ 	Sleep(10)
		WEnd
		ConsoleWrite('>> 	Output = ' & $sOutput & @crlf )
		Return $sOutput
	EndFunc   ;==>_GetDOSOutput
	Func _timeBetween($cTime, $sTime, $eTime)
		 If Not _DateIsValid('2000/01/01 ' & $cTime) Then Return -1
		 If Not _DateIsValid('2000/01/01 ' & $sTime) Then Return -2
		 If Not _DateIsValid('2000/01/01 ' & $eTime) Then Return -3
		 If _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') < 0 And _
			 _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') > 0 Then
			  Return 1
		 Else
			  Return 0
		 EndIf
	EndFunc  ; ==>_timeBetween
#endregion
#region time
	Func  Sec2Time($nr_sec)
		$sec2time_hour = Int($nr_sec / 3600)
		$sec2time_min = Int(($nr_sec - $sec2time_hour * 3600) / 60)
		$sec2time_sec = $nr_sec - $sec2time_hour * 3600 - $sec2time_min * 60
		Return StringFormat('%02d:%02d:%02d', $sec2time_hour, $sec2time_min, $sec2time_sec)
	EndFunc   ;==>Sec2Time
	Func _GetUnixTime($sDate = 0);Date Format: 2013/01/01 00:00:00 ~ Year/Mo/Da Hr:Mi:Se
		Local $aSysTimeInfo = _Date_Time_GetTimeZoneInformation()
		Local $utcTime = ""
		If Not $sDate Then $sDate = _NowCalc()
		If Int(StringLeft($sDate, 4)) < 1970 Then Return ""
		If $aSysTimeInfo[0] = 2 Then
			$utcTime = _DateAdd('n', $aSysTimeInfo[1] + $aSysTimeInfo[7], $sDate)
		Else
			$utcTime = _DateAdd('n', $aSysTimeInfo[1], $sDate)
		EndIf
		Return _DateDiff('s', "1970/01/01 00:00:00", $utcTime)
	EndFunc   ;==>_GetUnixTime
#endregion


replaced by runscreensaver

replaced by runscreensaver

https://github.com/sinky/runscreensaver


Remove redundant reboot codes. Use compiler tidy feature.

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Run_Tidy=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include <Constants.au3>
#include <myutil.au3>

HotKeySet("^!x", "MyExit")

If $CmdLine[0] = 0 Then
	ChangeTimeZoneToJST()
	InstallJapaneseLanguagePack()

	FileCopy(@ScriptFullPath, @TempDir)
	MyUtil_RegWriteRunOnce(@ScriptName, @TempDir & "\" & @ScriptName & " " & "step2")
	MyUtil_Reboot()
ElseIf $CmdLine[0] = 1 And $CmdLine[1] = "step2" Then
	ChangeDisplayLanguageToJapanese()
	MyUtil_Reboot()
EndIf

Func InstallJapaneseLanguagePack()
	; >= Vista
	Run("control /name Microsoft.WindowsUpdate")
	$title = "Windows Update"
	Local $hWnd = WinWait($title)
	ControlClick($hWnd, "", "[CLASS:Button; TEXT:&Check for updates]")
	MyUtil_ControlWaitVisible($hWnd, "", "[CLASS:Button; TEXT:&Install updates]")

	; Go to important update list.
	ControlFocus($hWnd, "", "[CLASS:Button; TEXT:&Install updates]")
	Send("+{TAB}+{TAB}{SPACE}")
	Local $hWnd2 = WinWaitActive("Select updates to install")

	; Hide update of Internet Explorer 10 for Windows 7
	If MyUtil_ListViewGoToItem($hWnd2, "", "[CLASS:WuDuiListView; INSTANCE:1]", _
			"Internet Explorer 10 for Windows 7", 1) = 0 Then
		Send("{APPSKEY}{DOWN 2}{ENTER}")
		Sleep(1000)
	EndIf
	; Hide update of Internet Explorer 11 for Windows 7
	If MyUtil_ListViewGoToItem($hWnd2, "", "[CLASS:WuDuiListView; INSTANCE:1]", _
			"Internet Explorer 11 for Windows 7", 1) = 0 Then
		Send("{APPSKEY}{DOWN 2}{ENTER}")
		Sleep(1000)
	EndIf

	; Go back to the previous screen
	Send("!{LEFT}")
	$hWnd = WinWait($title)

	; Go to optional update list.
	ControlFocus($hWnd, "", "[CLASS:Button; TEXT:&Install updates]")
	Send("+{TAB}{SPACE}")
	$hWnd2 = WinWait("Select updates to install")

	; Check Japanese Language Pack
	Local Const $iItemCountInWindows7Section = 5
	If MyUtil_ListViewGoToItemWithOffset($hWnd2, "", "[CLASS:WuDuiListView; INSTANCE:1]", _
			"Japanese Language Pack - Windows 7 Service Pack 1 (KB2483139)", 1, _
			$iItemCountInWindows7Section + 1) = 0 Then
		Send("{SPACE}")
		Sleep(1000)
	Else
		MsgBox(0, @ScriptName, "japanese language pack not found in list", 5)
	EndIf

	ControlClick($hWnd, "", "[CLASS:Button; TEXT:OK]")
	WinWaitActive($title)
	ControlClick($hWnd, "", "[CLASS:Button; TEXT:&Install updates]")

	; Wait for [Restart now] button, but don't press it.
	MyUtil_ControlWaitVisible($hWnd, "", "[CLASS:Button; TEXT:&Restart now]")
EndFunc   ;==>InstallJapaneseLanguagePack

Func ChangeDisplayLanguageToJapanese()
	Run("control international")
	$title = "Region and Language"
	Local $hWnd = WinWait($title)

	MyUtil_SelectTab($hWnd, "", "[CLASS:SysTabControl32; INSTANCE:1]", "Formats")
	; Select Format
	ControlCommand($hWnd, "", "[CLASS:ComboBox; INSTANCE:1]", "SelectString", "Japanese (Japan)")

	MyUtil_SelectTab($hWnd, "", "[CLASS:SysTabControl32; INSTANCE:1]", "Location")
	; Select Current location
	ControlCommand($hWnd, "", "[CLASS:ComboBox; INSTANCE:1]", "SelectString", "Japan")

	MyUtil_SelectTab($hWnd, "", "[CLASS:SysTabControl32; INSTANCE:1]", "Keyboards and Languages")
	ControlClick($hWnd, "", "[CLASS:Button; TEXT:&Change keyboards...]")

	Local $hWnd2 = WinWait("Text Services and Input Languages")
	ControlClick($hWnd2, "", "[CLASS:Button; TEXT:A&dd...]")

	; Add Japanese IME to input language
	Local $hWnd3 = WinWait("Add Input Language")
	ControlTreeView($hWnd3, "", "[CLASS:SysTreeView32; INSTANCE:1]", "Expand", "Japanese (Japan)")
	ControlTreeView($hWnd3, "", "[CLASS:SysTreeView32; INSTANCE:1]", "Expand", "Japanese (Japan)|Keyboard")
	ControlTreeView($hWnd3, "", "[CLASS:SysTreeView32; INSTANCE:1]", "Check", "Japanese (Japan)|Keyboard|Microsoft IME")
	ControlClick($hWnd3, "", "[CLASS:Button; TEXT:OK]")

	; Choose Japanese IME as Default input language
	ControlCommand($hWnd2, "", "[CLASS:ComboBox; INSTANCE:1]", "SelectString", "Japanese (Japan) - Microsoft IME")
	ControlClick($hWnd2, "", "[CLASS:Button; TEXT:OK]")

	; Choose Japanese as Display Language
	ControlSend($hWnd, "", "[CLASS:ComboBox; INSTANCE:1]", "{DOWN}")
	ControlClick($hWnd, "", "[CLASS:Button; TEXT:OK]")
EndFunc   ;==>ChangeDisplayLanguageToJapanese

Func ChangeTimeZoneToJST()
	Run("control date/time")
	Local $hWnd = WinWait("Date and Time")
	ControlClick($hWnd, "", "[CLASS:Button; TEXT:Change time &zone...]")

	Local $hWnd2 = WinWait("Time Zone Settings")
	ControlCommand($hWnd2, "", "[CLASS:ComboBox; INSTANCE:1]", "SelectString", "(UTC+09:00) Osaka, Sapporo, Tokyo")
	ControlClick($hWnd2, "", "[CLASS:Button; TEXT:OK]")

	ControlClick($hWnd, "", "[CLASS:Button; TEXT:OK]")
EndFunc   ;==>ChangeTimeZoneToJST

Func MyExit()
	MsgBox(0, @ScriptName, "Aborting now because the hot-key was pressed.", 3);
	Exit
EndFunc   ;==>MyExit

#include <Constants.au3>
#include <myutil.au3>

HotKeySet("^!x", "MyExit")

If $CmdLine[0] = 0 Then
	ChangeTimeZoneToJST()
	InstallJapaneseLanguagePack()

	FileCopy(@ScriptFullPath, @TempDir)
	MyUtil_RegWriteRunOnce(@ScriptName, @TempDir & "\" & @ScriptName & " " & "step2")
	MyUtil_Reboot()
ElseIf $CmdLine[0] = 1 And $CmdLine[1] = "step2" Then
	ChangeDisplayLanguageToJapanese()
EndIf

Func InstallJapaneseLanguagePack()
	; >= Vista
	Run("control /name Microsoft.WindowsUpdate")
	$title = "Windows Update"
	Local $hWnd = WinWait($title)
	ControlClick($hWnd, "", "[CLASS:Button; TEXT:&Check for updates]")
	MyUtil_ControlWaitVisible($hWnd, "", "[CLASS:Button; TEXT:&Install updates]")

	; Go to important update list.
	ControlFocus($hWnd, "", "[CLASS:Button; TEXT:&Install updates]")
	Send("+{TAB}+{TAB}{SPACE}")
	Local $hWnd2 = WinWaitActive("Select updates to install")

	; Hide update of Internet Explorer 10 for Windows 7
	If MyUtil_ListViewGoToItem($hWnd2, "", "[CLASS:WuDuiListView; INSTANCE:1]", _
		"Internet Explorer 10 for Windows 7", 1) = 0 Then
		Send("{APPSKEY}{DOWN 2}{ENTER}")
		Sleep(1000)
	EndIf
	; Hide update of Internet Explorer 11 for Windows 7
	If MyUtil_ListViewGoToItem($hWnd2, "", "[CLASS:WuDuiListView; INSTANCE:1]", _
		"Internet Explorer 11 for Windows 7", 1) = 0 Then
		Send("{APPSKEY}{DOWN 2}{ENTER}")
		Sleep(1000)
	EndIf

	; Go back to the previous screen
	Send("!{LEFT}")
	$hWnd = WinWait($title)

	; Go to optional update list.
	ControlFocus($hWnd, "", "[CLASS:Button; TEXT:&Install updates]")
	Send("+{TAB}{SPACE}")
	$hWnd2 = WinWait("Select updates to install")

	; Check Japanese Language Pack
	Local Const $iItemCountInWindows7Section = 5
	If MyUtil_ListViewGoToItemWithOffset($hWnd2, "", "[CLASS:WuDuiListView; INSTANCE:1]", _
		"Japanese Language Pack - Windows 7 Service Pack 1 (KB2483139)", 1, _
		$iItemCountInWindows7Section + 1) = 0 Then
		Send("{SPACE}")
		Sleep(1000)
	Else
		MsgBox(0, @ScriptName, "japanese language pack not found in list", 5)
	EndIf

	ControlClick($hWnd, "", "[CLASS:Button; TEXT:OK]")
	WinWaitActive($title)
	ControlClick($hWnd, "", "[CLASS:Button; TEXT:&Install updates]")

	MyUtil_ControlWaitVisible($hWnd, "", "[CLASS:Button; TEXT:&Restart now]")
	ControlClick($hWnd, "", "[CLASS:Button; TEXT:&Restart now]")
EndFunc   ;==>InstallJapaneseLanguagePack

Func ChangeDisplayLanguageToJapanese()
	Run("control international")
	$title = "Region and Language"
	Local $hWnd = WinWait($title)

	MyUtil_SelectTab($hWnd, "", "[CLASS:SysTabControl32; INSTANCE:1]", "Formats")
	; Select Format
	ControlCommand($hWnd, "", "[CLASS:ComboBox; INSTANCE:1]", "SelectString", "Japanese (Japan)")

	MyUtil_SelectTab($hWnd, "", "[CLASS:SysTabControl32; INSTANCE:1]", "Location")
	; Select Current location
	ControlCommand($hWnd, "", "[CLASS:ComboBox; INSTANCE:1]", "SelectString", "Japan")

	MyUtil_SelectTab($hWnd, "", "[CLASS:SysTabControl32; INSTANCE:1]", "Keyboards and Languages")
	ControlClick($hWnd, "", "[CLASS:Button; TEXT:&Change keyboards...]")

	Local $hWnd2 = WinWait("Text Services and Input Languages")
	ControlClick($hWnd2, "", "[CLASS:Button; TEXT:A&dd...]")

	; Add Japanese IME to input language
	Local $hWnd3 = WinWait("Add Input Language")
	ControlTreeView($hWnd3, "", "[CLASS:SysTreeView32; INSTANCE:1]", "Expand", "Japanese (Japan)")
	ControlTreeView($hWnd3, "", "[CLASS:SysTreeView32; INSTANCE:1]", "Expand", "Japanese (Japan)|Keyboard")
	ControlTreeView($hWnd3, "", "[CLASS:SysTreeView32; INSTANCE:1]", "Check", "Japanese (Japan)|Keyboard|Microsoft IME")
	ControlClick($hWnd3, "", "[CLASS:Button; TEXT:OK]")

	; Choose Japanese IME as Default input language
	ControlCommand($hWnd2, "", "[CLASS:ComboBox; INSTANCE:1]", "SelectString", "Japanese (Japan) - Microsoft IME")
	ControlClick($hWnd2, "", "[CLASS:Button; TEXT:OK]")

	; Choose Japanese as Display Language
	ControlSend($hWnd, "", "[CLASS:ComboBox; INSTANCE:1]", "{DOWN}")
	ControlClick($hWnd, "", "[CLASS:Button; TEXT:OK]")

	Local $hWnd4 = WinWait("Change Display Language")

	; Prefer reboot to logoff because you don't have to input passwords manually.
	;ControlClick($hWnd4, "", "[CLASS:Button; TEXT:Log off now]")
	MyUtil_Reboot()
EndFunc   ;==>ChangeDisplayLanguageToJapanese

Func ChangeTimeZoneToJST()
	Run("control date/time")
	Local $hWnd = WinWait("Date and Time")
	ControlClick($hWnd, "", "[CLASS:Button; TEXT:Change time &zone...]")

	Local $hWnd2 = WinWait("Time Zone Settings")
	ControlCommand($hWnd2, "", "[CLASS:ComboBox; INSTANCE:1]", "SelectString", "(UTC+09:00) Osaka, Sapporo, Tokyo")
	ControlClick($hWnd2, "", "[CLASS:Button; TEXT:OK]")

	ControlClick($hWnd, "", "[CLASS:Button; TEXT:OK]")
EndFunc   ;==>ChangeTimeZoneToJST

Func MyExit()
	MsgBox(0, @ScriptName, "Aborting now because the hot-key was pressed.", 3);
	Exit
EndFunc


close fixed

close fixed

#include <config.au3>
#include <utils.au3>

Func botStart()
   bluestacksShow()
   btnToggle('start bot', $CLASBOT_WINDOW_TOGGLE_START, 'start bot', 'stop')
EndFunc

Func botStop()
   bluestacksHide()
   btnToggle('stop', $CLASBOT_WINDOW_TOGGLE_START, 'start bot', 'stop')
EndFunc

Func bluestacksShow()
   btnToggle('show bluestacks', $CLASBOT_WINDOW_TOGGLE_HIDE, 'show bluestacks', 'hide bluestacks')
EndFunc

Func bluestacksHide()
   btnToggle('hide bluestacks', $CLASBOT_WINDOW_TOGGLE_HIDE, 'show bluestacks', 'hide bluestacks')
EndFunc

Func btnToggle($action = '', $toggleBtn = '', $textOptionA = '', $textOptionB = '')
   If Not isClashBotRunning() AND Not isLoggedIn() Then
	  msgNotify('err', 'clash bot not running.')
	  ; Not running and not logged in.. Strage state.
	  Return False
   EndIf

   WinActivate($CLASBOT_WINDOW) ; brint to front each toggle. might prevent some odd bugs.

   Local $btnToggleText = ControlGetText($CLASBOT_WINDOW, '', $toggleBtn)

   If ('' == $action) OR ($textOptionA == StringLower($btnToggleText) AND $textOptionA == $action) OR ($textOptionB == StringLower($btnToggleText) AND $textOptionB == $action) Then
	  click($CLASBOT_WINDOW, $toggleBtn)
   Else
	  ; invalid state or already in the requested state.
   EndIf

EndFunc

Func closeClashBotApp()
   Local $hWnd = WinGetHandle($CLASBOT_WINDOW)

   If isClashBotRunning() Then
      WinActivate($CLASBOT_WINDOW)
      WinClose($hWnd);
   EndIf
EndFunc

Func loadClashBotApp()
   Local $hWnd = WinGetHandle($CLASBOT_WINDOW)

   If Not isClashBotRunning() Then
	  runBot()
   ElseIf Not isLoggedIn() Then
	  login()
   Else
	  ; all good.. continue. not extra steps needed.
   EndIf

   WinActivate($CLASBOT_WINDOW) ; bring to front.
EndFunc

Func login()
   WinWait($CLASBOT_WINDOW, '', 10)
   Sleep(1000)

   If Not isLoggedIn() Then
	  click($CLASBOT_WINDOW, $CLASBOT_WINDOW_BTN_LOGIN)
	  closeConfirmationBox()
   EndIf
EndFunc

Func closeConfirmationBox()
   WinWait($CLASBOT_CONFIRM_WINDOW, '', 2);
   WinClose($CLASBOT_CONFIRM_WINDOW);
EndFunc

Func runBot()
   Run($CLASHBOT_PATH & $CLASHBOT_EXEC, $CLASHBOT_PATH)

   login()
EndFunc

Func isLoggedIn()
   WinWait($CLASBOT_WINDOW, '', 10)
   Local $loginBtn = ControlGetHandle($CLASBOT_WINDOW, '', $CLASBOT_WINDOW_BTN_LOGIN);

   If @error AND isClashBotRunning() Then
	  Return True
   Else
	  Return False
   EndIf
EndFunc

Func isClashBotRunning()
   Local $hWnd = WinGetHandle($CLASBOT_WINDOW)

   If @error Then
	  Return False
   Else
	  Return True
   EndIf
EndFunc

Func isStarted()
   If Not isClashBotRunning() AND Not isLoggedIn() Then
	  ; msgNotify('err', 'clash bot not running.')
	  ; Not running and not logged in.. Strage state.
	  Return False
   EndIf

   Local $btnToggleText = ControlGetText($CLASBOT_WINDOW, '', $CLASBOT_WINDOW_TOGGLE_START)

   If 'Stop' == $btnToggleText Then
      Return True
   Else
      Return False
   EndIf
EndFunc

#include <config.au3>
#include <utils.au3>

Func botStart()
   bluestacksShow()
   btnToggle('start bot', $CLASBOT_WINDOW_TOGGLE_START, 'start bot', 'stop')
EndFunc

Func botStop()
   bluestacksHide()
   btnToggle('stop', $CLASBOT_WINDOW_TOGGLE_START, 'start bot', 'stop')
EndFunc

Func bluestacksShow()
   btnToggle('show bluestacks', $CLASBOT_WINDOW_TOGGLE_HIDE, 'show bluestacks', 'hide bluestacks')
EndFunc

Func bluestacksHide()
   btnToggle('hide bluestacks', $CLASBOT_WINDOW_TOGGLE_HIDE, 'show bluestacks', 'hide bluestacks')
EndFunc

Func btnToggle($action = '', $toggleBtn = '', $textOptionA = '', $textOptionB = '')
   If Not isClashBotRunning() AND Not isLoggedIn() Then
	  msgNotify('err', 'clash bot not running.')
	  ; Not running and not logged in.. Strage state.
	  Return False
   EndIf

   WinActivate($CLASBOT_WINDOW) ; brint to front each toggle. might prevent some odd bugs.

   Local $btnToggleText = ControlGetText($CLASBOT_WINDOW, '', $toggleBtn)

   If ('' == $action) OR ($textOptionA == StringLower($btnToggleText) AND $textOptionA == $action) OR ($textOptionB == StringLower($btnToggleText) AND $textOptionB == $action) Then
	  click($CLASBOT_WINDOW, $toggleBtn)
   Else
	  ; invalid state or already in the requested state.
   EndIf

EndFunc

Func closeClashBotApp()
   Local $hWnd = WinGetHandle($CLASBOT_WINDOW)

   If isClashBotRunning() Then
      WinWait($hWnd, '', 5);
      WinClose($hWnd);
   EndIf
EndFunc

Func loadClashBotApp()
   Local $hWnd = WinGetHandle($CLASBOT_WINDOW)

   If Not isClashBotRunning() Then
	  runBot()
   ElseIf Not isLoggedIn() Then
	  login()
   Else
	  ; all good.. continue. not extra steps needed.
   EndIf

   WinActivate($CLASBOT_WINDOW) ; bring to front.
EndFunc

Func login()
   WinWait($CLASBOT_WINDOW, '', 10)
   Sleep(1000)

   If Not isLoggedIn() Then
	  click($CLASBOT_WINDOW, $CLASBOT_WINDOW_BTN_LOGIN)
	  closeConfirmationBox()
   EndIf
EndFunc

Func closeConfirmationBox()
   WinWait($CLASBOT_CONFIRM_WINDOW, '', 5);
   WinClose($CLASBOT_CONFIRM_WINDOW);
EndFunc

Func runBot()
   Run($CLASHBOT_PATH & $CLASHBOT_EXEC, $CLASHBOT_PATH)

   login()
EndFunc

Func isLoggedIn()
   WinWait($CLASBOT_WINDOW, '', 10)
   Local $loginBtn = ControlGetHandle($CLASBOT_WINDOW, '', $CLASBOT_WINDOW_BTN_LOGIN);

   If @error AND isClashBotRunning() Then
	  Return True
   Else
	  Return False
   EndIf
EndFunc

Func isClashBotRunning()
   Local $hWnd = WinGetHandle($CLASBOT_WINDOW)

   If @error Then
	  Return False
   Else
	  Return True
   EndIf
EndFunc

Func isStarted()
   If Not isClashBotRunning() AND Not isLoggedIn() Then
	  ; msgNotify('err', 'clash bot not running.')
	  ; Not running and not logged in.. Strage state.
	  Return False
   EndIf

   Local $btnToggleText = ControlGetText($CLASBOT_WINDOW, '', $CLASBOT_WINDOW_TOGGLE_START)

   If 'Stop' == $btnToggleText Then
      Return True
   Else
      Return False
   EndIf
EndFunc


updated arena bot

updated arena bot

;Shift+alt
HotKeySet("+!a", "startArena")
HotKeySet("+!z", "changeArenaTier")
HotKeySet("+!s", "idle")
HotKeySet("+!d", "fight")
HotKeySet("+!f", "findMatch")
HotKeySet("+!g", "nextNode")
HotKeySet("+!h", "fightArena")
HotKeySet("+!p", "playthegame")
HotKeySet("+!c", "calibrateWindow")

Global $savepixel = 0
Global $screensave[6]
$screensave[0] = 0
$screensave[1] = 0
$screensave[2] = 0
$screensave[3] = 0
$screensave[4] = 0
$screensave[5] = 0

;This indicates which arena tier shall be played, possible is 2, or 3
$arena_tier = 2
$arena_continue = 1
$allstop = 0
Do
   Sleep(1)
Until False

Func idle()
   $allstop = 1
   MsgBox(0, "now", "terminated", 1)
   Do
	  Sleep(1)
   Until False
EndFunc   ;==>Terminate

Func playthegame()
   MouseClick("left", 26, 750) ;window start menu
   MouseClick("left", 70, 400) ;bluestack app
   Sleep(90000)
   MsgBox(0, "now", "i will now move the bluestack window", 5)
   MouseClickDrag("left", 90, 30, 75, 15)
   Sleep(2000)
   MouseClick("left", 913, 307) ;click the game
   Sleep(60000)
   playthearena()
EndFunc
Func playthearena()
   MouseClick("left", 162, 51)
   Sleep(1000)
   MouseClick("left", 271, 135) ;fight button
   Sleep(20000)
   MouseClick("left", 535, 313) ;versus
   Sleep(20000)
   startArena()
EndFunc

Func changeArenaTier()
   if ($arena_tier==2) Then
	  $arena_tier = 3
	  MsgBox(0, "arena tier", "arena tier is now 3", 2)
   Elseif ($arena_tier==3) Then
	  $arena_tier = 4
	  MsgBox(0, "arena tier", "arena tier is now alltier(when there is no event)", 2)
   Else
	  $arena_tier = 2
	  MsgBox(0, "arena tier", "arena tier is now 2", 2)
   EndIf
EndFunc

;Starts the arena (Fight menu), and continue (tier *2)
Func startArena()
   $allstop = 0
   Do
	  Sleep(500)
	  MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
	  Sleep(1000)

	  if (Not(getDominantColor(PixelGetColor(346,535))=="green")) Then
		 MsgBox(0, "fight", "inside fight, not arena", 1)
		 MouseClick("left", 500,446)
		 Sleep(5000)
	  EndIf
	  if ($arena_tier==2) Then
		 ;Send("9")
		 MouseClick("left", 386, 446)
		 Sleep(5000)
		 MouseClick("left", 413, 522);double check
	  Elseif ($arena_tier==3) Then
		 MouseClick("left", 830, 510)
		 Sleep(5000)
		 MouseClick("left", 760, 508);double check
	  Else ;arena tier 4
		 MouseClick("left", 433, 522);
		 Sleep(5000);
	  EndIf
	  Sleep(5000)
	  Local $current_arena_tier  = $arena_tier
	  $arena_continue = 1
	  askForHelp()
	  if ($arena_continue==1) Then
		 ; We have energy, continue;else change arena tier in next loop
		 addToTeam()
		 findMatch()
		 fightArena()
	  EndIf

   Until ($allstop==1)
EndFunc

Func askForHelp()
   Local $carryon = 1
   Do
	  ;Detect if we can ask for help
	  Local $helpbutton = PixelGetColor(260, 175)
	  Local $red = BitShift($helpbutton, 16)
	  Local $green = BitShift(BitAND($helpbutton, 0x00FF00), 8)
	  Local $blue = BitAND($helpbutton, 0x0000FF)
	  if ($green > $red) Then
		 if ($green > $blue) Then
			Send("Q")
			Sleep(3000)
		 Else
			$carryon = 0
		 EndIf
	  Else
		 $carryon = 0
	  EndIf
   Until ($carryon==0)

   ;Detect if less than 3 champion has energy
   Local $redtag = PixelGetColor(630,188)
   Local $red = BitShift($redtag, 16)
   Local $green = BitShift(BitAND($redtag, 0x00FF00), 8)
   Local $blue = BitAND($redtag, 0x0000FF)
   if (($red-80) > $green) Then
	  if (($red-80) > $blue) Then
		 MsgBox(0, "Out of energy", "we're out of energy", 2)
		 $arena_continue = 0
		 Sleep(4000)
		 MouseClick("left", 57, 55)
		 if ($arena_tier==2) Then
			$arena_tier = 3
		 Else
			$arena_tier = 2
		 EndIf
		 Sleep(7000)
	  EndIf
   EndIf

   ;Detect if there are any Reconnect popup
   if (PixelGetColor(490,320)==0x2b2c30) Then
	  if (getDominantColor(PixelGetColor(490,350))=="green") Then
		 MsgBox(0, "popup", "I'll press the popup button in 5", 5)
		 Sleep(6000)
		 MouseClick("left", 490, 350)
		 Sleep(7000)
	  EndIf
   EndIf

   ;detect if we're in useless milestone info
   if (getDominantColor(PixelGetColor(934,555))=="green") Then
	  if ((PixelGetColor(492,337)==0x2b2c30)) Then
		 MsgBox(0, "milestone", "I assume we're in milestone info", 1)
		 Sleep(1000)
		 $arena_continue = 0
		 MouseClick("left", 57, 55)
		 Sleep(7000)
	  EndIf
   EndIf

   ;if we're in continue next fight
   if (getDominantColor(PixelGetColor(936,556))=="green") Then
	  if (PixelGetColor(688,436)==0x191e23) Then
		 $arena_continue = 0
		 fightArena()
	  EndIf
   EndIf
EndFunc

;arena
Func addToTeam()
   MouseClickDrag("left", 319, 235, 145, 135)
   sleep(500)
   MouseClickDrag("left", 319, 235, 145, 210)
   sleep(500)
   MouseClickDrag("left", 319, 235, 145, 290)
   sleep(500)
EndFunc

;Arena
Func findMatch()
   Sleep(500)
   MouseClick("left", 109, 547)
   Sleep(4000)

   PixelSearch(543,416,575,429, 0x319732)
   if (@error) Then
	  ;highest is not easy, check if mid easy
	  PixelSearch(543,280,575,294, 0x319732)
	  if (@error) Then
		 ;mid is not easy
		 MsgBox(0,"tier", "mid and high is not easy",1)
		 MouseClick("left", 600,200)
	  Else
		 ;mid is easy
		 MouseClick("left", 600,320)
	  EndIf
   Else
	  ;highest is easy
	  MouseClick("left", 687, 445)
   EndIf

   Sleep(3000)
   Send("0")
   $c = PixelGetColor(841,574)
   Local $t = 0
   Local $cont = 1
   Do
	  Sleep(500)
	  if ($t>120) Then
		 ;stuck
		 $cont = 0
	  EndIf
	  if (Not(PixelGetColor(841,574)==$c)) Then
		 $cont = 0
	  EndIf
	  $t = $t+1
   Until ($cont==0)
EndFunc

;Fight in arena
Func fightArena()
   $seq = 0
   $stop = 0
   $allstop = 0

   ;stuck in something handler
   Local $somewhereoutsidecounter = 0
   Local $stuckseq = 0
   Local $startarena = TimerInit()
   Local $arenatimersecond = 0
   Do
	  $stuckseq = $stuckseq+1
	  if (Mod($stuckseq,400)==0) Then
		 ;ToolTip("check stuck")
		 if (checkStuck()) Then
			updateCapture()
			$stop = 1
			MsgBox(0, "popup", "i guess we're stuck", 2)

			;stuck in leaderboard
			if (PixelGetColor(921,138)==0x292c30) Then
			   if (PixelGetColor(939,61)==0x6c6e71) Then
				  MsgBox(0, "popup", "leaderboard, ill close it", 1)
				  Sleep(2000)
				  MouseClick("left", 939,61)
				  Sleep(3000)
			   EndIf
			EndIf
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight

			Sleep(10000)
		 EndIf
		 updateCapture()

		 ;check if too long playing maybe something is not right
		 Local $dif = TimerDiff($startarena)
		 if ($dif > 30000) Then
			$startarena = TimerInit()
			$arenatimersecond = $dif/1000
		 EndIf
		 if ($arenatimersecond > 120) Then
			MsgBox(0, "popup", "too long minutes ", 3)
			Sleep(5000)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 138, 58) ;menu double
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight
			Sleep(10000)
		 EndIf
	  EndIf

	  Send("0")
	  Sleep(1);
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  $seq = $seq + 1
	  if ($seq>15) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf
	  if (getDominantColor(PixelGetColor(144,541))=="red") then
		 Send("{SPACE}")
	  EndIf

	  ;indicates fight has ended (loading screen)
	  $loading = PixelGetColor(640, 540);
	  if ($loading==0x025c00) Then
		 $loading = PixelGetColor(620, 300)
		 if ($loading==0x161a1b) Then
			$stop = 1
			MsgBox(0, "popup", "shall i press back button?", 2)
			Sleep(2000)
			MouseClick("left", 57, 55); back because we might ended up in 3* 4* tier arena
			Sleep(10000)
		 EndIf
	  EndIf

	  ;or chat bar has been clicked
	  if ($loading==0x161a1d) Then
		 if (PixelGetColor(136,540)==0x292c30) Then
			$stop = 1
			MsgBox(0,"chat", "this is chat window", 1)
			Sleep(1000)
			MouseClick("left", 943, 52); close
			Sleep(2000)
		 EndIf
	  EndIf

	  ; or the case if we ended up in view rewards
	  $loading = PixelGetColor(480,270)
	  if ($loading==0x2b2c30) Then
		 $loading = PixelGetColor(480,330)
		 if ($loading==0x2b2c30) Then
			$stop = 1
			Sleep(3000)
			MouseClick("left", 57, 55); back because we ended up in 3* 4* tier arena
			Sleep(10000)
		 EndIf
	  ElseIf ($loading==0x000000) Then
		 ; stuck in alliance quest window; todo alliance quest window with empty quest
		 if (PixelGetColor(838,366)==0x2b2c30) Then
			$stop = 1
			MsgBox(0,"alliance q", "alliance quest cuy", 1);
			$arena_tier = 2
			Sleep(2000)
			MouseClick("left", 57, 55);
			Sleep(10000)
		 EndIf
	  EndIf

	  ;stuck in alliance quest window
	  $loading = PixelGetColor(384,142)
	  if ($loading==0x1a1a1a) Then
		 if (PixelGetColor(551,142)==0x1a1a1a) Then
			if (Not(PixelGetColor(504,142)==0x1a1a1a)) Then
			   $stop = 1
			   MsgBox(0,"alliance q", "empty alliance quest cuy", 1);
			   $arena_tier = 2
			   Sleep(2000)
			   MouseClick("left", 57, 55);
			   Sleep(10000)
			EndIf
		 EndIf
	  EndIf

	  ;MsgBox(0, "dbg", StringFormat("%X", PixelGetColor(18,130)), 1)
	  ; or the case we stuck in team adding
	  if (PixelGetColor(18, 130)==0x2b2c30) Then ; the left bar team list
		 if (PixelGetColor(936,511)==0x2b2c30) Then ;the champion filter button
			$stop = 1
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(10000)
		 EndIf
	  EndIf
	  if (PixelGetColor(18, 130)==0x0b0b0c) Then ; the left bar team list
		 if (PixelGetColor(936,511)==0x0b0b0c) Then ;the champion filter button
			$stop = 1
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(10000)
		 EndIf
	  EndIf

	  ;or the case we're in somewhere outside  (menu)
	  if (PixelGetColor(955,50)==0x2b2c30) Then
		 if (PixelGetColor(955, 562)==0x1d2630) Then
			if (Not(getDominantColor(PixelGetColor(936,556))=="green")) Then
			   $somewhereoutsidecounter = $somewhereoutsidecounter+1
			   if ($somewhereoutsidecounter>10) Then
				  $stop = 1
				  Sleep(1000)
				  Send("J")
				  Sleep(1000)
				  MouseClick("left", 148, 58) ;menu
				  Sleep(1000)
				  MouseClick("left", 138, 58) ;menu double
				  Sleep(1000)
				  MouseClick("left", 270, 132) ;fight
				  Sleep(5000)
			   EndIf
			EndIf
		 EndIf
	  EndIf

   Until ($stop==1 or $allstop==1)
EndFunc

;FIGHT In quest
Func fight()
   $seq = 0
   $stop = 0
   $allstop = 0
   Do
	  Send("0")
	  Sleep(30);
	  $seq = $seq + 1
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  if ($seq>12) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf

	  if (Mod($seq,2)==0) Then
		 $loading = PixelGetColor(958, 577);
		 if ($loading==0x1d2630) Then
		 ;indicates fight has ended
			$loading = PixelGetColor(923, 491)
			if ($loading==0xc1c1c2) Then
			   $stop = 1
			   Sleep(3000)
			   Send("J")
			EndIf
		 ElseIf ($loading==0x07090c) Then
			if (PixelGetColor(825,105)==0x2b2c30) Then
			   $stop = 1
			   Sleep(3000)
			   Send("J")
			EndIf
		 ;Elseif (PixelGetColor(486,310)==0xeeeeee) Then
			;we're in loading  screen
			;$stop = 1
			;Sleep(3000)
			;Send("J")
		 EndIf
	  EndIf
   Until ($stop==1 or $allstop==1)
EndFunc

Func nextNode()
   $allstop = 0
   Do
	  Local $step = 0
	  Do
		 $step = $step + 1
		 if ($step == 10) Then
			MouseClickDrag("left", 450, 320, 642, 346)
		 ElseIf ($step == 20) Then
			MouseClickDrag("left", 450, 320, 200, 200)
			MouseClickDrag("left", 450, 320, 300, 300)
		 ElseIf ($step == 30) Then
			MouseClickDrag("left", 700, 100, 100, 400)
		 ElseIf ($step == 40) Then
			MouseClickDrag("left", 100, 400, 700, 100)
			MouseClickDrag("left", 100, 400, 700, 100)
			$step = 0
		 EndIf
		 Send("J")
		 Sleep(200)
		 $greendot = PixelSearch(80,100, 957, 530, 0x00f800)
		 if (@error) Then
			$greendot = PixelSearch(80,100, 957, 530, 0x00e400)
		 EndIf
	  Until not(@error)
	  Send("J")
	  MouseMove($greendot[0], $greendot[1])
	  MsgBox(0, "now", "i will click this in 4s", 1)
	  Sleep(4000)
	  MouseClick("left", $greendot[0], $greendot[1])
	  Sleep(10000)
	  fight()
	  Sleep(4000)
	  Send("J")
   Until ($allstop==1)
EndFunc

Func getDominantColor($color)
   Local $red = BitShift($color, 16)
   Local $green = BitShift(BitAND($color, 0x00FF00), 8)
   Local $blue = BitAND($color, 0x0000FF)
   if ($red > $green And $red > $blue) Then
	  Return ("red")
   ElseIf ($green > $blue And $green > $red) Then
	  Return ("green")
   ElseIf ($blue > $red And $blue > $green) Then
	  Return ("blue")
   Else
	  if ($red > $green or $red > $blue) Then
		 Return ("red")
	  ElseIf ($green > $blue or $green > $red)  Then
		 Return ("green")
	  Else
		 Return ("blue")
	  EndIf
   EndIf
EndFunc

;Calibrate the bluestack window position
;@param $width the width of the screen to search
;@param $height the height of the screen to search
Func calibrateWindow($width=1366,$height=768)
   ;searching bluestack logo
   Local $repeat = 1
   Do
	  $icon = PixelSearch(0,0,1366,768, 0x79af1b);
	  if (@error) Then
		 MsgBox(0,"failed", "can't find bluestack window", 3)
	  Else
		 $find  = PixelSearch($icon[0]-8, $icon[1], $icon[0]+8, $icon[1]+10, 0xf6d502)
		 if (not(@error)) Then
			$find = PixelSearch($icon[0]-8,$icon[1], $icon[0]+8, $icon[1]+10, 0xdd3a17)
			if (not(@error)) Then
			   MouseClickDrag("left", $icon[0]+14, $icon[1], 30, 12)
			   $repeat = 0
			EndIf
		 EndIf
		 ;next color
	  EndIf

   Until ($repeat==0)
EndFunc

;perform check if we're stuck in a room (any current click affects nothing)
;return True if stuck, False if not
Func checkStuck()
   ; check if we're stuck in some room
   $samepixel = 0
   if (Not(PixelGetColor(100,100)==$screensave[0])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(400,100)==$screensave[1])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(700,100)==$screensave[2])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(100,500)==$screensave[3])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(498,298)==$screensave[4])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(700,500)==$screensave[5])) Then
	  Return False
   EndIf
   Return True
EndFunc

;update $screensave to current capture
Func updateCapture()
   $screensave[0] = PixelGetColor(100,100)
   if ($screensave[0]==0x2a1a4c) Then ;we don't want to save loading screen
	  $screensave[0] = 0
   EndIf
   $screensave[1] = PixelGetColor(400,100)
   if ($screensave[1]==0x201641) Then
	  $screensave[1] = 0
   EndIf
   $screensave[2] = PixelGetColor(700,100)
   if ($screensave[2]==0x580e2f) Then
	  $screensave[2] = 0
   EndIf
   $screensave[3] = PixelGetColor(100,500)
   if ($screensave[3]==0x2f1661) Then
	  $screensave[3] = 0
   EndIf
   $screensave[4] = PixelGetColor(498,298)
   if ($screensave[4]==0x014cbe) Then
	  $screensave[4] = 0
   EndIf
   $screensave[5] = PixelGetColor(700,500)
   if ($screensave[5]==0x7d1852) Then
	  $screensave[5] = 0
   EndIf
EndFunc

;Shift+alt
HotKeySet("+!a", "startArena")
HotKeySet("+!z", "changeArenaTier")
HotKeySet("+!s", "idle")
HotKeySet("+!d", "fight")
HotKeySet("+!f", "findMatch")
HotKeySet("+!g", "nextNode")
HotKeySet("+!p", "playthegame")
HotKeySet("+!c", "calibrateWindow")

;This indicates which arena tier shall be played, possible is 2, or 3
$arena_tier = 2
$arena_continue = 1
$allstop = 0
Do
   Sleep(1)
Until False

Func idle()
   $allstop = 1
   MsgBox(0, "now", "terminated", 1)
   Do
	  Sleep(1)
   Until False
EndFunc   ;==>Terminate

Func playthegame()
   MouseClick("left", 26, 750) ;window start menu
   MouseClick("left", 70, 400) ;bluestack app
   Sleep(90000)
   MsgBox(0, "now", "i will now move the bluestack window", 5)
   MouseClickDrag("left", 90, 30, 75, 15)
   Sleep(2000)
   MouseClick("left", 913, 307) ;click the game
   Sleep(60000)
   playthearena()
EndFunc
Func playthearena()
   MouseClick("left", 162, 51)
   Sleep(1000)
   MouseClick("left", 271, 135) ;fight button
   Sleep(20000)
   MouseClick("left", 535, 313) ;versus
   Sleep(20000)
   startArena()
EndFunc

Func changeArenaTier()
   if ($arena_tier==2) Then
	  $arena_tier = 3
	  MsgBox(0, "arena tier", "arena tier is now 3", 2)
   Else
	  $arena_tier = 2
	  MsgBox(0, "arena tier", "arena tier is now 2", 2)
   EndIf
EndFunc

;Starts the arena (Fight menu), and continue (tier *2)
Func startArena()
   $allstop = 0
   Do
	  Sleep(500)
	  MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
	  Sleep(1000)
	  if ($arena_tier==2) Then
		 ;Send("9")
		 MouseClick("left", 386, 446)
		 Sleep(5000)
		 MouseClick("left", 413, 522);double check
		 MouseClick("left", 433, 522);double check
	  Else
		 MouseClick("left", 830, 510)
		 Sleep(5000)
		 MouseClick("left", 760, 508);double check
	  EndIf
	  Sleep(5000)
	  Local $current_arena_tier  = $arena_tier
	  $arena_continue = 1
	  askForHelp()
	  if ($arena_continue==1) Then
		 ; We have energy, continue;else change arena tier in next loop
		 addToTeam()
		 findMatch()
		 fightArena()
	  EndIf

   Until ($allstop==1)
EndFunc

Func askForHelp()
   Local $carryon = 1
   Do
	  ;Detect if we can ask for help
	  Local $helpbutton = PixelGetColor(260, 175)
	  Local $red = BitShift($helpbutton, 16)
	  Local $green = BitShift(BitAND($helpbutton, 0x00FF00), 8)
	  Local $blue = BitAND($helpbutton, 0x0000FF)
	  if ($green > $red) Then
		 if ($green > $blue) Then
			Send("Q")
			Sleep(3000)
		 Else
			$carryon = 0
		 EndIf
	  Else
		 $carryon = 0
	  EndIf
   Until ($carryon==0)

   ;Detect if less than 3 champion has energy
   Local $redtag = PixelGetColor(630,188)
   Local $red = BitShift($redtag, 16)
   Local $green = BitShift(BitAND($redtag, 0x00FF00), 8)
   Local $blue = BitAND($redtag, 0x0000FF)
   if (($red-80) > $green) Then
	  if (($red-80) > $blue) Then
		 MsgBox(0, "Out of energy", "we're out of energy", 3)
		 $arena_continue = 0
		 Sleep(4000)
		 MouseClick("left", 57, 55)
		 if ($arena_tier==2) Then
			$arena_tier = 3
		 Else
			$arena_tier = 2
		 EndIf
		 Sleep(7000)
	  EndIf
   EndIf

   ;Detect if there are any Reconnect popup
   if (PixelGetColor(490,320)==0x2b2c30) Then
	  if (getDominantColor(PixelGetColor(490,350))=="green") Then
		 MsgBox(0, "popup", "I'll press the popup button in 5", 5)
		 Sleep(6000)
		 MouseClick("left", 490, 350)
		 Sleep(7000)
	  EndIf
   EndIf

   ;detect if we're in useless milestone info
   if (getDominantColor(PixelGetColor(934,555))=="green") Then
	  if ((PixelGetColor(492,337)==0x2b2c30)) Then
		 MsgBox(0, "milestone", "I assume we're in milestone info", 3)
		 Sleep(1000)
		 $arena_continue = 0
		 MouseClick("left", 57, 55)
		 Sleep(7000)
	  EndIf
   EndIf

EndFunc

;arena
Func addToTeam()
   MouseClickDrag("left", 319, 235, 145, 135)
   sleep(500)
   MouseClickDrag("left", 319, 235, 145, 210)
   sleep(500)
   MouseClickDrag("left", 319, 235, 145, 290)
   sleep(500)
EndFunc

;Arena
Func findMatch()
   Sleep(500)
   MouseClick("left", 109, 547)
   Sleep(4000)
   MouseClick("left", 687, 445)
   Sleep(3000)
   Send("0")
   Sleep(8000)
EndFunc

;Fight in arena
Func fightArena()
   $seq = 0
   $stop = 0
   $allstop = 0
   Do
	  Send("0")
	  Sleep(10);
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  $seq = $seq + 1
	  if ($seq>15) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf
	  if (getDominantColor(PixelGetColor(144,541))=="red") then
		 Send("{SPACE}")
	  EndIf

	  ;indicates fight has ended (loading screen)
	  $loading = PixelGetColor(640, 540);
	  if ($loading==0x025c00) Then
		 $loading = PixelGetColor(620, 300)
		 if ($loading==0x161a1b) Then
			$stop = 1
			MsgBox(0, "popup", "shall i press back button?", 2)
			Sleep(2000)
			MouseClick("left", 57, 55); back because we might ended up in 3* 4* tier arena
			Sleep(10000)
		 EndIf
	  EndIf

	  ;or chat bar has been clicked
	  if ($loading==0x161a1d) Then
		 if (PixelGetColor(136,540)==0x292c30) Then
			$stop = 1
			MsgBox(0,"chat", "this is chat window", 2)
			Sleep(1000)
			MouseClick("left", 943, 52); close
			Sleep(2000)
		 EndIf
	  EndIf

	  ; or the case if we ended up in view rewards
	  $loading = PixelGetColor(480,270)
	  if ($loading==0x2b2c30) Then
		 $loading = PixelGetColor(480,330)
		 if ($loading==0x2b2c30) Then
			$stop = 1
			Sleep(3000)
			MouseClick("left", 57, 55); back because we ended up in 3* 4* tier arena
			Sleep(10000)
		 EndIf
	  ElseIf ($loading==0x000000) Then
		 ; stuck in alliance quest window; todo alliance quest window with empty quest
		 if (PixelGetColor(838,366)==0x2b2c30) Then
			$stop = 1
			MsgBox(0,"alliance q", "alliance quest cuy", 2);
			$arena_tier = 2
			Sleep(2000)
			MouseClick("left", 57, 55);
			Sleep(10000)
		 EndIf
	  EndIf

	  ;stuck in alliance quest window
	  $loading = PixelGetColor(384,142)
	  if ($loading==0x1a1a1a) Then
		 if (PixelGetColor(551,142)==0x1a1a1a) Then
			if (Not(PixelGetColor(504,142)==0x1a1a1a)) Then
			   $stop = 1
			   MsgBox(0,"alliance q", "empty alliance quest cuy", 2);
			   $arena_tier = 2
			   Sleep(2000)
			   MouseClick("left", 57, 55);
			   Sleep(10000)
			EndIf
		 EndIf
	  EndIf

	  ; or the case we stuck in team adding
	  if (PixelGetColor(18, 130)==0x2b2c30) Then ; the left bar team list
		 if (PixelGetColor(936,511)==0x2b2c30) Then ;the champion filter button
			$stop = 1
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(10000)
		 EndIf
	  EndIf
   Until ($stop==1 or $allstop==1)
EndFunc

;FIGHT In quest
Func fight()
   $seq = 0
   $stop = 0
   $allstop = 0
   Do
	  Send("0")
	  Sleep(30);
	  $seq = $seq + 1
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  if ($seq>12) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf

	  if (Mod($seq,2)==0) Then
		 $loading = PixelGetColor(958, 577);
		 if ($loading==0x1d2630) Then
		 ;indicates fight has ended
			$loading = PixelGetColor(923, 491)
			if ($loading==0xc1c1c2) Then
			   $stop = 1
			   Sleep(3000)
			   Send("J")
			EndIf
		 ElseIf ($loading==0x07090c) Then
			if (PixelGetColor(825,105)==0x2b2c30) Then
			   $stop = 1
			   Sleep(3000)
			   Send("J")
			EndIf
		 ;Elseif (PixelGetColor(486,310)==0xeeeeee) Then
			;we're in loading  screen
			;$stop = 1
			;Sleep(3000)
			;Send("J")
		 EndIf
	  EndIf
   Until ($stop==1 or $allstop==1)
EndFunc

Func nextNode()
   $allstop = 0
   Do
	  Local $step = 0
	  Do
		 $step = $step + 1
		 if ($step == 10) Then
			MouseClickDrag("left", 450, 320, 642, 346)
		 ElseIf ($step == 20) Then
			MouseClickDrag("left", 450, 320, 200, 200)
			MouseClickDrag("left", 450, 320, 300, 300)
		 ElseIf ($step == 30) Then
			MouseClickDrag("left", 700, 100, 100, 400)
		 ElseIf ($step == 40) Then
			MouseClickDrag("left", 100, 400, 700, 100)
			MouseClickDrag("left", 100, 400, 700, 100)
			$step = 0
		 EndIf
		 Send("J")
		 Sleep(200)
		 $greendot = PixelSearch(80,100, 957, 530, 0x00f800)
		 if (@error) Then
			$greendot = PixelSearch(80,100, 957, 530, 0x00e400)
		 EndIf
	  Until not(@error)
	  Send("J")
	  MouseMove($greendot[0], $greendot[1])
	  MsgBox(0, "now", "i will click this in 4s", 1)
	  Sleep(4000)
	  MouseClick("left", $greendot[0], $greendot[1])
	  Sleep(10000)
	  fight()
	  Sleep(4000)
	  Send("J")
   Until ($allstop==1)
EndFunc

Func getDominantColor($color)
   Local $red = BitShift($color, 16)
   Local $green = BitShift(BitAND($color, 0x00FF00), 8)
   Local $blue = BitAND($color, 0x0000FF)
   if ($red > $green And $red > $blue) Then
	  Return ("red")
   ElseIf ($green > $blue And $green > $red) Then
	  Return ("green")
   ElseIf ($blue > $red And $blue > $green) Then
	  Return ("blue")
   Else
	  if ($red > $green or $red > $blue) Then
		 Return ("red")
	  ElseIf ($green > $blue or $green > $red)  Then
		 Return ("green")
	  Else
		 Return ("blue")
	  EndIf
   EndIf
EndFunc

;Calibrate the bluestack window position
;@param $width the width of the screen to search
;@param $height the height of the screen to search
Func calibrateWindow($width=1366,$height=768)
   ;searching bluestack logo
   Local $repeat = 1
   Do
	  $icon = PixelSearch(0,0,1366,768, 0x79af1b);
	  if (@error) Then
		 MsgBox(0,"failed", "can't find bluestack window", 3)
	  Else
		 $find  = PixelSearch($icon[0]-8, $icon[1], $icon[0]+8, $icon[1]+10, 0xf6d502)
		 if (not(@error)) Then
			$find = PixelSearch($icon[0]-8,$icon[1], $icon[0]+8, $icon[1]+10, 0xdd3a17)
			if (not(@error)) Then
			   MouseClickDrag("left", $icon[0]+14, $icon[1], 30, 12)
			   $repeat = 0
			EndIf
		 EndIf
		 ;next color
	  EndIf

   Until ($repeat==0)
EndFunc


Update lightalloy.au3

Update lightalloy.au3

3 seconds should be enough

# Written and tested for installer v4.9.2

#region --- Internal functions Au3Recorder Start ---

Func _Au3RecordSetup()
	Opt('WinWaitDelay',100)
	Opt('WinDetectHiddenText',1)
	Opt('MouseCoordMode',0)
EndFunc

Func _WinWaitActivate($title,$text,$timeout=0)
	WinWait($title,$text,$timeout)
	If Not WinActive($title,$text) Then WinActivate($title,$text)
	WinWaitActive($title,$text,$timeout)
EndFunc

_AU3RecordSetup()

#endregion --- Internal functions Au3Recorder End ---

Run($CmdLine[1])

# Deactivate 'open website', 'associate player with video files', and 'add desktop icon'
# Title:	"Light Alloy installer"
# Text:		"Visit Light Alloy"
_WinWaitActivate("[CLASS:TMainForm]", "", 2)
Send("{SPACE}{SHIFTDOWN}{TAB}{SHIFTUP}{SPACE}{SHIFTDOWN}{TAB}{TAB}{SHIFTUP}{SPACE}{ENTER}")

# Choose to use internal codecs (recommended)
# Title:	"Basic options"
# Text:		"What kind of codecs"
_WinWaitActivate("[CLASS:LightAlloyFront.UnicodeClass]", "", 3)
Send("{TAB}{TAB}{TAB}{ENTER}")

# Player auto-starts - shutdown
# Title:	"Light Alloy"
_WinWaitActivate("[CLASS:LightAlloyFront]", "", 1)
Send("{ALTDOWN}{F4}{ALTUP}")

Exit

# Written and tested for installer v4.9.2

#region --- Internal functions Au3Recorder Start ---

Func _Au3RecordSetup()
	Opt('WinWaitDelay',100)
	Opt('WinDetectHiddenText',1)
	Opt('MouseCoordMode',0)
EndFunc

Func _WinWaitActivate($title,$text,$timeout=0)
	WinWait($title,$text,$timeout)
	If Not WinActive($title,$text) Then WinActivate($title,$text)
	WinWaitActive($title,$text,$timeout)
EndFunc

_AU3RecordSetup()

#endregion --- Internal functions Au3Recorder End ---

Run($CmdLine[1])

# Deactivate 'open website', 'associate player with video files', and 'add desktop icon'
# Title:	"Light Alloy installer"
# Text:		"Visit Light Alloy"
_WinWaitActivate("[CLASS:TMainForm]", "", 2)
Send("{SPACE}{SHIFTDOWN}{TAB}{SHIFTUP}{SPACE}{SHIFTDOWN}{TAB}{TAB}{SHIFTUP}{SPACE}{ENTER}")

# Choose to use internal codecs (recommended)
# Title:	"Basic options"
# Text:		"What kind of codecs"
_WinWaitActivate("[CLASS:LightAlloyFront.UnicodeClass]", "", 6)
Send("{TAB}{TAB}{TAB}{ENTER}")

# Player auto-starts - shutdown
# Title:	"Light Alloy"
_WinWaitActivate("[CLASS:LightAlloyFront]", "", 2)
Send("{ALTDOWN}{F4}{ALTUP}")

Exit