Added tons of comments. Simplified main Switch logic. Modified logic for determining IP address of server, should work on MCP 1.0 and MCP 2.0 servers.

#pragma compile(Console, true)
; Change this to 'false' to build a 32-bit binary
#pragma compile(x64, true)
#pragma compile(UPX, true)
' The name of the binary to generate
#pragma compile(Out, cloudconfig.exe)
; The icon to use as the progrma icon (gets jammed into binary)
#pragma compile(Icon, Bogo-D-Project-Disk-iDisk.ico)
; Icon courtesy http://bogo-d.deviantart.com
; Ownership info
#pragma compile(CompanyName, 'Dimension Data')
#pragma compile(FileDescription, 'Cloud Config Service')
#pragma compile(Comments, 'Cloud Config Service')
#pragma compile(FileVersion, 1.3.1.2)
#pragma compile(InternalName, 'CloudConfig')
#pragma compile(LegalCopyright, 'Copyright 2015 Dimension Data')

; We don't need no stinkin' trayicon!
#NoTrayIcon
; Since we will be modifying the system, we need Admin
#RequireAdmin

; Our logging routines
#include "Log.au3"
#include "Misc.au3"
; Routines for interfacing with Service Manager
#include "Services.au3"
#include "StringConstants.au3"
#include <FileConstants.au3>
#include <EventLog.au3>

; Our constants and variables
; The service name(s)
Global Const $sServiceName = "CloudConfig"
Global Const $sServiceDisplayName = "CloudConfig"
; The directory we expect to find our config file and other sundries
Global Const $prepDir = 'C:\CloudConfigService'
; The config file for the service
Global Const $configFile = $prepDir & '\CloudConfig.ini'
; We extract the command from the config file and jam it in this variable
Global $command = ''
; This is the number of boots the system has performed (as extracted from
; the config file)
Global $rebootcount = 0

; constants for Event log
Global Const $WE_SUCCESS = 0
Global Const $WE_ERROR = 1
Global Const $WE_WARNING = 2
Global Const $WE_INFORMATION = 4
Global Const $WE_SUCCESSAUDIT = 8
Global Const $WE_FAILUREAUDIT = 16

; The CCS_BOOT_COUNT is used to determine when to fire off the customization
; For Priced Software images on the Dimension Data Cloud, the value needs to be
; 2. For 3rd parties making images that can be imported into the Cloud, the value
; needs to be 3 to account for the extra boot that occurs when the image is initially
; imported into the platform.
;
; Uncomment to build for a Priced Software image
;Global Const $CCS_BOOT_COUNT = 2
; Uncomment to build a 3rd party image
Global Const $CCS_BOOT_COUNT = 3

; for future feature expansion, not currently used
Global $pingHost = '256.0.0.1' ; yes, it's an illegal IP. this is by design
Global $sleepyTime = 5000 ; Ping timeout, in milliseconds
Global $oldHostname = ''

If Not @Compiled Then Exit
If Not _Singleton(@ScriptName, 1) Then
   If $cmdline[0] > 0 Then
	  If $cmdline[1] = "finish" Then
		 WriteLog("Removing service.")
		 RemoveService()
	  Else
		 WriteLog("Unrecognized command. Terminating due to multiple instances.")
	  EndIf
	  Exit
   EndIf
   WriteLog("Multiple instances running. Terminating.")
   Exit
EndIf

If $cmdline[0] > 0 Then
	Switch $cmdline[1]
		Case "install", "-i", "/i"
			InstallService()
		Case "remove", "-u", "/u", "uninstall"
			RemoveService()
		Case "run", "-r", "/r", "start"
			_SelfRun($sServiceName, "start")
		Case "stop", "-s", "/s"
			_SelfRun($sServiceName, "stop")
		Case Else
			;WriteLog(" - - - Help - - - " & @crlf)
			;WriteLog(" Service Example Params : " & @crlf)
			;WriteLog("  -i : Installs service" & @crlf)
			;WriteLog("  -u : Removes service" & @crlf)
			;WriteLog("  -r : Runs the service" & @crlf)
			;WriteLog("  -s : Stops the service" & @crlf)
			;WriteLog(" - - - - - - - - " & @crlf)
			Exit
	EndSwitch
Else
	If Not _Service_Exists($sServiceName) Then
		If MsgBox(20, "Service Not Installed.", "Would you like to install this service?" & @CRLF & $sServiceName) = 6 Then
			If InstallService() Then
				If MsgBox(4, $sServiceName, "Service Installed Successfully." & @CRLF & "Do you wish to start the process?") = 6 Then _SelfRun($sServiceName, "start")
			EndIf
		Else
			Exit
		EndIf
	EndIf
EndIf

_Service_Init($sServiceName)
Exit

Func _main($iArg, $sArgs)

   Local $hostNameChanged = False

   If Not _Service_ReportStatus($SERVICE_RUNNING, $NO_ERROR, 0) Then
	  WriteLog("Error sending running status, exiting")
	  _Service_ReportStatus($SERVICE_STOPPED, _WinAPI_GetLastError(), 0)
	Exit
   EndIf

   If Not FileExists($configFile) Then
	  ; if we don't have our config file, we abort all operations
	  WriteLog('No config file present. Aborting.')
	  WriteEventLog($WE_ERROR, 'No config file present.')
	  _Service_ReportStatus($SERVICE_STOPPED, _WinAPI_GetLastError(), 0)
	Exit
   EndIf

   Local $bServiceRunning = True ; REQUIRED

   ; how many reboots have we performed?
   Local $rebootcount = readConfig('stage')
   ; what do we run?
   Local $command = readConfig('execution')
   ; how long do we pause before launching our script?
   Local $launchDelay = Int(readConfig('delay'))
   ; do we reboot?
   Local $reboot = readConfig('reboot')

   ; we only use a while loop so we can easily break out of the switch statement
   While $bServiceRunning

   Switch ($rebootcount)
	  Case $CCS_BOOT_COUNT
		 ; launch the cmd script
		 WriteLog('Deployment stage: ' & $rebootcount)
		 writeConfig('stage', $rebootcount + 1) ; update to push it past our allowed value

		 ; finally, launch our customization script, if provided
		 If $command <> '' Then
			If FileExists($command) Then
			   Sleep($launchDelay)  ; pause
			   WriteLog('Launching "' & $command & '" ...')
			   ; Run the command and wait for it to finish
			   Run(@ComSpec & " /c " & $command, "", @SW_HIDE)
			Else
			   WriteLog('The supplied action, "' & $command & '" could not be found or accessed.')
			EndIf
		 EndIf

		; The command ran, do we reboot?
		 If $reboot Then
			; we need to force a reboot
			WriteLog('Forcing system reboot.')
			WriteEventLog($WE_INFORMATION, 'Rebooting system.')
			Shutdown(BitOR($SD_REBOOT, $SD_FORCE))
		 EndIf

		 ; we're done, so signal end
		 $bServiceRunning = False

	  Case Else
		 writeConfig('stage', $rebootcount + 1) ; update the reboot count
		 $bServiceRunning = False
   EndSwitch

   WEnd

   _Service_ReportStatus($SERVICE_STOP_PENDING, $NO_ERROR, 1000)
   WriteLog("Stopping service.")
   _Service_Stop($sServiceName)

   _Service_ReportStatus($SERVICE_STOPPED, $NO_ERROR, 0)

EndFunc   ;==>_Svc_Main

Func InstallService()

