remove RunProgramsOnAccessControlServer

remove RunProgramsOnAccessControlServer

... the correct way to make programs secured by ACS's is to run the "verify" command as root apparently, not to actually start them (even tho that works as well)

#include <Array.au3>
#include <SQLite.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <AutoItConstants.au3>
#include <FontConstants.au3>
#include <MsgBoxConstants.au3>
#include <GuiListBox.au3>
#include <File.au3>
#include <String.au3>

HotKeySet("{PGUP}","WriteTransferMoney");
HotKeySet("{PGDN}","ParseBankLogs");
Func Paste()
   Sleep(1*500);
   Send(ClipGet());
EndFunc
Func init()
   _SQLite_Startup() ; Load the DLL
   If @error Then Exit MsgBox($MB_SYSTEMMODAL, "SQLite Error", "error loading SQLite3.dll ! you can download it from https://www.sqlite.org/download.html , look for ""Precompiled Binaries for Windows"", should be named something like sqlite-dll-win32-x86-3220000.zip");
;why this isn't the default beats me...
   AutoItSetOption("MouseClickDelay",0);
   AutoItSetOption("MouseClickDownDelay",0);
   AutoItSetOption("MouseClickDragDelay",0);
   AutoItSetOption("SendKeyDelay",1);
   AutoItSetOption("SendKeyDownDelay",1);
   AutoItSetOption("WinWaitDelay",0);
   AutoItSetOption("MustDeclareVars",1);
   Global $playerDB=selectPlayer();
   Global $db=_SQLite_Open ( $playerDB,$SQLITE_OPEN_READWRITE, $SQLITE_ENCODING_UTF8 );
   If @error Then Exit MsgBox($MB_SYSTEMMODAL, "SQLite Error", "error loading " & $playerDB & " ! (_SQLite_Open failed, and i'm too lazy to add proper error description code atm)");