;~ 	Check for Adminstrativee rights
	If Not (IsAdmin()) Then
		MsgBox(0, $sServiceName, "You must have administrative rights to install this as a service.")
		;WriteLog("Admin rights needed, will exit now")
		Exit
	EndIf

	;WriteLog("Installing Service, Please Wait" & @CRLF)
	FileCopy(@ScriptName, @SystemDir & '\' & @ScriptName, 1)
	_Service_Create($sServiceName, $sServiceDisplayName, $SERVICE_WIN32_OWN_PROCESS, $SERVICE_AUTO_START, $SERVICE_ERROR_SEVERE, '"' & @SystemDir & '\' & @ScriptName & '"')

	If @error Then
		WriteLog("Problem Installing Service, Error number is " & @error & @CRLF & " message  : " & _WinAPI_GetLastErrorMessage())
		Return 0
	Else
		WriteLog("Installation of Service Successful.")
	EndIf

	Return 1
	Exit
EndFunc   ;==>InstallService

Func RemoveService()
	_Service_Stop($sServiceName)
	Sleep(30000) ; pause for 30 seconds
	_Service_Delete($sServiceName)
	If Not @error Then WriteLog("Service Removed Successfully" & @CRLF)
	Exit
EndFunc   ;==>RemoveService

Func _exit()
	_Service_ReportStatus($SERVICE_STOPPED, $NO_ERROR, 0);
EndFunc   ;==>_exit

Func _Stopping()
	_Service_ReportStatus($SERVICE_STOP_PENDING, $NO_ERROR, 3000)
EndFunc   ;==>_Stopping

Func _SelfRun($servicename, $action)
	Local $sCmdFile = 'sc ' & $action & ' "' & $servicename & '"'
	Run($sCmdFile, @TempDir, @SW_HIDE)
	Exit
EndFunc   ;==>_SelfRun

Func writeConfig($section, $other)
	Switch ($section)
		Case 'stage'
			IniWrite($configFile, "deployment stage", "state", $other)
	EndSwitch
EndFunc   ;==>writeConfig

Func readConfig($section)
   Local $value = ''
	Switch ($section)
	  Case 'stage'
		 $value = IniRead($configFile, "deployment stage", "state", 0)
	  Case 'execution'
		 $value = IniRead($configFile, "deployment execution", "action", "")
	  Case 'delay'
		 $value = IniRead($configFile, "deployment execution", "delay", 60000) ; default to 1 minute
	  Case 'reboot'
		 $value = IniRead($configFile, "deployment execution", "forcereboot", "FALSE") ; default to no reboot
		 ; normalize $value into a boolean
		 If $value = 'true' Or $value = 'True' Or $value = 'TRUE' Or $value = 1 Or $value = 'yes' Or $value = 'Yes' Or $value = 'YES' Then
			; to simplify, only check for values that cause a reboot
			$value = True
		 Else
			; all other values are considered False
			$value = False
		 EndIf
	EndSwitch
	Return $value
EndFunc   ;==>readConfig

Func WriteEventLog($severity, $message)
   Local $hEventLog, $aData[1] = [0]
   Local $eventMessage = $sServiceName & ': ' & $message
   $hEventLog = _EventLog__Open("", "Application")
   _EventLog__Report($hEventLog, $severity, 0, 2, "", $eventMessage, $aData)
   _EventLog__Close($hEventLog)
EndFunc

; Check the hostname of the system and compare it with a defined value
Func checkHostname($expected)
   ; Update our view of environment variables
   EnvUpdate()
   ; get our current hostname
   Local $compName = @ComputerName
   ; check to see if it matches what we expect
   Local $return = StringCompare($compName, $expected, $STR_NOCASESENSE)
   If  $return = 0 Then
	  Return True
   Else
	  Return False
   EndIf
EndFunc   ;==>checkHostname

; not currently used
Func checkNetwork()
	Local $return = Ping($pingHost, $sleepyTime)
	If $return > 0 Then
		; network is alive
		writeConfig('network', '')
	EndIf
 EndFunc   ;==>checkNetwork

Func getIP()
   ; On the Dimension Data Cloud, all servers are assigned an RFC1918 address on
   ; all NICs. For MCP 1.0 locations, this will always be in the 10.0.0.0/8 space. For
   ; MCP 2.0 locations, it can be in any of the RFC1918 space, 10.0.0.0/8,
   ; 192.168.0.0/16 or 172.16.0.0/12. Our job is to try to determine what this IP is.
   ; In addition, you cannot assign a public IPv4 address directly to a server. You must
   ; always use NAT or VIPs.
   ; There are 4 macros that may contain the IP of the system.

   ; first, create an array using the macros (because AutoIT doesn't have variable interpolation
   Local $ipArray[4]
   $ipArray[0] = @IPAddress1
   $ipArray[1] = @IPAddress2
   $ipArray[2] = @IPAddress3
   $ipArray[3] = @IPAddress4

   Local $ip3 = ''

   ; now loop over the array
   For $ip In $ipArray
	  ; start evaluating the IP
	  $ip3 = StringLeft($ip, 3)
	  If $ip3 = '10.' Or $ip3 = '192' Or $ip3 = 172' Then
		 ; We stop at the first one we find, regardless of how many there may be
		 Return $ip
	  EndIf
   Next

   ; apparently, we didn't find any private addresses, so return "false"
   Return 0

EndFunc

Func updateHostsFile($ipAddress, $hostName)
   ; Update the hosts file with the IP and hostname we require
   Local $file = @SystemDir & "\drivers\etc\hosts"

   Local $fileHandle = FileOpen($file, $FO_OVERWRITE) ;; OVERWRITE existing file!!
   If $fileHandle = -1 Then
	  Return False
   EndIf
   Local $hostLine = '# Hosts file updated by Cloud Config Service' & @CRLF & $ipAddress & @TAB & $hostName & @CRLF
   Local $result = FileWriteLine($fileHandle, $hostLine)
   If $result = 0 Then
	  Return False
   EndIf
   FileClose($fileHandle)
   Return True
EndFunc

Func getVolGUID($volLabel)
   ;; this function iterates over the mounted drives to figure out what
   ;; the volume label is. It does this without regard to drive letter

   ;; get all drives
   Local $drives = DriveGetDrive("FIXED")

   ; Loop over the array holding the drive letters
   For $i = 1 To $drives[0]
	  ; get drive letter and uppercase it
	  Local $currentDrive = StringUpper($drives[$i])
	  ; get this drive's label and uppercase it
	  Local $currentLabel = StringUpper(DriveGetLabel($currentDrive))

	  If $currentLabel = $volLabel Then
		 ;; found it, grab the GUID
		 Local $volGUID = extractVolGUID($currentDrive)
		 Return $volGUID
	  EndIf
   Next

   Return False
EndFunc

Func extractVolGUID($drive)
   ;; get the GUID of the drive
   $drive = $drive & '\' ;; make sure there's a path. a double \\ doesn't hinder execution
   Local $iPID = Run(@ComSpec & ' /C mountvol.exe ' & $drive & ' /L', "", @SW_HIDE, $STDOUT_CHILD)
   ProcessWaitClose($iPID)
   Local $sOutput = StdoutRead($iPID)
   Local $volGUID = StringStripWS($sOutput, $STR_STRIPALL)

   Return $volGUID
EndFunc

#pragma compile(Console, true)
#pragma compile(x64, true)
#pragma compile(UPX, true)
#pragma compile(Out, cloudconfig.exe)
#pragma compile(Icon, Bogo-D-Project-Disk-iDisk.ico)
; Icon courtesy http://bogo-d.deviantart.com
#pragma compile(CompanyName, 'Dimension Data')
#pragma compile(FileDescription, 'Cloud Config Service')
#pragma compile(Comments, 'Cloud Config Service')
#pragma compile(FileVersion, 1.3.1.2)
#pragma compile(InternalName, 'CloudConfig')
#pragma compile(LegalCopyright, 'Copyright 2015 Dimension Data')

#NoTrayIcon
#RequireAdmin

#include "Log.au3"
#include "Misc.au3"
#include "Services.au3"
#include "StringConstants.au3"
#include <FileConstants.au3>
#include <EventLog.au3>

Global $sServiceName = "CloudConfig"
Global $sServiceDisplayName = "CloudConfig"
Global $prepDir = 'C:\CloudConfigService'
Global $configFile = $prepDir & '\CloudConfig.ini'
Global $command = ''
Global $rebootcount = 0

; constants for Event log
Global Const $WE_SUCCESS = 0
Global Const $WE_ERROR = 1
Global Const $WE_WARNING = 2
Global Const $WE_INFORMATION = 4
Global Const $WE_SUCCESSAUDIT = 8
Global Const $WE_FAILUREAUDIT = 16

; for future feature expansion, not currently used
Global $pingHost = '256.0.0.1' ; yes, it's an illegal IP. this is by design
Global $sleepyTime = 5000 ; Ping timeout, in milliseconds
Global $oldHostname = ''

If Not @Compiled Then Exit
If Not _Singleton(@ScriptName, 1) Then
   If $cmdline[0] > 0 Then
	  If $cmdline[1] = "finish" Then
		 WriteLog("Removing service.")
		 RemoveService()
	  Else
		 WriteLog("Unrecognized command. Terminating due to multiple instances.")
	  EndIf
	  Exit
   EndIf
   ;MsgBox(0, $sServiceName, "Process is running.")
   WriteLog("Multiple instances running. Terminating.")
   Exit
EndIf

If $cmdline[0] > 0 Then
	Switch $cmdline[1]
		Case "install", "-i", "/i"
			InstallService()
		Case "remove", "-u", "/u", "uninstall"
			RemoveService()
		Case "run", "-r", "/r", "start"
			_SelfRun($sServiceName, "start")
		Case "stop", "-s", "/s"
			_SelfRun($sServiceName, "stop")
		Case Else
			;WriteLog(" - - - Help - - - " & @crlf)
			;WriteLog(" Service Example Params : " & @crlf)
			;WriteLog("  -i : Installs service" & @crlf)
			;WriteLog("  -u : Removes service" & @crlf)
			;WriteLog("  -r : Runs the service" & @crlf)
			;WriteLog("  -s : Stops the service" & @crlf)
			;WriteLog(" - - - - - - - - " & @crlf)
			Exit
	EndSwitch
Else
	If Not _Service_Exists($sServiceName) Then
		If MsgBox(20, "Service Not Installed.", "Would you like to install this service?" & @CRLF & $sServiceName) = 6 Then
			If InstallService() Then
				If MsgBox(4, $sServiceName, "Service Installed Successfully." & @CRLF & "Do you wish to start the process?") = 6 Then _SelfRun($sServiceName, "start")
			EndIf
		Else
			Exit
		EndIf
	EndIf
EndIf

_Service_Init($sServiceName)
Exit

Func _main($iArg, $sArgs)

   Local $hostNameChanged = False

   If Not _Service_ReportStatus($SERVICE_RUNNING, $NO_ERROR, 0) Then
	  WriteLog("Error sending running status, exiting")
	  _Service_ReportStatus($SERVICE_STOPPED, _WinAPI_GetLastError(), 0)
	Exit
   EndIf

   If Not FileExists($configFile) Then
	  ; if we don't have our config file, we abort all operations
	  WriteLog('No config file present. Aborting.')
	  WriteEventLog($WE_ERROR, 'No config file present.')
	  _Service_ReportStatus($SERVICE_STOPPED, _WinAPI_GetLastError(), 0)
	Exit
   EndIf

   Local $bServiceRunning = True ; REQUIRED

   ; how many reboots have we performed?
   Local $rebootcount = readConfig('stage')
   ; what do we run?
   Local $command = readConfig('execution')
   ; how long do we pause before launching our script?
   Local $launchDelay = Int(readConfig('delay'))
   ; do we reboot?
   Local $reboot = readConfig('reboot')

   ; we only use a while loop so we can easily break out of the switch statement
   While $bServiceRunning

   Switch ($rebootcount)
	  Case 0
		 ; do nothing
		 WriteLog('Deployment stage: ' & $rebootcount)
		 writeConfig('stage', $rebootcount + 1) ; update the reboot count
		 $bServiceRunning = False
	  Case 1
		 ; do nothing
		 WriteLog('Deployment stage: ' & $rebootcount)
		 writeConfig('stage', $rebootcount + 1) ; update the reboot count
		 $bServiceRunning = False
	  Case 2
		 ; launch the cmd script
		 WriteLog('Deployment stage: ' & $rebootcount)
		 writeConfig('stage', $rebootcount + 1) ; update to push it past our allowed value

		 Sleep($launchDelay) ; pause first

		 ; finally, launch our customization script, if provided
		 If $command <> '' Then
			If FileExists($command) Then
			   Sleep($launchDelay)  ; pause
			   WriteLog('Launching "' & $command & '" ...')
			   Run(@ComSpec & " /c " & $command, "", @SW_HIDE)
			Else
			   WriteLog('The supplied action, "' & $command & '" could not be found or accessed.')
			EndIf
		 EndIf

		 If $reboot Then
			; we need to force a reboot
			WriteLog('Forcing system reboot.')
			WriteEventLog($WE_INFORMATION, 'Rebooting system.')
			Shutdown(BitOR($SD_REBOOT, $SD_FORCE))
		 EndIf

		 ; we're done, so signal end
		 $bServiceRunning = False

	  Case Else
		 ; we don't run past 3 reboots
		 $bServiceRunning = False
   EndSwitch

   WEnd

   _Service_ReportStatus($SERVICE_STOP_PENDING, $NO_ERROR, 1000)
   WriteLog("Stopping service.")
   _Service_Stop($sServiceName)

   _Service_ReportStatus($SERVICE_STOPPED, $NO_ERROR, 0)

EndFunc   ;==>_Svc_Main

Func InstallService()

;~ 	Check for Adminstrativee rights
	If Not (IsAdmin()) Then
		MsgBox(0, $sServiceName, "You must have administrative rights to install this as a service.")
		;WriteLog("Admin rights needed, will exit now")
		Exit
	EndIf

	;WriteLog("Installing Service, Please Wait" & @CRLF)
	_Service_Create($sServiceName, $sServiceDisplayName, $SERVICE_WIN32_OWN_PROCESS, $SERVICE_AUTO_START, $SERVICE_ERROR_SEVERE, '"' & @SystemDir & '\' & @ScriptName & '"')

	If @error Then
		WriteLog("Problem Installing Service, Error number is " & @error & @CRLF & " message  : " & _WinAPI_GetLastErrorMessage())
		Return 0
	Else
		WriteLog("Installation of Service Successful.")
	EndIf

	FileCopy(@ScriptName, @SystemDir & '\' & @ScriptName, 1)

	Return 1
	Exit
EndFunc   ;==>InstallService

Func RemoveService()
	_Service_Stop($sServiceName)
	_Service_Delete($sServiceName)
	If Not @error Then WriteLog("Service Removed Successfully" & @CRLF)
	Exit
EndFunc   ;==>RemoveService

Func _exit()
	_Service_ReportStatus($SERVICE_STOPPED, $NO_ERROR, 0);
EndFunc   ;==>_exit

Func _Stopping()
	_Service_ReportStatus($SERVICE_STOP_PENDING, $NO_ERROR, 3000)
EndFunc   ;==>_Stopping

Func _SelfRun($servicename, $action)
	Local $sCmdFile = 'sc ' & $action & ' "' & $servicename & '"'
	Run($sCmdFile, @TempDir, @SW_HIDE)
	Exit
EndFunc   ;==>_SelfRun

Func writeConfig($section, $other)
	Switch ($section)
		Case 'stage'
			IniWrite($configFile, "deployment stage", "state", $other)
	EndSwitch
EndFunc   ;==>writeConfig

Func readConfig($section)
   Local $value = ''
	Switch ($section)
	  Case 'stage'
		 $value = IniRead($configFile, "deployment stage", "state", 0)
	  Case 'execution'
		 $value = IniRead($configFile, "deployment execution", "action", "")
	  Case 'delay'
		 $value = IniRead($configFile, "deployment execution", "delay", 60000) ; default to 1 minute
	  Case 'reboot'
		 $value = IniRead($configFile, "deployment execution", "forcereboot", "FALSE") ; default to no reboot
		 ; normalize $value into a boolean
		 If $value = 'true' Or $value = 'True' Or $value = 'TRUE' Or $value = 1 Or $value = 'yes' Or $value = 'Yes' Or $value = 'YES' Then
			; to simplify, only check for values that cause a reboot
			$value = True
		 Else
			; all other values are considered False
			$value = False
		 EndIf
	EndSwitch
	Return $value
EndFunc   ;==>readConfig

Func WriteEventLog($severity, $message)
   Local $hEventLog, $aData[1] = [0]
   Local $eventMessage = $sServiceName & ': ' & $message
   $hEventLog = _EventLog__Open("", "Application")
   _EventLog__Report($hEventLog, $severity, 0, 2, "", $eventMessage, $aData)
   _EventLog__Close($hEventLog)
EndFunc

; Check the hostname of the system and compare it with a defined value
Func checkHostname($expected)
   ; Update our view of environment variables
   EnvUpdate()
   ; get our current hostname
   Local $compName = @ComputerName
   ; check to see if it matches what we expect
   Local $return = StringCompare($compName, $expected, $STR_NOCASESENSE)
   If  $return = 0 Then
	  Return True
   Else
	  Return False
   EndIf
EndFunc   ;==>checkHostname

; not currently used
Func checkNetwork()
	Local $return = Ping($pingHost, $sleepyTime)
	If $return > 0 Then
		; network is alive
		writeConfig('network', '')
	EndIf
 EndFunc   ;==>checkNetwork

Func getIP()
   ; try to determine the IP of this system (10.0.0.0/8 subnet only)
   ; there are 4 macros that may contain the IP of the system

   ; first, create an array using the macros (because AutoIT doesn't have variable interpolation
   Local $ipArray[4]
   $ipArray[0] = @IPAddress1
   $ipArray[1] = @IPAddress2
   $ipArray[2] = @IPAddress3
   $ipArray[3] = @IPAddress4

   Local $ip3 = ''

   ; now loop over the array
   For $ip In $ipArray
	  ; start evaluating the IP
	  $ip3 = StringLeft($ip, 3)
	  If $ip3 = '10.' Then
		 ; We stop at the first one we find, regardless of how many there may be
		 Return $ip
	  EndIf
   Next

   ; apparently, we didn't find any 10. addresses, so return "false"
   Return 0

EndFunc

Func updateHostsFile($ipAddress, $hostName)
   ; Update the hosts file with the IP and hostname we require
   Local $file = @SystemDir & "\drivers\etc\hosts"

   Local $fileHandle = FileOpen($file, $FO_OVERWRITE) ;; OVERWRITE existing file!!
   If $fileHandle = -1 Then
	  Return False
   EndIf
   Local $hostLine = '# Hosts file updated by Cloud Config Service' & @CRLF & $ipAddress & @TAB & $hostName & @CRLF
   Local $result = FileWriteLine($fileHandle, $hostLine)
   If $result = 0 Then
	  Return False
   EndIf
   FileClose($fileHandle)
   Return True
EndFunc

Func getVolGUID($volLabel)
   ;; this function iterates over the mounted drives to figure out what
   ;; the volume label is. It does this without regard to drive letter

   ;; get all drives
   Local $drives = DriveGetDrive("FIXED")

   ; Loop over the array holding the drive letters
   For $i = 1 To $drives[0]
	  ; get drive letter and uppercase it
	  Local $currentDrive = StringUpper($drives[$i])
	  ; get this drive's label and uppercase it
	  Local $currentLabel = StringUpper(DriveGetLabel($currentDrive))

	  If $currentLabel = $volLabel Then
		 ;; found it, grab the GUID
		 Local $volGUID = extractVolGUID($currentDrive)
		 Return $volGUID
	  EndIf
   Next

   Return False
EndFunc

Func extractVolGUID($drive)

   $drive = $drive & '\' ;; make sure there's a path. a double \\ doesn't hinder execution
   Local $iPID = Run(@ComSpec & ' /C mountvol.exe ' & $drive & ' /L', "", @SW_HIDE, $STDOUT_CHILD)
   ProcessWaitClose($iPID)
   Local $sOutput = StdoutRead($iPID)
   Local $volGUID = StringStripWS($sOutput, $STR_STRIPALL)

   Return $volGUID
EndFunc


set timeout to allow it to init

set timeout to allow it to init

#include <src/clashbot.au3>

loadClashBotApp()
botStart()

Sleep(2000)

If isClashBotRunning() AND isLoggedIn() AND isStarted() Then
    ConsoleWrite('true' & @CRLF)
Else
    ConsoleWrite('false' & @CRLF)
EndIf

#include <src/clashbot.au3>

loadClashBotApp()
botStart()

If isClashBotRunning() AND isLoggedIn() AND isStarted() Then
    ConsoleWrite('true' & @CRLF)
Else
    ConsoleWrite('false' & @CRLF)
EndIf


Made compatible with 2.6 Python.

Made compatible with 2.6 Python.

--HG--
extra : convert_revision : svn%3A79c32731-664e-0410-8185-e51b9e89f9fb/trunk%401089

;;  Copyright 2008 Nokia Siemens Networks Oyj
;;
;;  Licensed under the Apache License, Version 2.0 (the "License");
;;  you may not use this file except in compliance with the License.
;;  You may obtain a copy of the License at
;;
;;      http://www.apache.org/licenses/LICENSE-2.0
;;
;;  Unless required by applicable law or agreed to in writing, software
;;  distributed under the License is distributed on an "AS IS" BASIS,
;;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;  See the License for the specific language governing permissions and
;;  limitations under the License.

;; Robot Framework One Click Installer for Windows
;;
;; This installer installs Robot Framework and its preconditions Python and
;; Jython (optional). If installer is executed without arguments, it opens a
;; dialog explaining the options and asking the user to enter the installation
;; directory. If a command line options is given, it must be a path to an
;; existing directory and it is used as installation directory.
;;
;; For more information about this script see $USAGE below. To learn more
;; about silent Python installation, see url [1]. Silent Jython installation
;; options can be seen with command [2].
;;
;; [1] http://www.python.org/download/releases/2.5/msi/#automated
;; [2] java -jar jython_installer-2.2.x.jar --help

;;
;; Config
;;

; Expected patterns for installer names and target directory names.
$PYTHON_DIR_NAME = "Python"
$JYTHON_DIR_NAME = "Jython"
$PYTHON_PATTERN = "python-2.*.msi"
$ROBOT_PATTERN = "robotframework-2.*.exe"
$JYTHON_PATTERN = "jython_installer-2.*.jar"

; Usage to show to the user. If major versions of installed software are changed update them also here!!
; Patterns and directory names above are used in the usage so that they don't need to be updated.
$USAGE = "One Click Installer installs Robot Framework and its preconditions Python and Jython (optional). " & _
         "It also sets Robot Framework start-up scripts (pybot, jybot, rebot) as well as Python and Jython executables " & _
         "into %PATH% environment variable so that they can be executed from the command line. (Note that " & _
         "you need to restart the command prompt for these changes to take effect.)" & @CRLF & @CRLF & _
         "You should use this installer ONLY if you don't previously have Python or Jython installed. " & _
         "In that case, and also if you want to have a custom installation, you need to install needed " & _
         "components separately." & @CRLF & @CRLF & _
         "One Click Installer requires that you have all the required component installers in the same directory " & _
         "with it and that they have expected names. If Robot Framework or Python installer is missing, " & _
         "installation fails. If Jython installer doesn't exist, Jython is simply not installed. Note that " & _
         "in order to install Jython, Java 1.4 or newer must be already installed. Supported " & _
         "versions are Robot Framework 2.x, Python 2.5.x and Jython 2.2.x where '.x' means that any minor version " & _
         "(e.g. 2.5 or 2.5.2) is OK. These installers can be downloaded from respective project websites if " & _
         "they are missing. Expected patterns for installer names are '" & $ROBOT_PATTERN & "', '" & _
         $PYTHON_PATTERN & "' and '" & $JYTHON_PATTERN & "'." & @CRLF & @CRLF & _
         "The only thing you need to specify is the base directory where to install Python and Jython. " & _
         "They are installed into directories '" & $PYTHON_DIR_NAME & "' and '" & $JYTHON_DIR_NAME & "', " & _
         "respectively, inside the given base directory. Robot Framework itself is installed under Python " & _
         "installation directory and its startup scripts can be found from '[PYTHON]\Scripts' and code from " & _
         "'[PYTHON]\Lib\site-packages'." & @CRLF & @CRLF & _
         "Note that the specified base directory MUST exist and Python and Jython directories inside it must not. " & _
         "It is also not recommended to use a path containing spaces. Good candidates include directories like " & _
         "'C:\' and 'C:\APPS'."

;;
;; Main
;;

$base_dir = GetBaseDirectory()
$python_installer = GetRequiredInstaller($PYTHON_PATTERN, "Python")
$robot_installer = GetRequiredInstaller($ROBOT_PATTERN, "Robot")
$jython_installer = GetOptionalInstaller($JYTHON_PATTERN)
$python_dir = GetPythonDir($base_dir & $PYTHON_DIR_NAME)
$jython_dir = GetJythonDir($base_dir & $PYTHON_DIR_NAME, $jython_installer)
InstallPython($python_installer, $python_dir)
InstallJython($jython_installer, $jython_dir)
SetPath($python_dir, $jython_dir)  ; This must be done before InstallRobot to always have msvcrt71.dll in PATH
InstallRobot($robot_installer)
Exit

;;
;; Functions
;;

Func GetBaseDirectory()
    If $CmdLine[0] == 0 Then
        $base = InputBox("Robot Framework One Click Installer", $USAGE, "C:\", "", 500, 470)
    ElseIf $CmdLine[0] == 1 Then
        $base = $CmdLine[1]
    Else
        Cancel("Usage: " & @ScriptName & " [basedir]")
    EndIf
    If $base == "" Then
        Cancel("Installation cancelled by user.")
    ElseIf FileExists($base) == 0 Then
        Cancel("Given directory doesn't exist.")
    ElseIf StringRight($base, 1) <> "\" Then
        $base = $base & "\"
    EndIf
    Return $base
EndFunc

Func Cancel($msg)
    MsgBox(0, "Installation Cancelled", $msg)
    Exit
EndFunc

Func GetRequiredInstaller($pattern, $name)
    $installer = GetOptionalInstaller($pattern)
    If $installer == "" Then
        Cancel("Could not find " & $name & " installer with pattern '" & $pattern & "'")
    Endif
    return $installer
EndFunc

Func GetOptionalInstaller($pattern)
    $found = FileFindFirstFile($pattern)
    If $found == -1 Then
        $installer = ""
    Else
        $installer = FileFindNextFile($found)
    EndIf
    FileClose($found)
    return $installer
EndFunc

Func GetPythonDir($dir)
    VerifyInstallationDir($dir, "Python")
    return $dir
EndFunc

Func GetJythonDir($dir, $installer)
    If $installer == "" Then
        return ""
    EndIf
    VerifyInstallationDir($dir, "Jython")
    return $dir
EndFunc

Func VerifyInstallationDir($dir, $name)
    If FileExists($dir) == 1 Then
        Cancel($name & " installation directory '" & $dir & "' already exists.")
    EndIf
EndFunc

Func InstallPython($installer, $dir)
    $cmd = "msiexec /i " & $installer & " TARGETDIR=" & $dir & " /qb!"
    RunWait($cmd)
EndFunc

Func InstallJython($installer, $dir)
    If $installer == "" Then
        return
    EndIf
    $cmd = "java -jar " & $installer & " -s -d " & $dir
    RunWait($cmd)
EndFunc

Func InstallRobot($installer)
    Run($installer)
    WaitSetupWindowAndClickEnter("This Wizard will install")
    WaitSetupWindowAndClickEnter("Select python installation")
    WaitSetupWindowAndClickEnter("Ready to install")
    WaitSetupWindowAndClickEnter("Postinstall script finished")
EndFunc

Func WaitSetupWindowAndClickEnter($exp_text)
    WinWaitActive("Setup", $exp_text)
    Send("{ENTER}")
EndFunc

Func SetPath($python, $jython)
    $update = $python & ";" & $python & "\Scripts;" & $jython
    $orig = RegRead("HKCU\Environment", "PATH")

    If $orig == "" Then
        $new = $update
    ElseIf StringRight($orig, 1) == ";" Then
        $new = $orig & $update
    Else
        $new = $orig & ";" & $update
    EndIf

    RegWrite("HKCU\Environment", "PATH", "REG_EXPAND_SZ", $new)
    EnvUpdate()
EndFunc

;;  Copyright 2008 Nokia Siemens Networks Oyj
;;
;;  Licensed under the Apache License, Version 2.0 (the "License");
;;  you may not use this file except in compliance with the License.
;;  You may obtain a copy of the License at
;;
;;      http://www.apache.org/licenses/LICENSE-2.0
;;
;;  Unless required by applicable law or agreed to in writing, software
;;  distributed under the License is distributed on an "AS IS" BASIS,
;;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;  See the License for the specific language governing permissions and
;;  limitations under the License.

;; Robot Framework One Click Installer for Windows
;;
;; This installer installs Robot Framework and its preconditions Python and
;; Jython (optional). If installer is executed without arguments, it opens a
;; dialog explaining the options and asking the user to enter the installation
;; directory. If a command line options is given, it must be a path to an
;; existing directory and it is used as installation directory.
;;
;; For more information about this script see $USAGE below. To learn more
;; about silent Python installation, see url [1]. Silent Jython installation
;; options can be seen with command [2].
;;
;; [1] http://www.python.org/download/releases/2.5/msi/#automated
;; [2] java -jar jython_installer-2.2.x.jar --help

;;
;; Config
;;

; Expected patterns for installer names and target directory names.
$PYTHON_DIR_NAME = "Python25"
$JYTHON_DIR_NAME = "Jython22"
$PYTHON_PATTERN = "python-2.5*.msi"
$ROBOT_PATTERN = "robotframework-2.*.exe"
$JYTHON_PATTERN = "jython_installer-2.2*.jar"

; Usage to show to the user. If major versions of installed software are changed update them also here!!
; Patterns and directory names above are used in the usage so that they don't need to be updated.
$USAGE = "One Click Installer installs Robot Framework and its preconditions Python and Jython (optional). " & _
         "It also sets Robot Framework start-up scripts (pybot, jybot, rebot) as well as Python and Jython executables " & _
         "into %PATH% environment variable so that they can be executed from the command line. (Note that " & _
         "you need to restart the command prompt for these changes to take effect.)" & @CRLF & @CRLF & _
         "You should use this installer ONLY if you don't previously have Python or Jython installed. " & _
         "In that case, and also if you want to have a custom installation, you need to install needed " & _
         "components separately." & @CRLF & @CRLF & _
         "One Click Installer requires that you have all the required component installers in the same directory " & _
         "with it and that they have expected names. If Robot Framework or Python installer is missing, " & _
         "installation fails. If Jython installer doesn't exist, Jython is simply not installed. Note that " & _
         "in order to install Jython, Java 1.4 or newer must be already installed. Supported " & _
         "versions are Robot Framework 2.x, Python 2.5.x and Jython 2.2.x where '.x' means that any minor version " & _
         "(e.g. 2.5 or 2.5.2) is OK. These installers can be downloaded from respective project websites if " & _
         "they are missing. Expected patterns for installer names are '" & $ROBOT_PATTERN & "', '" & _
         $PYTHON_PATTERN & "' and '" & $JYTHON_PATTERN & "'." & @CRLF & @CRLF & _
         "The only thing you need to specify is the base directory where to install Python and Jython. " & _
         "They are installed into directories '" & $PYTHON_DIR_NAME & "' and '" & $JYTHON_DIR_NAME & "', " & _
         "respectively, inside the given base directory. Robot Framework itself is installed under Python " & _
         "installation directory and its startup scripts can be found from '[PYTHON]\Scripts' and code from " & _
         "'[PYTHON]\Lib\site-packages'." & @CRLF & @CRLF & _
         "Note that the specified base directory MUST exist and Python and Jython directories inside it must not. " & _
         "It is also not recommended to use a path containing spaces. Good candidates include directories like " & _
         "'C:\' and 'C:\APPS'."

;;
;; Main
;;

$base_dir = GetBaseDirectory()
$python_installer = GetRequiredInstaller($PYTHON_PATTERN, "Python")
$robot_installer = GetRequiredInstaller($ROBOT_PATTERN, "Robot")
$jython_installer = GetOptionalInstaller($JYTHON_PATTERN)
$python_dir = GetPythonDir($base_dir & $PYTHON_DIR_NAME)
$jython_dir = GetJythonDir($base_dir & $PYTHON_DIR_NAME, $jython_installer)
InstallPython($python_installer, $python_dir)
InstallJython($jython_installer, $jython_dir)
SetPath($python_dir, $jython_dir)  ; This must be done before InstallRobot to always have msvcrt71.dll in PATH
InstallRobot($robot_installer)
Exit

;;
;; Functions
;;

Func GetBaseDirectory()
    If $CmdLine[0] == 0 Then
        $base = InputBox("Robot Framework One Click Installer", $USAGE, "C:\", "", 500, 470)
    ElseIf $CmdLine[0] == 1 Then
        $base = $CmdLine[1]
    Else
        Cancel("Usage: " & @ScriptName & " [basedir]")
    EndIf
    If $base == "" Then
        Cancel("Installation cancelled by user.")
    ElseIf FileExists($base) == 0 Then
        Cancel("Given directory doesn't exist.")
    ElseIf StringRight($base, 1) <> "\" Then
        $base = $base & "\"
    EndIf
    Return $base
EndFunc

Func Cancel($msg)
    MsgBox(0, "Installation Cancelled", $msg)
    Exit
EndFunc

Func GetRequiredInstaller($pattern, $name)
    $installer = GetOptionalInstaller($pattern)
    If $installer == "" Then
        Cancel("Could not find " & $name & " installer with pattern '" & $pattern & "'")
    Endif
    return $installer
EndFunc

Func GetOptionalInstaller($pattern)
    $found = FileFindFirstFile($pattern)
    If $found == -1 Then
        $installer = ""
    Else
        $installer = FileFindNextFile($found)
    EndIf
    FileClose($found)
    return $installer
EndFunc

Func GetPythonDir($dir)
    VerifyInstallationDir($dir, "Python")
    return $dir
EndFunc

Func GetJythonDir($dir, $installer)
    If $installer == "" Then
        return ""
    EndIf
    VerifyInstallationDir($dir, "Jython")
    return $dir
EndFunc

Func VerifyInstallationDir($dir, $name)
    If FileExists($dir) == 1 Then
        Cancel($name & " installation directory '" & $dir & "' already exists.")
    EndIf
EndFunc

Func InstallPython($installer, $dir)
    $cmd = "msiexec /i " & $installer & " TARGETDIR=" & $dir & " /qb!"
    RunWait($cmd)
EndFunc

Func InstallJython($installer, $dir)
    If $installer == "" Then
        return
    EndIf
    $cmd = "java -jar " & $installer & " -s -d " & $dir
    RunWait($cmd)
EndFunc

Func InstallRobot($installer)
    Run($installer)
    WaitSetupWindowAndClickEnter("This Wizard will install")
    WaitSetupWindowAndClickEnter("Select python installation")
    WaitSetupWindowAndClickEnter("Ready to install")
    WaitSetupWindowAndClickEnter("Postinstall script finished")
EndFunc

Func WaitSetupWindowAndClickEnter($exp_text)
    WinWaitActive("Setup", $exp_text)
    Send("{ENTER}")
EndFunc

Func SetPath($python, $jython)
    $update = $python & ";" & $python & "\Scripts;" & $jython
    $orig = RegRead("HKCU\Environment", "PATH")

    If $orig == "" Then
        $new = $update
    ElseIf StringRight($orig, 1) == ";" Then
        $new = $orig & $update
    Else
        $new = $orig & ";" & $update
    EndIf

    RegWrite("HKCU\Environment", "PATH", "REG_EXPAND_SZ", $new)
    EnvUpdate()
EndFunc


Send telegran command , fix help info

Send telegran command , fix help info

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=..\..\images\RT1.ico
#AutoIt3Wrapper_Outfile=SendTelegramSubteBA.exe
#AutoIt3Wrapper_Compression=4
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_UseX64=y
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_Comment="By Marcelo N. Saied "
#AutoIt3Wrapper_Res_Description="Send Telegram application Message"
#AutoIt3Wrapper_Res_Fileversion=1.0.0.1
#AutoIt3Wrapper_Res_ProductVersion=1.0
#AutoIt3Wrapper_Res_LegalCopyright=Marcelo N. Saied
#AutoIt3Wrapper_Res_Field=Productname|SendTelegramSubteBA.exe
#AutoIt3Wrapper_Res_Field=ProductVersion|Version 1.0
#AutoIt3Wrapper_Run_Obfuscator=y
#Obfuscator_Parameters=/mergeonly
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
; *** Start added by AutoIt3Wrapper ***
#include <FileConstants.au3>
; *** End added by AutoIt3Wrapper ***
;===================================================================
;===================================================================
;===                                                             ===
;===   Name   = SendTelegramSubteBA.exe                                 ===
;===                                                             ===
;===   Description:Send Telegram application Message             ===
;===                                                             ===
;===   Author: Marcelo N. Saied                                  ===
;===           marcelosaied@gmail.com                            ===
;===                                                             ===
;===   Automation and Scripting Language: AUTOIT  v3.3.8.1       ===
;===           http://www.autoitscript.com/site/                 ===
;===                                                             ===
;===   Created on: Jan 9 , 2016                                  ===
;===                                                             ===
;===================================================================
;===================================================================
#Region  ------------ AutoIt3Wrapper
$chatID=""
#EndRegion
#Region  ------------ Modules
	#include <File.au3>
	#include <Constants.au3>
	#include <Date.au3>
	#include <Array.au3>
	#include <date.au3>
	#include <IE.au3>
	#include <Array.au3>
	#include "..\..\udf\WinHttp.au3"
#EndRegion
#Region  -----------------------------  parse arguments ------------------------------
; Help
   $helpText="Help:                                                                     " & @crlf & _
			"                                                                           " & @crlf & _
			"      Usage:                                                               " & @crlf & _
			"          SendTelegramSubteBA.exe -m <message> -chatid chatid              " & @crlf & _
			"                                                                           " & @crlf & _
			"          -m   message                                                     " & @crlf & _
			"          -chatid  chatid                                                  " & @crlf & _
			"                                                                           " & @crlf & _
			"            Author: Saied, Marcelo                                         " & @crlf & _
			"                                                                           " & @crlf & _
			"                                      2017                                 " & @crlf & _
			"                                                                           " & @crlf & _
			"                                                                           " & @crlf & _
			"                                                                           " & @crlf & _
			"                                                                           "
;~

   if $CmdLine[0]=0 then
	  ConsoleWrite($helpText)
	   exit 1
   endif
   if StringStripWS($CmdLine[1],4)="?"   then  ; output help
	  ConsoleWrite($helpText)
	    exit 3
	endif
;~ 	ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $CmdLine[0] = ' & $CmdLine[0] & @crlf )
    if $CmdLine[0]<2 then  ; if no 3 argumentes then exit    -f filename  -u username -p password  ([-d][-nd])
	  ConsoleWrite("No enough arguments. <Usage>: SendTelegramSubteBA.exe -m <message> -chatid  chatid   ")
	  exit 5
   endif

   for $x=1 to $CmdLine[0]-1
	  Select
		case $CmdLine[$x] = "-m"
			$x = $x + 1
			if StringLen($CmdLine[$x]) > 2 then   $mensaje=$CmdLine[$x]
		case $CmdLine[$x] = "-chatid"
			$x = $x + 1
			if StringLen($CmdLine[$x]) > 2 then   $chatID=$CmdLine[$x]
		 Case Else
			ConsoleWrite("No enough arguments <Usage>: SendTelegram.exe -m <message>  ")
			ConsoleWrite("                              SendTelegram.exe ?  for help  ")
			ConsoleWrite(@CRLF)
			exit 6
	  EndSelect
   Next
#EndRegion

SendTelegram($mensaje)
Func SendTelegram($msgtext="testeo")
	if SendTelegramexec($msgtext) Then
		exit 15
	else
		exit 20
	endif
EndFunc

Func SendTelegramexec($msgtext="testeo harcoded")
	local $token=IniRead("..\..\secret\config.ini","bot","token","")
	$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & "&text=" & $msgtext
	$sGet = HttpGet($urlMSG)

	if $sGet<>"0" then
		ConsoleWrite('Telegram Message sent = ' & $msgtext & @crlf )
		return 0
	Else
		$s_text="Error sending message to Telegram = "
		return 1
	endif
EndFunc

exit

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=..\..\images\RT1.ico
#AutoIt3Wrapper_Outfile=SendTelegramSubteBA.exe
#AutoIt3Wrapper_Compression=4
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_UseX64=y
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_Comment="By Marcelo N. Saied "
#AutoIt3Wrapper_Res_Description="Send Telegram application Message"
#AutoIt3Wrapper_Res_Fileversion=1.0.0.1
#AutoIt3Wrapper_Res_ProductVersion=1.0
#AutoIt3Wrapper_Res_LegalCopyright=Marcelo N. Saied
#AutoIt3Wrapper_Res_Field=Productname|SendTelegramSubteBA.exe
#AutoIt3Wrapper_Res_Field=ProductVersion|Version 1.0
#AutoIt3Wrapper_Run_Obfuscator=y
#Obfuscator_Parameters=/mergeonly
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
; *** Start added by AutoIt3Wrapper ***
#include <FileConstants.au3>
; *** End added by AutoIt3Wrapper ***
;===================================================================
;===================================================================
;===                                                             ===
;===   Name   = SendTelegramSubteBA.exe                                 ===
;===                                                             ===
;===   Description:Send Telegram application Message             ===
;===                                                             ===
;===   Author: Marcelo N. Saied                                  ===
;===           marcelosaied@gmail.com                            ===
;===                                                             ===
;===   Automation and Scripting Language: AUTOIT  v3.3.8.1       ===
;===           http://www.autoitscript.com/site/                 ===
;===                                                             ===
;===   Created on: Jan 9 , 2016                                  ===
;===                                                             ===
;===================================================================
;===================================================================
#Region  ------------ AutoIt3Wrapper
$chatID=""
#EndRegion
#Region  ------------ Modules
	#include <File.au3>
	#include <Constants.au3>
	#include <Date.au3>
	#include <Array.au3>
	#include <date.au3>
	#include <IE.au3>
	#include <Array.au3>
	#include "..\..\udf\WinHttp.au3"
#EndRegion
#Region  -----------------------------  parse arguments ------------------------------
; Help
   $helpText="Help:                                                                     " & @crlf & _
			"                                                                           " & @crlf & _
			"      Usage:                                                               " & @crlf & _
			"          SendTelegramSubteBA.exe -m <message> -chatid chatid <optional>   " & @crlf & _
			"                                                                           " & @crlf & _
			"          -m   message                                                     " & @crlf & _
			"          -chatid  chatid  <optional>                                      " & @crlf & _
			"                                                                           " & @crlf & _
			"            Author: Saied, Marcelo                                         " & @crlf & _
			"                                                                           " & @crlf & _
			"                                      2017                                 " & @crlf & _
			"                                                                           " & @crlf & _
			"                                                                           " & @crlf & _
			"                                                                           " & @crlf & _
			"                                                                           "
;~

   if $CmdLine[0]=0 then
	  ConsoleWrite($helpText)
	   exit 1
   endif
   if StringStripWS($CmdLine[1],4)="?"   then  ; output help
	  ConsoleWrite($helpText)
	    exit 3
	endif
;~ 	ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $CmdLine[0] = ' & $CmdLine[0] & @crlf )
    if $CmdLine[0]<2 then  ; if no 3 argumentes then exit    -f filename  -u username -p password  ([-d][-nd])
	  ConsoleWrite("No enough arguments. <Usage>: SendTelegramSubteBA.exe -m <message> -chatid  chatid  <optional>  ")
	  exit 5
   endif

   for $x=1 to $CmdLine[0]-1
	  Select
		case $CmdLine[$x] = "-m"
			$x = $x + 1
			if StringLen($CmdLine[$x]) > 2 then   $mensaje=$CmdLine[$x]
		case $CmdLine[$x] = "-chatid"
			$x = $x + 1
			if StringLen($CmdLine[$x]) > 2 then   $chatID=$CmdLine[$x]
		 Case Else
			ConsoleWrite("No enough arguments <Usage>: SendTelegram.exe -m <message>  ")
			ConsoleWrite("                              SendTelegram.exe ?  for help  ")
			ConsoleWrite(@CRLF)
			exit 6
	  EndSelect
   Next
#EndRegion

SendTelegram($mensaje)
Func SendTelegram($msgtext="testeo")
	if SendTelegramexec($msgtext) Then
		sleep(3000)
		if $chatID<>"" then	SendTelegramexec($msgtext)
	endif
EndFunc

Func SendTelegramexec($msgtext="testeo harcoded")
	local $token=IniRead("..\..\secret\config.ini","bot","token","")
	$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & "&text=" & $msgtext
	$sGet = HttpGet($urlMSG)

	if $sGet<>"0" then
		ConsoleWrite('Telegram Message sent = ' & $msgtext & @crlf )
		return 0
	Else
		$s_text="Error sending message to Telegram = "
		return 1
	endif
EndFunc

exit


Function Time between

Function Time between

#region ===========================================================================
	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, $dbfile, $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 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 SendTelegramMessages($TweetArr)
		If IsArray($TweetArr) Then
			$U = UBound($TweetArr) - 1
			For $i = $u To 1 Step -1
				sendmessages($TweetArr[1])
			Next
			Exit 30
		Else
			Exit 21
		EndIf
	EndFunc
;~  	Func sendmessages($message)  ;~ from file of recipients
;~ 		Local $fileh = FileOpen("secret\recipients.txt", 0)
;~ 		If $fileh = -1 Then
;~ 			Exit 26
;~ 		EndIf
;~ 		While 1
;~ 			Local $chatidLine = FileReadLine($fileh)
;~ 			If @error = -1 Then ExitLoop
;~ 			$chatidArr = StringSplit($chatidLine, ',')
;~ 			$chatid = $chatidArr[1]
;~ 			if $chatID<>"" then
;~ 				ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $chatidArr[2] & @CRLF)
;~ 				$respuesta = SendTelegramexec($chatid,$message)
;~ 			$respuesta  0 is ok
;~ 			endif
;~ 		WEnd
;~ 		FileClose($fileh)
;~ 	EndFunc   ;==>_sendmessages
	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&"%0A"&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")
		$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & _
		"&text=" & $msgtext & "&parse_mode=HTML"
		$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 handeling ===================================================================
	func _ScrapTweetMessages($Username)
		Local $sData = InetRead("https://twitter.com/"&$Username)
		Local $nBytesRead = @extended
		ConsoleWrite('@@(' & @ScriptName & '-' & @ScriptLineNumber & ') : $nBytesRead = ' & $nBytesRead & @CRLF)
		$htmltxt = BinaryToString($sData)
		If $nBytesRead < 100 Then	Exit 25
		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)
	;~ 		_ArrayDisplay($TweetArr)
			return $TweetArr
		Else
			ConsoleWrite('!!!(' &  @ScriptLineNumber & ') : Error on  $MSGArr = ' & $MSGArr & @crlf )
			return 0
		endif
	EndFunc
#endregion
#region  ==== Bot Messages handeling ===================================================================
	func UpdateUsers()
		ConsoleWrite('  Update users ' & @crlf)
		local $s=GetBotUpdates()
		$s=StringReplace($s,'"username":','"last_name":')
		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
					$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())
					$epochArr = StripIntJS($jsonObj.jsonPath( "$.result..message.date").stringify())
					for $i=1 to $UserIDArr[0]
						SQLregister($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i])
					next
				endif
			endif
		endif
	EndFunc
	Func GetBotUpdates()
		$urlMSG="https://api.telegram.org/" & $token & "/getUpdates"
		$sGet = HttpGetJson($urlMSG)
		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 SQLregister($UserID,$Fname,$Lname,$epoch)
;~ 	ConsoleWrite('++SQLregister() = '& @crlf)
		if SQLExistUser($UserID)=0 then
			SQLInsertUser($UserID,$Fname,$Lname,$epoch)
		endif
	EndFunc
	Func SQLInsertUser($UserID,$Fname,$Lname,$epoch)
;~ 	ConsoleWrite('++SQLInsertUser() = '& @crlf)
		ConsoleWrite('  Nuevo usuario = '& $Fname & "  "  & $Lname  & @crlf)
		$query='INSERT INTO Users VALUES (' & $UserID & ',"' & $Fname & '","' & $Lname & '",1,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 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
#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
	;~   _ArrayDisplay($array1)
		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
		 ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') & @CRLF)
		 ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') & @CRLF)
		 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 ===========================================================================
	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, $dbfile, $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 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 SendTelegramMessages($TweetArr)
		If IsArray($TweetArr) Then
			$U = UBound($TweetArr) - 1
			For $i = $u To 1 Step -1
				sendmessages($TweetArr[1])
			Next
			Exit 30
		Else
			Exit 21
		EndIf
	EndFunc
;~  	Func sendmessages($message)  ;~ from file of recipients
;~ 		Local $fileh = FileOpen("secret\recipients.txt", 0)
;~ 		If $fileh = -1 Then
;~ 			Exit 26
;~ 		EndIf
;~ 		While 1
;~ 			Local $chatidLine = FileReadLine($fileh)
;~ 			If @error = -1 Then ExitLoop
;~ 			$chatidArr = StringSplit($chatidLine, ',')
;~ 			$chatid = $chatidArr[1]
;~ 			if $chatID<>"" then
;~ 				ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $chatidArr[2] & @CRLF)
;~ 				$respuesta = SendTelegramexec($chatid,$message)
;~ 			$respuesta  0 is ok
;~ 			endif
;~ 		WEnd
;~ 		FileClose($fileh)
;~ 	EndFunc   ;==>_sendmessages
	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&"%0A"&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")
		$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & _
		"&text=" & $msgtext & "&parse_mode=HTML"
		$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 handeling ===================================================================
	func _ScrapTweetMessages($Username)
		Local $sData = InetRead("https://twitter.com/"&$Username)
		Local $nBytesRead = @extended
		ConsoleWrite('@@(' & @ScriptName & '-' & @ScriptLineNumber & ') : $nBytesRead = ' & $nBytesRead & @CRLF)
		$htmltxt = BinaryToString($sData)
		If $nBytesRead < 100 Then	Exit 25
		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)
	;~ 		_ArrayDisplay($TweetArr)
			return $TweetArr
		Else
			ConsoleWrite('!!!(' &  @ScriptLineNumber & ') : Error on  $MSGArr = ' & $MSGArr & @crlf )
			return 0
		endif
	EndFunc
#endregion
#region  ==== Bot Messages handeling ===================================================================
	func UpdateUsers()
		ConsoleWrite('  Update users ' & @crlf)
		local $s=GetBotUpdates()
		$s=StringReplace($s,'"username":','"last_name":')
		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
					$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())
					$epochArr = StripIntJS($jsonObj.jsonPath( "$.result..message.date").stringify())
					for $i=1 to $UserIDArr[0]
						SQLregister($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i])
					next
				endif
			endif
		endif
	EndFunc
	Func GetBotUpdates()
		$urlMSG="https://api.telegram.org/" & $token & "/getUpdates"
		$sGet = HttpGetJson($urlMSG)
		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 SQLregister($UserID,$Fname,$Lname,$epoch)
;~ 	ConsoleWrite('++SQLregister() = '& @crlf)
		if SQLExistUser($UserID)=0 then
			SQLInsertUser($UserID,$Fname,$Lname,$epoch)
		endif
	EndFunc
	Func SQLInsertUser($UserID,$Fname,$Lname,$epoch)
;~ 	ConsoleWrite('++SQLInsertUser() = '& @crlf)
		ConsoleWrite('  Nuevo usuario = '& $Fname & "  "  & $Lname  & @crlf)
		$query='INSERT INTO Users VALUES (' & $UserID & ',"' & $Fname & '","' & $Lname & '",1,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 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
#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
	;~   _ArrayDisplay($array1)
		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
#endregion


updated usage

updated usage

--HG--
extra : convert_revision : svn%3A79c32731-664e-0410-8185-e51b9e89f9fb/trunk%401090

;;  Copyright 2008 Nokia Siemens Networks Oyj
;;
;;  Licensed under the Apache License, Version 2.0 (the "License");
;;  you may not use this file except in compliance with the License.
;;  You may obtain a copy of the License at
;;
;;      http://www.apache.org/licenses/LICENSE-2.0
;;
;;  Unless required by applicable law or agreed to in writing, software
;;  distributed under the License is distributed on an "AS IS" BASIS,
;;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;  See the License for the specific language governing permissions and
;;  limitations under the License.