EndFunc
Func selectPlayer()
Local $FileList=_FileListToArray(@AppDataDir & "\Onlink\users\","*.db");
Local $GUI = GUICreate("Select agent", 300, 300) ;create gui
Local $ListBox = _GUICtrlListBox_Create($GUI, "", 0, 0,300,300) ;create listbox
For $i = 1 To $FileList[0]
    ;MsgBox(0, $i, $FileList[$i])
    _GUICtrlListBox_AddString($ListBox, StringReplace($FileList[$i],".db","",-1) )
Next

GUISetState() ;show the gui
WinSetOnTop($GUI,"",$WINDOWS_ONTOP);
Local $selected=-1
Do
   Sleep(100);
   $selected=_GUICtrlListBox_GetCurSel ( $ListBox );
Until $selected <> -1;
Local $ret=@AppDataDir & "\Onlink\users\" & _GUICtrlListBox_GetText($ListBox,$selected) & ".db";
ConsoleWriteError($ret);
GUIDelete() ; if autoit expect me to clean up all inner gui controls myself, and this technically leaks memory, here is a list of all the f*ks i give:
Return $ret;
EndFunc

Func SplashMessage($title,$message, $timeoutMS=500)
   Return 0;not working with onlink, onlink overrides WinSetOnTop, apparently...
	  Local $size=50+(StringLen($message)*15);
	  Local $hwnd=SplashTextOn($title, $message, $size, $size, -1, -1, $DLG_TEXTLEFT, "", 24)
	  WinSetOnTop($hwnd,"",$WINDOWS_ONTOP);
	  Sleep($timeoutMS);
	  SplashOff()
   EndFunc

Func e_SQLite_GetTable2d ( $hDB, $sSQL, ByRef $aResult, ByRef $iRows, ByRef $iColumns, $iCharSize = -1, $bSwichDimensions = False )
   if( _SQLite_GetTable2d ( $hDB, $sSQL,$aResult, $iRows,$iColumns, $iCharSize, $bSwichDimensions ) <> $SQLITE_OK) Then
	  Exit MsgBox(0,"SQL error","error executing: " & $sSql );
   EndIf

EndFunc

Func WriteTransferMoney()
   Local $aResult, $iRows, $iColumns;
   local $connectedIp;
   Send("{tab}" & _StringRepeat("{BACKSPACE}",30) & "waiting for db flush, hold on...");
   Do
	  sleep(100);
	  e_SQLite_GetTable2d($db, 'SELECT remotehost FROM player LIMIT 1', $aResult, $iRows, $iColumns) ;
	  $connectedIp=$aResult[1][0];
	  ; get player's account for current bank:
      e_SQLite_GetTable2d($db, 'SELECT SUBSTR(content,LENGTH((SELECT remotehost FROM player LIMIT 1))+2) FROM accounts WHERE content LIKE (SELECT remotehost FROM player LIMIT 1) || '' %'' AND suP_ref LIKE ''%(player)'' LIMIT 1',$aResult, $iRows, $iColumns) ;
	  ;_ArrayDisplay($aResult, "Results from the query");
	  ;ConsoleWrite(UBound($aResult) & @CRLF);
   Until (UBound($aResult) == 2) ; waiting for the game to flush db after entering transfer money screen.. sometimes it takes a few seconds.
   ;_ArrayDisplay($aResult, "Results from the query")
   ;_ArrayDisplay($aResult, "Results from the query");
   local $playerAccountNumber=$aResult[1][0];
   ;ConsoleWrite($playerAccount  & @CRLF );
   e_SQLite_GetTable2d($db, 'SELECT bankaccount.balance FROM bankaccount WHERE bankaccount.accountnumber=(SELECT remote.security_name FROM remote)',$aResult, $iRows, $iColumns) ;
   ;_ArrayDisplay($aResult, "Results from the query");
   Local $connectedAccountBalance=$aResult[1][0];
   e_SQLite_GetTable2d($db, 'SELECT remote.security_name FROM remote WHERE id=1',$aResult, $iRows, $iColumns) ;
   Local $connectedAccountNumber=$aResult[1][0];
   Send(_StringRepeat("{BACKSPACE}",33) & $connectedAccountNumber &  "{tab}" & $connectedIp & "{tab}" & $playerAccountNumber & "{tab}" & $connectedAccountBalance);
; get current connected bank account number: SELECT remote.security_name WHERE id=1

; get balance of current connected bank account: SELECT bankaccount.balance FROM bankaccount WHERE bankaccount.accountnumber=(SELECT remote.security_name FROM remote)

EndFunc
Func ParseBankLogs()
   Local $aResult, $iRows, $iColumns;
   local $connectedIp;
   ;Send("{tab}" & _StringRepeat("{BACKSPACE}",15) & "waiting for db flush, hold on...");
   Do
	  sleep(100);
	  e_SQLite_GetTable2d($db, 'SELECT remotehost FROM player LIMIT 1', $aResult, $iRows, $iColumns) ;
	  $connectedIp=$aResult[1][0];
	  ; get player's account for current bank:
      e_SQLite_GetTable2d($db, 'SELECT SUBSTR(content,LENGTH((SELECT remotehost FROM player LIMIT 1))+2) FROM accounts WHERE content LIKE (SELECT remotehost FROM player LIMIT 1) || '' %'' AND suP_ref LIKE ''%(player)'' LIMIT 1',$aResult, $iRows, $iColumns) ;
	  ;_ArrayDisplay($aResult, "Results from the query");
	  ;ConsoleWrite(UBound($aResult) & @CRLF);
   Until (UBound($aResult) == 2) ; waiting for the game to flush db after entering transfer money screen.. sometimes it takes a few seconds.
   ; current connected account number: SELECT remote.security_name FROM remote WHERE id=1
   ; logbank: SELECT logbank FROM bankaccount WHERE accountnumber = (SELECT remote.security_name FROM remote WHERE id=1)
   ; logs: SELECT data1,data2,data3,date,fromip,fromname FROM accesslog WHERE sup_ref = ((SELECT logbank FROM bankaccount WHERE accountnumber = (SELECT remote.security_name FROM remote WHERE id=1)) || ''(logbank)'')
   e_SQLite_GetTable2d($db,'SELECT data1 FROM accesslog WHERE sup_ref = ((SELECT logbank FROM bankaccount WHERE accountnumber = (SELECT remote.security_name FROM remote WHERE id=1)) || ''(logbank)'')',$aResult, $iRows, $iColumns);
   ;_ArrayDisplay($aResult, "Results from the query");
   Local $cur, $curL, $matchIp, $matchAccount, $sql, $aResult2,$iRows2,$iColumns2;
   For $i = 1 To $iRows Step 1
	  $curL=$aResult[$i][0];
	  ;ConsoleWrite($cur & @CRLF);
	  $cur=StringRegExp($curL,"^(\d+\.\d+\.\d+\.\d+)\ (\d+)$",$STR_REGEXPARRAYMATCH);
	  if @error Then ContinueLoop
	  $matchIp=$cur[0];
	  $matchAccount=$cur[1];
	  ;ConsoleWrite($matchIp & " - " & $matchAccount & @CRLF);
	  e_SQLite_GetTable2d($db,'SELECT * FROM accesscodes WHERE key = ' & _SQLite_Escape($curL) & ' AND sup_ref = ''1(player)''',$aResult2, $iRows2, $iColumns2);
	  ;_ArrayDisplay($aResult2, "Results from the query");
	  ConsoleWrite($iRows2);

	  if($iRows2 > 0) Then ContinueLoop
	  $sql='INSERT INTO accesscodes (content,key,sup_ref) VALUES(''?'', ' & _SQLite_Escape($curL) & ', ''1(player)'');';
	  if(_SQLite_Exec($db,$sql) <> $SQLITE_OK) Then
		 ; sigh...
		Exit MsgBox(0,"error","SQLite error executing " & $sql);
	  EndIf
   Next
   Beep();
EndFunc

init();
While 1
   Sleep(100);
WEnd

#include <Array.au3>
#include <SQLite.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <AutoItConstants.au3>
#include <FontConstants.au3>
#include <MsgBoxConstants.au3>
#include <GuiListBox.au3>
#include <File.au3>
#include <String.au3>

HotKeySet("{PGUP}","WriteTransferMoney");
HotKeySet("{PGDN}","ParseBankLogs");
HotKeySet("{END}","RunProgramsOnAccessControlServer"); i'm just making up these hotkeys as i need em, there's no logic to it.
Func Paste()
   Sleep(1*500);
   Send(ClipGet());
EndFunc
Func init()
   _SQLite_Startup() ; Load the DLL
   If @error Then Exit MsgBox($MB_SYSTEMMODAL, "SQLite Error", "error loading SQLite3.dll ! you can download it from https://www.sqlite.org/download.html , look for ""Precompiled Binaries for Windows"", should be named something like sqlite-dll-win32-x86-3220000.zip");
;why this isn't the default beats me...
   AutoItSetOption("MouseClickDelay",0);
   AutoItSetOption("MouseClickDownDelay",0);
   AutoItSetOption("MouseClickDragDelay",0);
   AutoItSetOption("SendKeyDelay",1);
   AutoItSetOption("SendKeyDownDelay",1);
   AutoItSetOption("WinWaitDelay",0);
   AutoItSetOption("MustDeclareVars",1);
   Global $playerDB=selectPlayer();
   Global $db=_SQLite_Open ( $playerDB,$SQLITE_OPEN_READWRITE, $SQLITE_ENCODING_UTF8 );
   If @error Then Exit MsgBox($MB_SYSTEMMODAL, "SQLite Error", "error loading " & $playerDB & " ! (_SQLite_Open failed, and i'm too lazy to add proper error description code atm)");
EndFunc
Func selectPlayer()
Local $FileList=_FileListToArray(@AppDataDir & "\Onlink\users\","*.db");
Local $GUI = GUICreate("Select agent", 300, 300) ;create gui
Local $ListBox = _GUICtrlListBox_Create($GUI, "", 0, 0,300,300) ;create listbox
For $i = 1 To $FileList[0]
    ;MsgBox(0, $i, $FileList[$i])
    _GUICtrlListBox_AddString($ListBox, StringReplace($FileList[$i],".db","",-1) )
Next

GUISetState() ;show the gui
WinSetOnTop($GUI,"",$WINDOWS_ONTOP);
Local $selected=-1
Do
   Sleep(100);
   $selected=_GUICtrlListBox_GetCurSel ( $ListBox );
Until $selected <> -1;
Local $ret=@AppDataDir & "\Onlink\users\" & _GUICtrlListBox_GetText($ListBox,$selected) & ".db";
ConsoleWriteError($ret);
GUIDelete() ; if autoit expect me to clean up all inner gui controls myself, and this technically leaks memory, here is a list of all the f*ks i give:
Return $ret;
EndFunc

Func SplashMessage($title,$message, $timeoutMS=500)
   Return 0;not working with onlink, onlink overrides WinSetOnTop, apparently...
	  Local $size=50+(StringLen($message)*15);
	  Local $hwnd=SplashTextOn($title, $message, $size, $size, -1, -1, $DLG_TEXTLEFT, "", 24)
	  WinSetOnTop($hwnd,"",$WINDOWS_ONTOP);
	  Sleep($timeoutMS);
	  SplashOff()
   EndFunc

Func e_SQLite_GetTable2d ( $hDB, $sSQL, ByRef $aResult, ByRef $iRows, ByRef $iColumns, $iCharSize = -1, $bSwichDimensions = False )
   if( _SQLite_GetTable2d ( $hDB, $sSQL,$aResult, $iRows,$iColumns, $iCharSize, $bSwichDimensions ) <> $SQLITE_OK) Then
	  Exit MsgBox(0,"SQL error","error executing: " & $sSql );
   EndIf

EndFunc

Func WriteTransferMoney()
   Local $aResult, $iRows, $iColumns;
   local $connectedIp;
   Send("{tab}" & _StringRepeat("{BACKSPACE}",30) & "waiting for db flush, hold on...");
   Do
	  sleep(100);
	  e_SQLite_GetTable2d($db, 'SELECT remotehost FROM player LIMIT 1', $aResult, $iRows, $iColumns) ;
	  $connectedIp=$aResult[1][0];
	  ; get player's account for current bank:
      e_SQLite_GetTable2d($db, 'SELECT SUBSTR(content,LENGTH((SELECT remotehost FROM player LIMIT 1))+2) FROM accounts WHERE content LIKE (SELECT remotehost FROM player LIMIT 1) || '' %'' AND suP_ref LIKE ''%(player)'' LIMIT 1',$aResult, $iRows, $iColumns) ;
	  ;_ArrayDisplay($aResult, "Results from the query");
	  ;ConsoleWrite(UBound($aResult) & @CRLF);
   Until (UBound($aResult) == 2) ; waiting for the game to flush db after entering transfer money screen.. sometimes it takes a few seconds.
   ;_ArrayDisplay($aResult, "Results from the query")
   ;_ArrayDisplay($aResult, "Results from the query");
   local $playerAccountNumber=$aResult[1][0];
   ;ConsoleWrite($playerAccount  & @CRLF );
   e_SQLite_GetTable2d($db, 'SELECT bankaccount.balance FROM bankaccount WHERE bankaccount.accountnumber=(SELECT remote.security_name FROM remote)',$aResult, $iRows, $iColumns) ;
   ;_ArrayDisplay($aResult, "Results from the query");
   Local $connectedAccountBalance=$aResult[1][0];
   e_SQLite_GetTable2d($db, 'SELECT remote.security_name FROM remote WHERE id=1',$aResult, $iRows, $iColumns) ;
   Local $connectedAccountNumber=$aResult[1][0];
   Send(_StringRepeat("{BACKSPACE}",33) & $connectedAccountNumber &  "{tab}" & $connectedIp & "{tab}" & $playerAccountNumber & "{tab}" & $connectedAccountBalance);
; get current connected bank account number: SELECT remote.security_name WHERE id=1

; get balance of current connected bank account: SELECT bankaccount.balance FROM bankaccount WHERE bankaccount.accountnumber=(SELECT remote.security_name FROM remote)

EndFunc
Func ParseBankLogs()
   Local $aResult, $iRows, $iColumns;
   local $connectedIp;
   ;Send("{tab}" & _StringRepeat("{BACKSPACE}",15) & "waiting for db flush, hold on...");
   Do
	  sleep(100);
	  e_SQLite_GetTable2d($db, 'SELECT remotehost FROM player LIMIT 1', $aResult, $iRows, $iColumns) ;
	  $connectedIp=$aResult[1][0];
	  ; get player's account for current bank:
      e_SQLite_GetTable2d($db, 'SELECT SUBSTR(content,LENGTH((SELECT remotehost FROM player LIMIT 1))+2) FROM accounts WHERE content LIKE (SELECT remotehost FROM player LIMIT 1) || '' %'' AND suP_ref LIKE ''%(player)'' LIMIT 1',$aResult, $iRows, $iColumns) ;
	  ;_ArrayDisplay($aResult, "Results from the query");
	  ;ConsoleWrite(UBound($aResult) & @CRLF);
   Until (UBound($aResult) == 2) ; waiting for the game to flush db after entering transfer money screen.. sometimes it takes a few seconds.
   ; current connected account number: SELECT remote.security_name FROM remote WHERE id=1
   ; logbank: SELECT logbank FROM bankaccount WHERE accountnumber = (SELECT remote.security_name FROM remote WHERE id=1)
   ; logs: SELECT data1,data2,data3,date,fromip,fromname FROM accesslog WHERE sup_ref = ((SELECT logbank FROM bankaccount WHERE accountnumber = (SELECT remote.security_name FROM remote WHERE id=1)) || ''(logbank)'')
   e_SQLite_GetTable2d($db,'SELECT data1 FROM accesslog WHERE sup_ref = ((SELECT logbank FROM bankaccount WHERE accountnumber = (SELECT remote.security_name FROM remote WHERE id=1)) || ''(logbank)'')',$aResult, $iRows, $iColumns);
   ;_ArrayDisplay($aResult, "Results from the query");
   Local $cur, $curL, $matchIp, $matchAccount, $sql, $aResult2,$iRows2,$iColumns2;
   For $i = 1 To $iRows Step 1
	  $curL=$aResult[$i][0];
	  ;ConsoleWrite($cur & @CRLF);
	  $cur=StringRegExp($curL,"^(\d+\.\d+\.\d+\.\d+)\ (\d+)$",$STR_REGEXPARRAYMATCH);
	  if @error Then ContinueLoop
	  $matchIp=$cur[0];
	  $matchAccount=$cur[1];
	  ;ConsoleWrite($matchIp & " - " & $matchAccount & @CRLF);
	  e_SQLite_GetTable2d($db,'SELECT * FROM accesscodes WHERE key = ' & _SQLite_Escape($curL) & ' AND sup_ref = ''1(player)''',$aResult2, $iRows2, $iColumns2);
	  ;_ArrayDisplay($aResult2, "Results from the query");
	  ConsoleWrite($iRows2);

	  if($iRows2 > 0) Then ContinueLoop
	  $sql='INSERT INTO accesscodes (content,key,sup_ref) VALUES(''?'', ' & _SQLite_Escape($curL) & ', ''1(player)'');';
	  if(_SQLite_Exec($db,$sql) <> $SQLITE_OK) Then
		 ; sigh...
		Exit MsgBox(0,"error","SQLite error executing " & $sql);
	  EndIf
   Next
   Beep();
EndFunc

Func RunProgramsOnAccessControlServer()
   ; Denial is not included.
   Local $args=[ _
	  "run File_Copier", _
	  "run Proxy_Killer", _
	  "run Firewall_Bypass", _
	  "run Password_Breaker", _
	  "run Decypher", _
	  "run B.Monitor_Killer", _
	  "run File_Deleter", _
	  "run Log_Deleter", _
	  "run Sentry_Bypass", _
	  "run Encryption_Bypass", _
	  "run Proxy_Bypass", _
	  "run Gateway_Nuke", _
	  "run Motion_Sensor", _
	  "run Defrag", _
	  "run Decrypter", _
	  "run Encrypter", _
	  "run PC_AdminMenuInject", _
	  "run PC_ConsoleEnable", _
	  "run PC_LoginEnable", _
	  "run PC_MainMenuInject", _
	  "run PC_md2Crack", _
	  "run PC_md4Crack", _
	  "run PC_md5Crack", _
	  "run PC_SHA-512Crack", _
	  "run B.Monitor_Bypass", _
	  "run Compressor", _
	  "run Decompressor", _
	  "run Encrypter", _
	  "run LAN_Agent", _
	  "run Log_UnDeleter", _
	  "run Voice_Analyser", _
	  "run IP_Lookup", _
	  "run IP_Probe", _
	  "run LAN_Probe", _
	  "run LAN_Scan", _
	  "run LAN_Spoof", _
	  "run LAN_Force", _
	  "run Trace_Tracker", _
	  "run Monitor_Bypass", _
	  "run LAN_Spike", _
	  "run VDPIN_Cracker", _
	  "run Encryption_Killer", _
	  "run Firewall_Killer", _
	  "run Sentry_Killer", _
	  "run Log_Modifier" _
   ];
   Local $iMax = UBound($args)
   Send("dir{ENTER}");
   Sleep(200);
   For $i = 0 to $iMax - 1;
	  Send($args[$i] & "{ENTER}");
	  sleep(60);
   Next
EndFunc

init();
While 1
   Sleep(100);
WEnd


inform active alerts

inform active alerts

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return true
	EndFunc
	Func SQLInsertUser($UserID,$Fname,$Lname,$epoch,$active=1)
		ConsoleWrite('  Nuevo usuario = '& $Fname & "  "  & $Lname  & @crlf)
		$query='INSERT INTO Users VALUES (' & $UserID & ',"' & $Fname & '","' & $Lname & '",' & $active &',0,' & $epoch & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting User ErrNo 1011" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLUpdateUserActive($UserID,$Fname,$Lname,$active=1)
		ConsoleWrite('    Usuario Activo 1/Start 0/Stop= '&$active& "  " & $Fname & "  "  & $Lname  & @crlf)
		$query='UPDATE  Users SET Active=' & $active &' WHERE UserID='& $UserID & ' ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			ConsoleWrite("       Error updating active user User ErrNo 1012" & @CRLF & $query& @crlf)
			Return false
		EndIf
	EndFunc
	Func SQLExistUser($UserID)
;~ 	ConsoleWrite('++SQLExistUser() = '& @crlf)
		$query='SELECT UserID FROM Users WHERE UserID="'&$UserID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
	Func SQLUpdateUserAlerts($UserID,$mensage)
		$mensage=StringReplace($mensage,"callback_query ","")
		$msgArr=StringSplit($mensage,"_")
		_printfromarray($msgArr)
		$active=0
		if $msgArr[2]="ON" then $active=1
		$query='UPDATE AlertasLineas SET ' & $msgArr[1] & '=' & $active & ' WHERE userid=' & $UserID & ';   '
		$query&='INSERT INTO AlertasLineas (userid,' & $msgArr[1] & ')  SELECT ' & $UserID & ',' & $active &' WHERE (Select Changes() = 0);'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			ConsoleWrite("!    Error updating alertasLineas User ErrNo 1013" & @CRLF & $query& @crlf)
			Return false
		EndIf
	EndFunc
#endregion
#region   ===================================   keyboard   ==========================
	;============== show keyboard =========================
	func KeyboardActivate($UserID)
		$keybrd =  '{"inline_keyboard":['
		$keybrd &= '['
		$keybrd &= '{"text":"Linea A","callback_data":"A_ON"},'
		$keybrd &= '{"text":"Linea B","callback_data":"B_ON"},'
		$keybrd &= '{"text":"Linea C","callback_data":"C_ON"}'
		$keybrd &= '],['
		$keybrd &= '{"text":"Linea D","callback_data":"D_ON"},'
		$keybrd &= '{"text":"Linea E","callback_data":"E_ON"},'
		$keybrd &= '{"text":"Linea H","callback_data":"H_ON"}'
		$keybrd &= '],['
		$keybrd &= '{"text":"Linea P","callback_data":"P_ON"},'
		$keybrd &= '{"text":"Linea U","callback_data":"U_ON"},'
		$keybrd &= '{"text":"Listo","callback_data":"CLOSE_ON"}'
		$keybrd &= '],['
		$keybrd &= ']'
		$keybrd &= ']}'
		$alertasactivas=SQLGetAlertLines($UserID)
		$res=_SendMsg($UserID,"Sus alertas activas:"& $alertasactivas & $nuevaLinea & "Cual desea activar?","HTML",$keybrd)
		$MSGID=StringRegExp($res,'"message_id":(.*?),"from":',1)
		$UsrID=StringRegExp($res,',"chat":{"id":(.*?),"first_name":',1)
		$utime=StringRegExp($res,',"date":(.*?),"text":',1)
		if IsArray($MSGID) then	SQLregisterKeyboard($UsrID[0],$MsgID[0],$utime[0])
		if $res then return True
		return false
	EndFunc
	func KeyboardDesActivate($UserID)
		$keybrd =  '{"inline_keyboard":['
		$keybrd &= '['
		$keybrd &= '{"text":"Linea A","callback_data":"A_OFF"},'
		$keybrd &= '{"text":"Linea B","callback_data":"B_OFF"},'
		$keybrd &= '{"text":"Linea C","callback_data":"C_OFF"}'
		$keybrd &= '],['
		$keybrd &= '{"text":"Linea D","callback_data":"D_OFF"},'
		$keybrd &= '{"text":"Linea E","callback_data":"E_OFF"},'
		$keybrd &= '{"text":"Linea H","callback_data":"H_OFF"}'
		$keybrd &= '],['
		$keybrd &= '{"text":"Linea P","callback_data":"P_OFF"},'
		$keybrd &= '{"text":"Linea U","callback_data":"U_OFF"},'
		$keybrd &= '{"text":"Listo","callback_data":"CLOSE_OFF"}'
		$keybrd &= '],['
		$keybrd &= ']'
		$keybrd &= ']}'
		$alertasactivas=SQLGetAlertLines($UserID)
		$res=_SendMsg($UserID,"Sus alertas activas:"& $alertasactivas & $nuevaLinea & "Cual desea desactivar?","HTML",$keybrd)
		$MSGID=StringRegExp($res,'"message_id":(.*?),"from":',1)
		$UsrID=StringRegExp($res,',"chat":{"id":(.*?),"first_name":',1)
		$utime=StringRegExp($res,',"date":(.*?),"text":',1)
		if IsArray($MSGID) then	SQLregisterKeyboard($UsrID[0],$MsgID[0],$utime[0])
		if $res then return True
		return false
	EndFunc
	Func SQLGetAlertLines($UserID)
		$query='select * from AlertasLineas WHERE UserID=' & $UserID & ' ;'
		_SQLITEqry($query,$dbfullPath)
		_printfromarray($qryResult)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				$lineasactivas=" "
				for $i=1 to UBound($qryResult,2)-1
					if $qryResult[1][$i]=1 then
						$lineasactivas &=$qryResult[0][$i] & " "
					endif
				next
				return $lineasactivas
			EndIf
		endif
	EndFunc
	Func SQLregisterKeyboard($UserID,$MsgID,$epoch)
		$query='INSERT INTO Keyboard VALUES (' & $UserID & ',' & $MsgID  & ',' & $epoch & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			$KeyBoardActive=1
			$ahora=0.2
			return true
		endif
		Return false
	EndFunc
	;==================   limpiar keyboard  =====================
	Func ClearKeyBoards()
		$query='SELECT UserID,MsgID FROM Keyboard WHERE Timestamp < ' & _GetUnixTime()-60 & ';'
		_SQLITEqry($query,$dbfullPath)
		_printfromarray($qryResult)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				for $i=1 to UBound($qryResult)-1
					_DeleteMsg( $qryResult[$i][0],$qryResult[$i][1])
					SQLUnRegisterKeyboard($qryResult[$i][0],$qryResult[$i][1])
					$ahora=1
				next
			EndIf
		endif
	EndFunc
	Func SQLUnRegisterKeyboard($UserID,$MsgID)
		$query='DELETE FROM Keyboard WHERE UserID=' & $UserID & ' AND MsgID=' & $MsgID & ' ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then return true
		Return false
	EndFunc
#endregion
#region   ===========================================================================
	func closeall()
		_SQLite_Close()
		_SQLite_Shutdown()
		exit 30
	EndFunc
#endregion
#region =====================================   Helpers functions  ===============================
	Func _mergeArray($array1, $array2)
		$array1 = _ArrayAdd_Column($array1)
		$size = UBound($array1)
		$newCol = UBound($array1, 2) - 1
		For $i = 0 To $size - 1
			$array1[$i][$newCol] = $array2[$i]
		Next
		Return $array1
	EndFunc   ;==>_mergeArray
	Func _ArrayAdd_Column($Array)
		Local $aTemp[UBound($Array)][UBound($Array, 0) + 1]
		For $i = 0 To UBound($Array) - 1

			For $j = 0 To UBound($Array, 0) - 1
				If UBound($Array, 0) = 1 Then $aTemp[$i][0] = $Array[$i]
				If UBound($Array, 0) > 1 Then $aTemp[$i][$j] = $Array[$i][$j]
			Next
		Next
		Return $aTemp
	EndFunc   ;==>_ArrayAdd_Column
	Func _ClearSciteConsole()
		ConsoleWrite('!!!!!!!!!!!_ClearSciteConsole Func General 92!!!!!!!!!!!!  ' & @CRLF)
		ControlSend("[CLASS:SciTEWindow]", "", "Scintilla2", "+{F5}")
	EndFunc   ;==>_ClearSciteConsole
	Func _GetDOSOutput($sCommand)
	 ConsoleWrite('++_GetDOSOutput $sCommand = ' & $sCommand & @crlf )
		Local $iPID, $sOutput = ""
		$iPID = Run('"' & @ComSpec & '" /c ' & $sCommand, "", @SW_HIDE, 2 + 4)
		While 1
			$sOutput &= StdoutRead($iPID, False, False)
			$err=@error
			If $err Then
				ConsoleWrite('!!  _GetDOSOutput $err = ' & $err & @crlf )
				ExitLoop
			EndIf
	;~ 	Sleep(10)
		WEnd
		ConsoleWrite('>> 	Output = ' & $sOutput & @crlf )
		Return $sOutput
	EndFunc   ;==>_GetDOSOutput
	Func _timeBetween($cTime, $sTime, $eTime)
		 If Not _DateIsValid('2000/01/01 ' & $cTime) Then Return -1
		 If Not _DateIsValid('2000/01/01 ' & $sTime) Then Return -2
		 If Not _DateIsValid('2000/01/01 ' & $eTime) Then Return -3
		 If _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') < 0 And _
			 _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') > 0 Then
			  Return 1
		 Else
			  Return 0
		 EndIf
	EndFunc  ; ==>_timeBetween
#endregion
#region log
	Func _initLog()
		ConsoleWrite('++_initLog() = '& @crlf)
		FileClose($hLogFile)
		;open log file for activity
		$hLogFile = FileOpen($LogFileActivity, 1+8)
		If $hLogFile = -1 Then
			ConsoleWrite("Error Unable to open file Log File.")
			MsgBox(48+4096, "Activity Log File error", "Activity Log File cannot be reached." & @crlf & _
								"File configured: " & $LogFileActivity & @crlf & _
								"Using Log file: " & $LogFileActivity& @crlf &"ErrNo 2052",0)
		EndIf

		ConsoleWrite('- ActivityLogFile = ' & $LogFileActivity & @crlf )
		FileWriteLine($hLogFile,"===============================================================================" )
		FileWriteLine($hLogFile,"===============================================================================")
		FileWriteLine($hLogFile,_NowCalcDate()  & @TAB& "Start of activities"& @TAB& "Version: "& $version)
		FileWriteLine($hLogFile,"===============================================================================")
	EndFunc
	Func _ConsoleWrite($s_text,$logLevel=0)
		Switch $logLevel
			Case 0
				$logLevelmsg="DEBUG"
				$levelcolor="+"
			Case 1
				$levelcolor=">"
				$logLevelmsg="INFO"
			Case 2
				$levelcolor="-"
				$logLevelmsg="WARN"
			Case 3
				$levelcolor="!"
				$logLevelmsg="ERROR"
			Case Else
				$logLevelmsg="NA"
		EndSwitch
		FileWriteLine($hLogFile, _LogDate()&" ["& $logLevelmsg&"] " & $s_text )
;~ 			ConsoleWrite($levelcolor&"["& $logLevelmsg&"] " & $s_text & @CRLF)
		ConsoleWrite($s_text & @CRLF)
	EndFunc   ;==>_ConsoleWrite
	Func _LogDate()
		$tCur = _Date_Time_GetLocalTime()
		$tCur = _Date_Time_SystemTimeToDateTimeStr($tCur)
		$date = "[" & stringreplace($tCur,"/","-") & "] "
		return $date
	EndFunc
	Func _EndLog()
		ConsoleWrite('++_EndLog() = '& @crlf)
		FileWriteLine($hLogFile,"..............................................................................." )
		FileWriteLine($hLogFile,_NowCalcDate()   & @TAB& "End of activities")
		FileWriteLine($hLogFile,"..............................................................................." & @CRLF)
		FileClose($hLogFile)
	EndFunc
#endregion
#region time
	Func  Sec2Time($nr_sec)
		$sec2time_hour = Int($nr_sec / 3600)
		$sec2time_min = Int(($nr_sec - $sec2time_hour * 3600) / 60)
		$sec2time_sec = $nr_sec - $sec2time_hour * 3600 - $sec2time_min * 60
		Return StringFormat('%02d:%02d:%02d', $sec2time_hour, $sec2time_min, $sec2time_sec)
	EndFunc   ;==>Sec2Time
	Func _GetUnixTime($sDate = 0);Date Format: 2013/01/01 00:00:00 ~ Year/Mo/Da Hr:Mi:Se
		Local $aSysTimeInfo = _Date_Time_GetTimeZoneInformation()
		Local $utcTime = ""
		If Not $sDate Then $sDate = _NowCalc()
		If Int(StringLeft($sDate, 4)) < 1970 Then Return ""
		If $aSysTimeInfo[0] = 2 Then
			$utcTime = _DateAdd('n', $aSysTimeInfo[1] + $aSysTimeInfo[7], $sDate)
		Else
			$utcTime = _DateAdd('n', $aSysTimeInfo[1], $sDate)
		EndIf
		Return _DateDiff('s', "1970/01/01 00:00:00", $utcTime)
	EndFunc   ;==>_GetUnixTime
#endregion

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			For $j = 0 To UBound($Array, 0) - 1
				If UBound($Array, 0) = 1 Then $aTemp[$i][0] = $Array[$i]
				If UBound($Array, 0) > 1 Then $aTemp[$i][$j] = $Array[$i][$j]
			Next
		Next
		Return $aTemp
	EndFunc   ;==>_ArrayAdd_Column
	Func _ClearSciteConsole()
		ConsoleWrite('!!!!!!!!!!!_ClearSciteConsole Func General 92!!!!!!!!!!!!  ' & @CRLF)
		ControlSend("[CLASS:SciTEWindow]", "", "Scintilla2", "+{F5}")
	EndFunc   ;==>_ClearSciteConsole
	Func _GetDOSOutput($sCommand)
	 ConsoleWrite('++_GetDOSOutput $sCommand = ' & $sCommand & @crlf )
		Local $iPID, $sOutput = ""
		$iPID = Run('"' & @ComSpec & '" /c ' & $sCommand, "", @SW_HIDE, 2 + 4)
		While 1
			$sOutput &= StdoutRead($iPID, False, False)
			$err=@error
			If $err Then
				ConsoleWrite('!!  _GetDOSOutput $err = ' & $err & @crlf )
				ExitLoop
			EndIf
	;~ 	Sleep(10)
		WEnd
		ConsoleWrite('>> 	Output = ' & $sOutput & @crlf )
		Return $sOutput
	EndFunc   ;==>_GetDOSOutput
	Func _timeBetween($cTime, $sTime, $eTime)
		 If Not _DateIsValid('2000/01/01 ' & $cTime) Then Return -1
		 If Not _DateIsValid('2000/01/01 ' & $sTime) Then Return -2
		 If Not _DateIsValid('2000/01/01 ' & $eTime) Then Return -3
		 If _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') < 0 And _
			 _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') > 0 Then
			  Return 1
		 Else
			  Return 0
		 EndIf
	EndFunc  ; ==>_timeBetween
#endregion
#region log
	Func _initLog()
		ConsoleWrite('++_initLog() = '& @crlf)
		FileClose($hLogFile)
		;open log file for activity
		$hLogFile = FileOpen($LogFileActivity, 1+8)
		If $hLogFile = -1 Then
			ConsoleWrite("Error Unable to open file Log File.")
			MsgBox(48+4096, "Activity Log File error", "Activity Log File cannot be reached." & @crlf & _
								"File configured: " & $LogFileActivity & @crlf & _
								"Using Log file: " & $LogFileActivity& @crlf &"ErrNo 2052",0)
		EndIf

		ConsoleWrite('- ActivityLogFile = ' & $LogFileActivity & @crlf )
		FileWriteLine($hLogFile,"===============================================================================" )
		FileWriteLine($hLogFile,"===============================================================================")
		FileWriteLine($hLogFile,_NowCalcDate()  & @TAB& "Start of activities"& @TAB& "Version: "& $version)
		FileWriteLine($hLogFile,"===============================================================================")
	EndFunc
	Func _ConsoleWrite($s_text,$logLevel=0)
		Switch $logLevel
			Case 0
				$logLevelmsg="DEBUG"
				$levelcolor="+"
			Case 1
				$levelcolor=">"
				$logLevelmsg="INFO"
			Case 2
				$levelcolor="-"
				$logLevelmsg="WARN"
			Case 3
				$levelcolor="!"
				$logLevelmsg="ERROR"
			Case Else
				$logLevelmsg="NA"
		EndSwitch
		FileWriteLine($hLogFile, _LogDate()&" ["& $logLevelmsg&"] " & $s_text )
;~ 			ConsoleWrite($levelcolor&"["& $logLevelmsg&"] " & $s_text & @CRLF)
		ConsoleWrite($s_text & @CRLF)
	EndFunc   ;==>_ConsoleWrite
	Func _LogDate()
		$tCur = _Date_Time_GetLocalTime()
		$tCur = _Date_Time_SystemTimeToDateTimeStr($tCur)
		$date = "[" & stringreplace($tCur,"/","-") & "] "
		return $date
	EndFunc
	Func _EndLog()
		ConsoleWrite('++_EndLog() = '& @crlf)
		FileWriteLine($hLogFile,"..............................................................................." )
		FileWriteLine($hLogFile,_NowCalcDate()   & @TAB& "End of activities")
		FileWriteLine($hLogFile,"..............................................................................." & @CRLF)
		FileClose($hLogFile)
	EndFunc
#endregion
#region time
	Func  Sec2Time($nr_sec)
		$sec2time_hour = Int($nr_sec / 3600)
		$sec2time_min = Int(($nr_sec - $sec2time_hour * 3600) / 60)
		$sec2time_sec = $nr_sec - $sec2time_hour * 3600 - $sec2time_min * 60
		Return StringFormat('%02d:%02d:%02d', $sec2time_hour, $sec2time_min, $sec2time_sec)
	EndFunc   ;==>Sec2Time
	Func _GetUnixTime($sDate = 0);Date Format: 2013/01/01 00:00:00 ~ Year/Mo/Da Hr:Mi:Se
		Local $aSysTimeInfo = _Date_Time_GetTimeZoneInformation()
		Local $utcTime = ""
		If Not $sDate Then $sDate = _NowCalc()
		If Int(StringLeft($sDate, 4)) < 1970 Then Return ""
		If $aSysTimeInfo[0] = 2 Then
			$utcTime = _DateAdd('n', $aSysTimeInfo[1] + $aSysTimeInfo[7], $sDate)
		Else
			$utcTime = _DateAdd('n', $aSysTimeInfo[1], $sDate)
		EndIf
		Return _DateDiff('s', "1970/01/01 00:00:00", $utcTime)
	EndFunc   ;==>_GetUnixTime
#endregion


prepared for compilation

prepared for compilation

#NoTrayIcon
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=images\twirl.ico
#AutoIt3Wrapper_Outfile=release\Get-Tweet.exe
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_Comment=SubteBA Telegram Alerter
#AutoIt3Wrapper_Res_Description=SubteBA Telegram Alerter
#AutoIt3Wrapper_Res_Fileversion=0.2.0.39
#AutoIt3Wrapper_Res_Fileversion_AutoIncrement=y
#AutoIt3Wrapper_Res_LegalCopyright=By Marcelo Saied
#AutoIt3Wrapper_Run_Obfuscator=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#region init
	#NoTrayIcon
	#include <Misc.au3>
	If _Singleton(@ScriptName, 1) = 0 Then ; allow only one instance
		MsgBox(0, "Warning", "An occurence of " & @ScriptName & " is already running")
		Exit
	EndIf

	$SendToAll=0 ; si es 0 solo se manda a Dev users
					  ; si es 1 se manda a todos
	if @Compiled then $SendToAll=1

	#include <includes\includes.au3>
	_ConfigInitial()
#endregion init
local $Username=IniRead("..\..\secret\config.ini","Twitter","Username","subteba")

while 1
;~ Get tweeter data , and send messages
	$beginScrap = TimerInit()
	If _timeBetween(@HOUR & ':' & @MIN, $StartTimeScrap, $EndTimeScrap) then
		TweeterMessages($Username)
		consolewrite('>>   '&$Username&' Scrap time: '&Sec2Time(TimerDiff($beginScrap)/1000) & @crlf)
	Else
		ConsoleWrite(' Out of Scrap Time '& $StartTimeScrap & "  To "  & $EndTimeScrap & @CRLF)
	endif

	while ($TweeterScrapMsec - TimerDiff($beginScrap)) > 0
;~ 		ConsoleWrite('>>        TweeterScrapMsec = ' & $TweeterScrapMsec & " > "& TimerDiff($beginScrap)&@crlf )
		$beginGetUpdates = TimerInit()
		If _timeBetween(@HOUR & ':' & @MIN, $StartTimeBot, $EndTimeBot) then
			UpdateUsers()
		endif
		while $GetUpdateTimemsec > TimerDiff($beginGetUpdates)
;~ 			ConsoleWrite('@@GetUpdateTimemsec = ' & $GetUpdateTimemsec & " > "& TimerDiff($beginGetUpdates)&@crlf )
			Sleep(100)
		wend
	wend
wend

closeall()

#NoTrayIcon
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=images\twirl.ico
#AutoIt3Wrapper_Outfile=release\Get-Tweet.exe
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_Comment=SubteBA Telegram Alerter
#AutoIt3Wrapper_Res_Description=SubteBA Telegram Alerter
#AutoIt3Wrapper_Res_Fileversion=0.2.0.27
#AutoIt3Wrapper_Res_Fileversion_AutoIncrement=y
#AutoIt3Wrapper_Res_LegalCopyright=By Marcelo Saied
#AutoIt3Wrapper_Run_Obfuscator=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#region init
	#NoTrayIcon
	#include <Misc.au3>
	If _Singleton(@ScriptName, 1) = 0 Then ; allow only one instance
		MsgBox(0, "Warning", "An occurence of " & @ScriptName & " is already running")
		Exit
	EndIf

	$SendToAll=0 ; si es 0 solo se manda a Dev users
					  ; si es 1 se manda a todos
	if @Compiled then $SendToAll=1

	#include <includes\includes.au3>
	_ConfigInitial()
#endregion init
local $Username=IniRead("..\..\secret\config.ini","Twitter","Username","subteba")

#region testeos
;~ 	ConsoleWrite("Test _SendMsg      -> "  & @TAB & _SendMsg($DEVChatID,"Testeo _SendMsg") & @CRLF)
	$keybrd='[[Hello,Hello2]]'
;~ 	$keybrd = '{"keyboard":[[{ text: "Yes" }],[{ text: "No" }]] }'
;~ 	$keybrd = "[['top-left', 'top-right'],['bottom-left', 'bottom-right']]"
;~ 	$keybrd='[[KeyboardButton(text="Yes"), KeyboardButton(text="No")]]'
	ConsoleWrite("Test _SendMsg      -> "  & @TAB & _SendMsg($DEVChatID,"Test _SendMsg","HTML",$keybrd) & @CRLF)

;~ 	$Path="images\workflow1.jpg"
;~ 	$Caption="testeo de envio de imagen imagen"
;~ 	$DEVChatID=464405525 ; gille
;~ 	_SendPhoto($DEVChatID, $Path, $Caption)
	exit
#endregion
while 1
;~ Get tweeter data , and send messages
	$beginScrap = TimerInit()
	If _timeBetween(@HOUR & ':' & @MIN, $StartTimeScrap, $EndTimeScrap) then
		TweeterMessages($Username)
		consolewrite('>>   '&$Username&' Scrap time: '&Sec2Time(TimerDiff($beginScrap)/1000) & @crlf)
	Else
		ConsoleWrite(' Out of Scrap Time '& $StartTimeScrap & "  To "  & $EndTimeScrap & @CRLF)
	endif

	while ($TweeterScrapMsec - TimerDiff($beginScrap)) > 0
;~ 		ConsoleWrite('>>        TweeterScrapMsec = ' & $TweeterScrapMsec & " > "& TimerDiff($beginScrap)&@crlf )
		$beginGetUpdates = TimerInit()
		If _timeBetween(@HOUR & ':' & @MIN, $StartTimeBot, $EndTimeBot) then
			UpdateUsers()
		endif
		while $GetUpdateTimemsec > TimerDiff($beginGetUpdates)
;~ 			ConsoleWrite('@@GetUpdateTimemsec = ' & $GetUpdateTimemsec & " > "& TimerDiff($beginGetUpdates)&@crlf )
			Sleep(100)
		wend
	wend
wend

closeall()


add localhost to SOL paths list

add localhost to SOL paths list

#include <String.au3>
#include <File.au3>
#include <Array.au3>

Global $string, $password, $email, $data, $path, $search, $file, $root
$root = "HKEY_CLASSES_ROOT\muledump"

Func _write()
	RegWrite($root,"","REG_SZ","URL: muledump Protocol")
	RegWrite($root,"URL Protocol","REG_SZ","")
	RegWrite($root & "\shell")
	RegWrite($root & "\shell\open")
	RegWrite($root & "\shell\open\command","","REG_SZ", @AutoItExe & ' "' & @ScriptFullPath & '" %1')
	If RegRead("HKEY_CLASSES_ROOT\muledump","") Then
		MsgBox(64,"mulelogin","muledump: URL handler installed")
	Else
		MsgBox(16,"mulelogin","Unable to write to registry" & @CRLF & "Try again with admin rights")
	EndIf
	Exit
EndFunc

Func _install()
	Local $k
	$k = RegEnumKey($root, 1)
	If @error == 2 Then
		MsgBox(16,"mulelogin","Unable to open the registry" & @CRLF & "Try again with admin rights")
		Exit
	EndIf
	If @error == 1 Then _write()
	$k = MsgBox(6 + 32, 'mulelogin', _
		'URL handler is already installed. Uninstall?' & @CRLF & @CRLF & _
		'"Cancel" to do nothing' & @CRLF & _
		'"Try Again" to reinstall' & @CRLF & _
		'"Continue" to uninstall')
	If $k == 10 Then _write()
	If $k == 11 Then
		RegDelete($root)
		if @error <> 0 Then
			MsgBox(16,"mulelogin","Unable to delete the key" & @CRLF & "Try again with admin rights")
		Else
			MsgBox(64,"mulelogin","muledump: URL handler uninstalled")
		EndIf
	EndIf
	Exit
EndFunc

Func _length($string)
	Local $binlength, $declength, $array, $result
	$declength = StringLen($string)/2
    While $declength > 0
        $binlength &= Mod($declength,2)
        $declength = Floor($declength/2)
    WEnd
	$binlength = StringReverse($binlength)
	if @error <> 0 Then
		$binlength = _StringReverse($binlength)
	EndIf
	$binlength = $binlength & "1"
	$array = StringSplit($binlength,"")
	For $i = 1 To $array[0]
        $array[0] -= 1
        If $array[$i] = "1" Then $result += 2 ^ ($array[0])
	Next
	Return Hex(Int($result),2)
EndFunc

Func _build()
	;header
	$string  = "0x 00 BF" 						;Magic Number		 2 bytes
	$string &= "?? ?? ?? ??"					;Size				 4 bytes
	$string &= "54 43 53 4F 00 04 00 00 00 00"	;Marker				10 bytes
	$string &= "00 05"							;Name Size			 2 bytes
	$string &= "52 6F 74 4D 47"					;"RotMG"			 5 bytes
	$string &= "00 00 00"						;Padding			 3 bytes
	$string &= "03"								;AMF Version		 1 byte

	;data
	$string &= "11"								;Length				 1 byte
	$string &= "50 61 73 73 77 6F 72 64"		;"Password"			 8 bytes
	$string &= "06"								;Type (string) 		 1 byte
	$string &= _length($password)				;Length				 1 byte
	$string &= $password						;Actual Password	 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string &= "09"								;Length				 1 byte
	$string &= "47 55 49 44"					;"GUID"				 4 bytes
	$string &= "06"								;Type (string)		 1 byte
	$string &= _length($email)					;Length				 1 byte
	$string &=  $email							;Email				 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string = StringReplace($string," ","")
	$string = StringRegExpReplace($string,"\?{8}",Hex(Int(StringLen(StringMid($string,15))/2)))
EndFunc

If $CmdLine[0] = 0 Then _install()

$data = StringReplace($CmdLine[1],"muledump:","")
$data = StringSplit($data,"-")
$email = $data[1]
$password = $data[2]

_build()

Local $paths[3] = [ _
	"localhost", _
	"realmofthemadgodhrd.appspot.com", _
	"www.realmofthemadgod.com" _
]
$path = @AppDataDir & "\Macromedia\Flash Player\#SharedObjects\"
$search = FileFindFirstFile($path & "*")
$searchPath = FileFindNextFile($search)
For $gameDir In $paths
	$gameFilePath = $path & $searchPath & "\" & $gameDir & "\RotMG.sol"
	$file = FileOpen($gameFilePath,26)
	FileWrite($file,$string)
	FileClose($file)
Next
FileClose($search)

ShellExecute("http://www.realmofthemadgod.com/")
; replace the line above if you're using a projector
; for example, with totalcmd + swfview
;ShellExecute('C:\Program Files\Total Commander\Totalcmd.exe', '/S=L:Pswfview e:\temp\rotmg\loader.swf')
; or to open the latest swf with the Adobe Flash Projector
;ShellExecute('C:\flashplayer_16_sa.exe', 'https://realmofthemadgodhrd.appspot.com/AssembleeGameClient'&BinaryToString(InetRead("http://www.realmofthemadgod.com/version.txt"))&'.swf')

#include <String.au3>
#include <File.au3>
#include <Array.au3>

Global $string, $password, $email, $data, $path, $search, $file, $root
$root = "HKEY_CLASSES_ROOT\muledump"

Func _write()
	RegWrite($root,"","REG_SZ","URL: muledump Protocol")
	RegWrite($root,"URL Protocol","REG_SZ","")
	RegWrite($root & "\shell")
	RegWrite($root & "\shell\open")
	RegWrite($root & "\shell\open\command","","REG_SZ", @AutoItExe & ' "' & @ScriptFullPath & '" %1')
	If RegRead("HKEY_CLASSES_ROOT\muledump","") Then
		MsgBox(64,"mulelogin","muledump: URL handler installed")
	Else
		MsgBox(16,"mulelogin","Unable to write to registry" & @CRLF & "Try again with admin rights")
	EndIf
	Exit
EndFunc

Func _install()
	Local $k
	$k = RegEnumKey($root, 1)
	If @error == 2 Then
		MsgBox(16,"mulelogin","Unable to open the registry" & @CRLF & "Try again with admin rights")
		Exit
	EndIf
	If @error == 1 Then _write()
	$k = MsgBox(6 + 32, 'mulelogin', _
		'URL handler is already installed. Uninstall?' & @CRLF & @CRLF & _
		'"Cancel" to do nothing' & @CRLF & _
		'"Try Again" to reinstall' & @CRLF & _
		'"Continue" to uninstall')
	If $k == 10 Then _write()
	If $k == 11 Then
		RegDelete($root)
		if @error <> 0 Then
			MsgBox(16,"mulelogin","Unable to delete the key" & @CRLF & "Try again with admin rights")
		Else
			MsgBox(64,"mulelogin","muledump: URL handler uninstalled")
		EndIf
	EndIf
	Exit
EndFunc

Func _length($string)
	Local $binlength, $declength, $array, $result
	$declength = StringLen($string)/2
    While $declength > 0
        $binlength &= Mod($declength,2)
        $declength = Floor($declength/2)
    WEnd
	$binlength = StringReverse($binlength)
	if @error <> 0 Then
		$binlength = _StringReverse($binlength)
	EndIf
	$binlength = $binlength & "1"
	$array = StringSplit($binlength,"")
	For $i = 1 To $array[0]
        $array[0] -= 1
        If $array[$i] = "1" Then $result += 2 ^ ($array[0])
	Next
	Return Hex(Int($result),2)
EndFunc

Func _build()
	;header
	$string  = "0x 00 BF" 						;Magic Number		 2 bytes
	$string &= "?? ?? ?? ??"					;Size				 4 bytes
	$string &= "54 43 53 4F 00 04 00 00 00 00"	;Marker				10 bytes
	$string &= "00 05"							;Name Size			 2 bytes
	$string &= "52 6F 74 4D 47"					;"RotMG"			 5 bytes
	$string &= "00 00 00"						;Padding			 3 bytes
	$string &= "03"								;AMF Version		 1 byte

	;data
	$string &= "11"								;Length				 1 byte
	$string &= "50 61 73 73 77 6F 72 64"		;"Password"			 8 bytes
	$string &= "06"								;Type (string) 		 1 byte
	$string &= _length($password)				;Length				 1 byte
	$string &= $password						;Actual Password	 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string &= "09"								;Length				 1 byte
	$string &= "47 55 49 44"					;"GUID"				 4 bytes
	$string &= "06"								;Type (string)		 1 byte
	$string &= _length($email)					;Length				 1 byte
	$string &=  $email							;Email				 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string = StringReplace($string," ","")
	$string = StringRegExpReplace($string,"\?{8}",Hex(Int(StringLen(StringMid($string,15))/2)))
EndFunc

If $CmdLine[0] = 0 Then _install()

$data = StringReplace($CmdLine[1],"muledump:","")
$data = StringSplit($data,"-")
$email = $data[1]
$password = $data[2]

_build()

Local $paths[2] = ["www.realmofthemadgod.com", "realmofthemadgodhrd.appspot.com"]
$path = @AppDataDir & "\Macromedia\Flash Player\#SharedObjects\"
$search = FileFindFirstFile($path & "*")
$searchPath = FileFindNextFile($search)
For $gameDir In $paths
	$gameFilePath = $path & $searchPath & "\" & $gameDir & "\RotMG.sol"
	$file = FileOpen($gameFilePath,26)
	FileWrite($file,$string)
	FileClose($file)
Next
FileClose($search)

ShellExecute("http://www.realmofthemadgod.com/")
; replace the line above if you're using a projector
; for example, with totalcmd + swfview
;ShellExecute('C:\Program Files\Total Commander\Totalcmd.exe', '/S=L:Pswfview e:\temp\rotmg\loader.swf')
; or to open the latest swf with the Adobe Flash Projector
;ShellExecute('C:\flashplayer_16_sa.exe', 'https://realmofthemadgodhrd.appspot.com/AssembleeGameClient'&BinaryToString(InetRead("http://www.realmofthemadgod.com/version.txt"))&'.swf')