;; Robot Framework One Click Installer for Windows
;;
;; This installer installs Robot Framework and its preconditions Python and
;; Jython (optional). If installer is executed without arguments, it opens a
;; dialog explaining the options and asking the user to enter the installation
;; directory. If a command line options is given, it must be a path to an
;; existing directory and it is used as installation directory.
;;
;; For more information about this script see $USAGE below. To learn more
;; about silent Python installation, see url [1]. Silent Jython installation
;; options can be seen with command [2].
;;
;; [1] http://www.python.org/download/releases/2.5/msi/#automated
;; [2] java -jar jython_installer-2.2.x.jar --help

;;
;; Config
;;

; Expected patterns for installer names and target directory names.
$PYTHON_DIR_NAME = "Python"
$JYTHON_DIR_NAME = "Jython"
$PYTHON_PATTERN = "python-2.*.msi"
$ROBOT_PATTERN = "robotframework-2.*.exe"
$JYTHON_PATTERN = "jython_installer-2.*.jar"

; Usage to show to the user. If major versions of installed software are changed update them also here!!
; Patterns and directory names above are used in the usage so that they don't need to be updated.
$USAGE = "One Click Installer installs Robot Framework and its preconditions Python and Jython (optional). " & _
         "It also sets Robot Framework start-up scripts (pybot, jybot, rebot) as well as Python and Jython executables " & _
         "into %PATH% environment variable so that they can be executed from the command line. (Note that " & _
         "you need to restart the command prompt for these changes to take effect.)" & @CRLF & @CRLF & _
         "You should use this installer ONLY if you do not previously have Python or Jython installed. " & _
         "In that case, and also if you want to have a custom installation, you need to install needed " & _
         "components separately." & @CRLF & @CRLF & _
         "One Click Installer requires that you have all the required component installers in the same directory " & _
         "with it and that they have expected names. If Robot Framework or Python installer is missing, " & _
         "installation fails. If Jython installer does not exist, Jython is simply not installed. Note that " & _
         "in order to install Jython, Java 1.4 or newer must be already installed. Minimum supported versions " & _
         "are Robot Framework 2.0, Python 2.5 and Jython 2.2, but newer versiosn are always recommened. These " & _
         "installers can be downloaded from respective project websites. Expected patterns for installer names are '" & _
         $ROBOT_PATTERN & "', '" & $PYTHON_PATTERN & "' and '" & $JYTHON_PATTERN & "'." & @CRLF & @CRLF & _
         "The only thing you need to specify is the base directory where to install Python and Jython. " & _
         "They are installed into directories '" & $PYTHON_DIR_NAME & "' and '" & $JYTHON_DIR_NAME & "', " & _
         "respectively, inside the given base directory. Robot Framework itself is installed under Python " & _
         "installation directory and its startup scripts can be found from '[PYTHON]\Scripts' and code from " & _
         "'[PYTHON]\Lib\site-packages'." & @CRLF & @CRLF & _
         "Note that the specified base directory MUST exist and Python and Jython directories inside it must not. " & _
         "It is also not recommended to use a path containing spaces. Good candidates include directories like " & _
         "'C:\' and 'C:\APPS'."

;;
;; Main
;;

$base_dir = GetBaseDirectory()
$python_installer = GetRequiredInstaller($PYTHON_PATTERN, "Python")
$robot_installer = GetRequiredInstaller($ROBOT_PATTERN, "Robot")
$jython_installer = GetOptionalInstaller($JYTHON_PATTERN)
$python_dir = GetPythonDir($base_dir & $PYTHON_DIR_NAME)
$jython_dir = GetJythonDir($base_dir & $PYTHON_DIR_NAME, $jython_installer)
InstallPython($python_installer, $python_dir)
InstallJython($jython_installer, $jython_dir)
SetPath($python_dir, $jython_dir)  ; This must be done before InstallRobot to always have msvcrt71.dll in PATH
InstallRobot($robot_installer)
Exit

;;
;; Functions
;;

Func GetBaseDirectory()
    If $CmdLine[0] == 0 Then
        $base = InputBox("Robot Framework One Click Installer", $USAGE, "C:\", "", 500, 470)
    ElseIf $CmdLine[0] == 1 Then
        $base = $CmdLine[1]
    Else
        Cancel("Usage: " & @ScriptName & " [basedir]")
    EndIf
    If $base == "" Then
        Cancel("Installation cancelled by user.")
    ElseIf FileExists($base) == 0 Then
        Cancel("Given directory doesn't exist.")
    ElseIf StringRight($base, 1) <> "\" Then
        $base = $base & "\"
    EndIf
    Return $base
EndFunc

Func Cancel($msg)
    MsgBox(0, "Installation Cancelled", $msg)
    Exit
EndFunc

Func GetRequiredInstaller($pattern, $name)
    $installer = GetOptionalInstaller($pattern)
    If $installer == "" Then
        Cancel("Could not find " & $name & " installer with pattern '" & $pattern & "'")
    Endif
    return $installer
EndFunc

Func GetOptionalInstaller($pattern)
    $found = FileFindFirstFile($pattern)
    If $found == -1 Then
        $installer = ""
    Else
        $installer = FileFindNextFile($found)
    EndIf
    FileClose($found)
    return $installer
EndFunc

Func GetPythonDir($dir)
    VerifyInstallationDir($dir, "Python")
    return $dir
EndFunc

Func GetJythonDir($dir, $installer)
    If $installer == "" Then
        return ""
    EndIf
    VerifyInstallationDir($dir, "Jython")
    return $dir
EndFunc

Func VerifyInstallationDir($dir, $name)
    If FileExists($dir) == 1 Then
        Cancel($name & " installation directory '" & $dir & "' already exists.")
    EndIf
EndFunc

Func InstallPython($installer, $dir)
    $cmd = "msiexec /i " & $installer & " TARGETDIR=" & $dir & " /qb!"
    RunWait($cmd)
EndFunc

Func InstallJython($installer, $dir)
    If $installer == "" Then
        return
    EndIf
    $cmd = "java -jar " & $installer & " -s -d " & $dir
    RunWait($cmd)
EndFunc

Func InstallRobot($installer)
    Run($installer)
    WaitSetupWindowAndClickEnter("This Wizard will install")
    WaitSetupWindowAndClickEnter("Select python installation")
    WaitSetupWindowAndClickEnter("Ready to install")
    WaitSetupWindowAndClickEnter("Postinstall script finished")
EndFunc

Func WaitSetupWindowAndClickEnter($exp_text)
    WinWaitActive("Setup", $exp_text)
    Send("{ENTER}")
EndFunc

Func SetPath($python, $jython)
    $update = $python & ";" & $python & "\Scripts;" & $jython
    $orig = RegRead("HKCU\Environment", "PATH")

    If $orig == "" Then
        $new = $update
    ElseIf StringRight($orig, 1) == ";" Then
        $new = $orig & $update
    Else
        $new = $orig & ";" & $update
    EndIf

    RegWrite("HKCU\Environment", "PATH", "REG_EXPAND_SZ", $new)
    EnvUpdate()
EndFunc

;;  Copyright 2008 Nokia Siemens Networks Oyj
;;
;;  Licensed under the Apache License, Version 2.0 (the "License");
;;  you may not use this file except in compliance with the License.
;;  You may obtain a copy of the License at
;;
;;      http://www.apache.org/licenses/LICENSE-2.0
;;
;;  Unless required by applicable law or agreed to in writing, software
;;  distributed under the License is distributed on an "AS IS" BASIS,
;;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;  See the License for the specific language governing permissions and
;;  limitations under the License.

;; Robot Framework One Click Installer for Windows
;;
;; This installer installs Robot Framework and its preconditions Python and
;; Jython (optional). If installer is executed without arguments, it opens a
;; dialog explaining the options and asking the user to enter the installation
;; directory. If a command line options is given, it must be a path to an
;; existing directory and it is used as installation directory.
;;
;; For more information about this script see $USAGE below. To learn more
;; about silent Python installation, see url [1]. Silent Jython installation
;; options can be seen with command [2].
;;
;; [1] http://www.python.org/download/releases/2.5/msi/#automated
;; [2] java -jar jython_installer-2.2.x.jar --help

;;
;; Config
;;

; Expected patterns for installer names and target directory names.
$PYTHON_DIR_NAME = "Python"
$JYTHON_DIR_NAME = "Jython"
$PYTHON_PATTERN = "python-2.*.msi"
$ROBOT_PATTERN = "robotframework-2.*.exe"
$JYTHON_PATTERN = "jython_installer-2.*.jar"

; Usage to show to the user. If major versions of installed software are changed update them also here!!
; Patterns and directory names above are used in the usage so that they don't need to be updated.
$USAGE = "One Click Installer installs Robot Framework and its preconditions Python and Jython (optional). " & _
         "It also sets Robot Framework start-up scripts (pybot, jybot, rebot) as well as Python and Jython executables " & _
         "into %PATH% environment variable so that they can be executed from the command line. (Note that " & _
         "you need to restart the command prompt for these changes to take effect.)" & @CRLF & @CRLF & _
         "You should use this installer ONLY if you don't previously have Python or Jython installed. " & _
         "In that case, and also if you want to have a custom installation, you need to install needed " & _
         "components separately." & @CRLF & @CRLF & _
         "One Click Installer requires that you have all the required component installers in the same directory " & _
         "with it and that they have expected names. If Robot Framework or Python installer is missing, " & _
         "installation fails. If Jython installer doesn't exist, Jython is simply not installed. Note that " & _
         "in order to install Jython, Java 1.4 or newer must be already installed. Supported " & _
         "versions are Robot Framework 2.x, Python 2.5.x and Jython 2.2.x where '.x' means that any minor version " & _
         "(e.g. 2.5 or 2.5.2) is OK. These installers can be downloaded from respective project websites if " & _
         "they are missing. Expected patterns for installer names are '" & $ROBOT_PATTERN & "', '" & _
         $PYTHON_PATTERN & "' and '" & $JYTHON_PATTERN & "'." & @CRLF & @CRLF & _
         "The only thing you need to specify is the base directory where to install Python and Jython. " & _
         "They are installed into directories '" & $PYTHON_DIR_NAME & "' and '" & $JYTHON_DIR_NAME & "', " & _
         "respectively, inside the given base directory. Robot Framework itself is installed under Python " & _
         "installation directory and its startup scripts can be found from '[PYTHON]\Scripts' and code from " & _
         "'[PYTHON]\Lib\site-packages'." & @CRLF & @CRLF & _
         "Note that the specified base directory MUST exist and Python and Jython directories inside it must not. " & _
         "It is also not recommended to use a path containing spaces. Good candidates include directories like " & _
         "'C:\' and 'C:\APPS'."

;;
;; Main
;;

$base_dir = GetBaseDirectory()
$python_installer = GetRequiredInstaller($PYTHON_PATTERN, "Python")
$robot_installer = GetRequiredInstaller($ROBOT_PATTERN, "Robot")
$jython_installer = GetOptionalInstaller($JYTHON_PATTERN)
$python_dir = GetPythonDir($base_dir & $PYTHON_DIR_NAME)
$jython_dir = GetJythonDir($base_dir & $PYTHON_DIR_NAME, $jython_installer)
InstallPython($python_installer, $python_dir)
InstallJython($jython_installer, $jython_dir)
SetPath($python_dir, $jython_dir)  ; This must be done before InstallRobot to always have msvcrt71.dll in PATH
InstallRobot($robot_installer)
Exit

;;
;; Functions
;;

Func GetBaseDirectory()
    If $CmdLine[0] == 0 Then
        $base = InputBox("Robot Framework One Click Installer", $USAGE, "C:\", "", 500, 470)
    ElseIf $CmdLine[0] == 1 Then
        $base = $CmdLine[1]
    Else
        Cancel("Usage: " & @ScriptName & " [basedir]")
    EndIf
    If $base == "" Then
        Cancel("Installation cancelled by user.")
    ElseIf FileExists($base) == 0 Then
        Cancel("Given directory doesn't exist.")
    ElseIf StringRight($base, 1) <> "\" Then
        $base = $base & "\"
    EndIf
    Return $base
EndFunc

Func Cancel($msg)
    MsgBox(0, "Installation Cancelled", $msg)
    Exit
EndFunc

Func GetRequiredInstaller($pattern, $name)
    $installer = GetOptionalInstaller($pattern)
    If $installer == "" Then
        Cancel("Could not find " & $name & " installer with pattern '" & $pattern & "'")
    Endif
    return $installer
EndFunc

Func GetOptionalInstaller($pattern)
    $found = FileFindFirstFile($pattern)
    If $found == -1 Then
        $installer = ""
    Else
        $installer = FileFindNextFile($found)
    EndIf
    FileClose($found)
    return $installer
EndFunc

Func GetPythonDir($dir)
    VerifyInstallationDir($dir, "Python")
    return $dir
EndFunc

Func GetJythonDir($dir, $installer)
    If $installer == "" Then
        return ""
    EndIf
    VerifyInstallationDir($dir, "Jython")
    return $dir
EndFunc

Func VerifyInstallationDir($dir, $name)
    If FileExists($dir) == 1 Then
        Cancel($name & " installation directory '" & $dir & "' already exists.")
    EndIf
EndFunc

Func InstallPython($installer, $dir)
    $cmd = "msiexec /i " & $installer & " TARGETDIR=" & $dir & " /qb!"
    RunWait($cmd)
EndFunc

Func InstallJython($installer, $dir)
    If $installer == "" Then
        return
    EndIf
    $cmd = "java -jar " & $installer & " -s -d " & $dir
    RunWait($cmd)
EndFunc

Func InstallRobot($installer)
    Run($installer)
    WaitSetupWindowAndClickEnter("This Wizard will install")
    WaitSetupWindowAndClickEnter("Select python installation")
    WaitSetupWindowAndClickEnter("Ready to install")
    WaitSetupWindowAndClickEnter("Postinstall script finished")
EndFunc

Func WaitSetupWindowAndClickEnter($exp_text)
    WinWaitActive("Setup", $exp_text)
    Send("{ENTER}")
EndFunc

Func SetPath($python, $jython)
    $update = $python & ";" & $python & "\Scripts;" & $jython
    $orig = RegRead("HKCU\Environment", "PATH")

    If $orig == "" Then
        $new = $update
    ElseIf StringRight($orig, 1) == ";" Then
        $new = $orig & $update
    Else
        $new = $orig & ";" & $update
    EndIf

    RegWrite("HKCU\Environment", "PATH", "REG_EXPAND_SZ", $new)
    EnvUpdate()
EndFunc


add log in upload.au3

add log in upload.au3

#include <File.au3>
FileDelete(@ScriptDir & "\upload.log")
Local $hFile = FileOpen(@ScriptDir & "\upload.log", 1)
Local $count = 0
Local $result = 1
Sleep(400)
; Verific daca vereastra de upload este FireFox
If WinExists("[TITLE:File; CLASS:#32770]") Then
    $activeWindow = WinWait("[TITLE:File; CLASS:#32770]", " ", 6)
    WinActivate($activeWindow)
    _FileWriteLog($hFile, "File$activeWindow='" & $activeWindow & "'")
Else ; In caz contrar e Chrome
    $activeWindow = WinWait("[TITLE:Open; CLASS:#32770]", "", 3)
    WinActivate($activeWindow)
    _FileWriteLog($hFile, "Open$activeWindow='" & $activeWindow & "'")
EndIf
$activeWindowTitle = WinGetTitle($activeWindow)
WinFlash($activeWindowTitle, "", 1, 50) ; Just to Flash the window

Do
   _FileWriteLog($hFile, "$activeWindowTitle00='" & $activeWindowTitle & "'")
   If $count > 10 Then
	  $result = 1
	  ExitLoop
	EndIf
	Sleep(100)
    $count = $count + 1
Until ControlShow($activeWindowTitle, "", "Edit1") = 1
_FileWriteLog($hFile, "filePath='" & $CmdLine[1] & "'")
Local $edit = ControlSetText($activeWindowTitle, "", "Edit1", $CmdLine[1])
;Local $edit = ControlSetText($activeWindowTitle, "", "Edit1", "D:\Mill\src\test\resources\file\export.xml")
_FileWriteLog($hFile, "$edit='" & $edit & "'")

$count = 0
Do
    _FileWriteLog($hFile, "$activeWindowTitle4='" & $activeWindowTitle & "'")
	If $count > 10 Then
	   $result = 1
	  ExitLoop
	EndIf
    Sleep(100)
    $count = $count + 1
	$result = 0
Until ControlShow($activeWindowTitle, "", "Button1") = 1

Local $click;
If (ControlShow($activeWindowTitle, "", "Button1") = 1) Then
   $click = ControlClick($activeWindowTitle, "", "[CLASS:Button; INSTANCE:1]")
   $result = 0
   _FileWriteLog($hFile, "$clickDefault='" & $click & "'")
ElseIf (ControlShow($activeWindowTitle, "", "Button2") = 1) Then
   $click = ControlClick($activeWindowTitle, "", "[CLASS:Button; INSTANCE:2]") ;Pentru browserul straniu de la BeGlobal
   $result = 0
   _FileWriteLog($hFile, "$clickStraniu='" & $click =  & "'")
Else
   $result = 1
   _FileWriteLog($hFile, "Error! Nu am gasit nici un button!!!!")
EndIf
Sleep(300)
$close = WinWaitClose($activeWindowTitle, "", 3)
_FileWriteLog($hFile, "win='" & $activeWindowTitle & "'")
_FileWriteLog($hFile, "$close='" & $close & "'")
_FileWriteLog($hFile, "$result='" & $result & "'")
_FileWriteLog($hFile, "------------------------- New Upload --------------------------")
FileClose($hFile)
Exit $result

#include <File.au3>
FileDelete(@ScriptDir & "\upload.log")
Local $hFile = FileOpen(@ScriptDir & "\upload.log", 1)
Local $count = 0
Local $result = 1
Sleep(400)
; Verific daca vereastra de upload este FireFox
If WinExists("[TITLE:File; CLASS:#32770]") Then
    $activeWindow = WinWait("[TITLE:File; CLASS:#32770]", " ", 6)
    WinActivate($activeWindow)
    _FileWriteLog($hFile, "File$activeWindow='" & $activeWindow & "'")
Else ; In caz contrar e Chrome
    $activeWindow = WinWait("[TITLE:Open; CLASS:#32770]", "", 3)
    WinActivate($activeWindow)
    _FileWriteLog($hFile, "Open$activeWindow='" & $activeWindow & "'")
EndIf
$activeWindowTitle = WinGetTitle($activeWindow)
WinFlash($activeWindowTitle, "", 1, 50) ; Just to Flash the window

Do
   _FileWriteLog($hFile, "$activeWindowTitle00='" & $activeWindowTitle & "'")
   If $count > 10 Then
	  $result = 1
	  ExitLoop
	EndIf
	Sleep(100)
    $count = $count + 1
Until ControlShow($activeWindowTitle, "", "Edit1") = 1
Local $edit = ControlSetText($activeWindowTitle, "", "Edit1", $CmdLine[1])
;Local $edit = ControlSetText($activeWindowTitle, "", "Edit1", "D:\Mill\src\test\resources\file\export.xml")
_FileWriteLog($hFile, "$edit='" & $edit & "'")

$count = 0
Do
    _FileWriteLog($hFile, "$activeWindowTitle4='" & $activeWindowTitle & "'")
	If $count > 10 Then
	   $result = 1
	  ExitLoop
	EndIf
    Sleep(100)
    $count = $count + 1
	$result = 0
Until ControlShow($activeWindowTitle, "", "Button1") = 1

Local $click;
If (ControlShow($activeWindowTitle, "", "Button1") = 1) Then
   $click = ControlClick($activeWindowTitle, "", "[CLASS:Button; INSTANCE:1]")
   $result = 0
   _FileWriteLog($hFile, "$clickDefault='" & $click & "'")
ElseIf (ControlShow($activeWindowTitle, "", "Button2") = 1) Then
   $click = ControlClick($activeWindowTitle, "", "[CLASS:Button; INSTANCE:2]") ;Pentru browserul straniu de la BeGlobal
   $result = 0
   _FileWriteLog($hFile, "$clickStraniu='" & $click =  & "'")
Else
   $result = 1
   _FileWriteLog($hFile, "Error! Nu am gasit nici un button!!!!")
EndIf
Sleep(300)
$close = WinWaitClose($activeWindowTitle, "", 3)
_FileWriteLog($hFile, "win='" & $activeWindowTitle & "'")
_FileWriteLog($hFile, "$close='" & $close & "'")
_FileWriteLog($hFile, "$result='" & $result & "'")
_FileWriteLog($hFile, "------------------------- New Upload --------------------------")
FileClose($hFile)
Exit $result


cleanup

cleanup


comments

comments

#cs ----------------------------------------------------------------------------

 AutoIt Version: 3.3.16.0
 Author:         karlh@google.com

 Script Function:
	Start event streams

#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here
#include <MsgBoxConstants.au3>
#include <Debug.au3>

#include "importeventlogs.au3"

_DebugSetup("Start", True)
ConsoleWrite("starting" & @CRLF)
ConsoleWrite("@CPUArch: " & @CPUArch & @CRLF)

_DebugSetup("DllCall", True)

Local $ret = StreamLogs("c:\temp\")
if $ret Then
	ConsoleWrite("Error starting" & @CRLF)
	Exit (1)
EndIf

; run test for 10 seconds and exit
sleep(10 * 1000)

ConsoleWrite("exit" & @CRLF)

#cs ----------------------------------------------------------------------------

 AutoIt Version: 3.3.16.0
 Author:         karlh@

 Script Function:
	Start event streams

#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here
#include <MsgBoxConstants.au3>
#include <Debug.au3>

#include "importeventlogs.au3"

;MsgBox(0, "", "@AutoItVersion: " & AutoItVersion & ", @CPUArch: " & @CPUArch)
_DebugSetup("Start", True)
ConsoleWrite("starting" & @CRLF)
ConsoleWrite("@CPUArch: " & @CPUArch & @CRLF)

_DebugSetup("DllCall", True)

Local $ret = StreamLogs("c:\temp\")
if $ret Then
	ConsoleWrite("Error starting" & @CRLF)
	Exit (1)
EndIf

sleep(10 * 1000)

; MsgBox($MB_OK, "Tutorial", "done")
ConsoleWrite("exit" & @CRLF)


Update Exemplo_01.au3

Update Exemplo_01.au3

;~ #AutoIt3Wrapper_AU3Check_Parameters= -q -d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
;~ #Tidy_Parameters=/sf

; #SCRIPT#== ====================================================================================================================
; Description ...: Exemplo de movimentação de um item entre duas ListView
; Author ........: Luigi (Luismar Chechelaky)
; Link ..........: https://github.com/chechelaky/AutoIt/edit/master/Diversos/ListView/Exemplo_01.au3
; AutoIt version.: 3.3.12.0
; ===============================================================================================================================

#include-once
#include <Array.au3>
#include <GUIConstantsEx.au3>
#include <ComboConstants.au3>
#include <GuiListView.au3>
#include <GuiImageList.au3>
#include <WindowsConstants.au3>
#include <GuiComboBoxEx.au3>

OnAutoItExitRegister("OnExit")

Opt("GUIOnEventMode", 1)
Opt("GUIEventOptions", 1)
Opt("MustDeclareVars", 1)

Global $aGuiSize[2] = [510, 380]
Global $sGuiTitle = "GuiTitle"
Global $hGui
Global $iListView1, $iListView2
Global $hListView1, $hListView2

$hGui = GUICreate($sGuiTitle, $aGuiSize[0], $aGuiSize[1])
GUISetOnEvent($GUI_EVENT_CLOSE, "Quit")

$iListView1 = GUICtrlCreateListView("Nome", 10, 10, 240, 360)
$hListView1 = GUICtrlGetHandle($iListView1)
_GUICtrlListView_SetColumnWidth($iListView1, 0, 235)
GUICtrlCreateListViewItem("aaa", $iListView1)
GUICtrlCreateListViewItem("bbb", $iListView1)
GUICtrlCreateListViewItem("ccc", $iListView1)
GUICtrlCreateListViewItem("ddd", $iListView1)
GUICtrlCreateListViewItem("eee", $iListView1)

$iListView2 = GUICtrlCreateListView("Nome", 260, 10, 240, 360)
$hListView2 = GUICtrlGetHandle($iListView2)
_GUICtrlListView_SetColumnWidth($iListView2, 0, 235)

GUISetState(@SW_SHOW, $hGui)
GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY")

While Sleep(25)
WEnd

Func OnExit()
	GUISetState($hGui, @SW_HIDE)
	GUIDelete($hGui)
EndFunc   ;==>OnExit

Func Quit()
	Exit
EndFunc   ;==>Quit

Func ListViewMove($from, $to, $mode = False) ; true = insert / false = delete
	Local $index = _GUICtrlListView_GetHotItem($from)
	If $index = -1 Then Return
	Local $text = _GUICtrlListView_GetItemText($from, $index)
	_GUICtrlListView_DeleteItem($from, $index)
	_GUICtrlListView_AddItem($to, $text)
	Local $bSort = False
	_GUICtrlListView_SimpleSort($to, $bSort, 0)
	$bSort = False
	_GUICtrlListView_SimpleSort($from, $bSort, 0)
EndFunc   ;==>ListViewMove

Func WM_NOTIFY($hWnd, $iMsg, $wParam, $lParam)
	#forceref $hWnd, $iMsg, $wParam
	Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR, $tInfo

	$tNMHDR = DllStructCreate($tagNMHDR, $lParam)
	$hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))
	$iIDFrom = DllStructGetData($tNMHDR, "IDFrom")
	$iCode = DllStructGetData($tNMHDR, "Code")
	Switch $hWndFrom
		Case $hListView1
			Switch $iCode
				Case $NM_DBLCLK
					ListViewMove($hListView1, $hListView2, True)
			EndSwitch

		Case $hListView2
			Switch $iCode
				Case $NM_DBLCLK
					ListViewMove($hListView2, $hListView1, False)
			EndSwitch
	EndSwitch
	Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY

;~ #AutoIt3Wrapper_AU3Check_Parameters= -q -d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
;~ #Tidy_Parameters=/sf

#include-once
#include <Array.au3>
#include <GUIConstantsEx.au3>
#include <ComboConstants.au3>
#include <GuiListView.au3>
#include <GuiImageList.au3>
#include <WindowsConstants.au3>
#include <GuiComboBoxEx.au3>

OnAutoItExitRegister("OnExit")

Opt("GUIOnEventMode", 1)
Opt("GUIEventOptions", 1)
Opt("MustDeclareVars", 1)

Global $aGuiSize[2] = [510, 380]
Global $sGuiTitle = "GuiTitle"
Global $hGui
Global $iListView1, $iListView2
Global $hListView1, $hListView2

$hGui = GUICreate($sGuiTitle, $aGuiSize[0], $aGuiSize[1])
GUISetOnEvent($GUI_EVENT_CLOSE, "Quit")

$iListView1 = GUICtrlCreateListView("Nome", 10, 10, 240, 360)
$hListView1 = GUICtrlGetHandle($iListView1)
_GUICtrlListView_SetColumnWidth($iListView1, 0, 235)
GUICtrlCreateListViewItem("aaa", $iListView1)
GUICtrlCreateListViewItem("bbb", $iListView1)
GUICtrlCreateListViewItem("ccc", $iListView1)
GUICtrlCreateListViewItem("ddd", $iListView1)
GUICtrlCreateListViewItem("eee", $iListView1)

$iListView2 = GUICtrlCreateListView("Nome", 260, 10, 240, 360)
$hListView2 = GUICtrlGetHandle($iListView2)
_GUICtrlListView_SetColumnWidth($iListView2, 0, 235)

GUISetState(@SW_SHOW, $hGui)
GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY")

While Sleep(25)
WEnd

Func OnExit()
	GUISetState($hGui, @SW_HIDE)
	GUIDelete($hGui)
EndFunc   ;==>OnExit

Func Quit()
	Exit
EndFunc   ;==>Quit

Func ListViewMove($from, $to, $mode = False) ; true = insert / false = delete
	Local $index = _GUICtrlListView_GetHotItem($from)
	If $index = -1 Then Return
	Local $text = _GUICtrlListView_GetItemText($from, $index)
	_GUICtrlListView_DeleteItem($from, $index)
	_GUICtrlListView_AddItem($to, $text)
	Local $bSort = False
	_GUICtrlListView_SimpleSort($to, $bSort, 0)
	$bSort = False
	_GUICtrlListView_SimpleSort($from, $bSort, 0)
EndFunc   ;==>ListViewMove

Func WM_NOTIFY($hWnd, $iMsg, $wParam, $lParam)
	#forceref $hWnd, $iMsg, $wParam
	Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR, $tInfo

	$tNMHDR = DllStructCreate($tagNMHDR, $lParam)
	$hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))
	$iIDFrom = DllStructGetData($tNMHDR, "IDFrom")
	$iCode = DllStructGetData($tNMHDR, "Code")
	Switch $hWndFrom
		Case $hListView1
			Switch $iCode
				Case $NM_DBLCLK
					ListViewMove($hListView1, $hListView2, True)
			EndSwitch

		Case $hListView2
			Switch $iCode
				Case $NM_DBLCLK
					ListViewMove($hListView2, $hListView1, False)
			EndSwitch
	EndSwitch
	Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY


format

format

Global $stream_dll_hand

Func StreamWinEventLogs($output_dir = "c:\temp\")
	 ; Start streaming logs
	 ConsoleWrite("StreamLogs" & @CRLF)

	$stream_dll_hand = DllOpen("event-stream.dll")
	ConsoleWrite("dll handle  " & $stream_dll_hand  & @CRLF)
	if $stream_dll_hand < 0 Then
		ConsoleWrite("Error opening dll " & $stream_dll_hand  & @CRLF)
		return $stream_dll_hand
	EndIf

	Local $ret = DllCall ( $stream_dll_hand, "int:cdecl", "StartStreamEventsThread", "WSTR", "Microsoft-Windows-Sysmon/Operational", "WSTR", $output_dir & "Microsoft-Windows-SysmonOperational.xml")
	if $ret Then
		ConsoleWrite("error sysmon " & $ret  & @CRLF)
		return $ret
	Endif

	$ret = DllCall ( $stream_dll_hand, "int:cdecl", "StartStreamEventsThread", "WSTR", "System", "WSTR",  $output_dir &  "System.xml")
	if $ret Then
		ConsoleWrite("error System " & $ret  & @CRLF)
		return $ret
	Endif

	$ret = DllCall ( $stream_dll_hand, "int:cdecl", "StartStreamEventsThread", "WSTR", "Application", "WSTR",  $output_dir &  "Application.xml")
	if $ret Then
		ConsoleWrite("error Application " & $ret  & @CRLF)
		return $ret
	Endif

	$ret = DllCall ( $stream_dll_hand, "int:cdecl", "StartStreamEventsThread", "WSTR", "Security", "WSTR",  $output_dir &  "Security.xml")
	if $ret Then
		ConsoleWrite("error Application " & $ret  & @CRLF)
		return $ret
	Endif

	$ret = DllCall ( $stream_dll_hand, "int:cdecl", "StartStreamEventsThread", "WSTR", "Windows Powershell", "WSTR",  $output_dir &  "Microsoft-Windows-PowershellOperational.xml")
	if $ret Then
		ConsoleWrite("error powershell " & $ret  & @CRLF)
		return $ret
	Endif

	return 0
EndFunc

Func StopStreamWinEventLogs()
	DllClose($stream_dll_hand)
EndFunc