Jump to content
therks

Simple "chat" program with clickable links

Recommended Posts

therks

Hi there,

So I've created this very simple "chat" program so that my brother and I can quickly and easily share text and links to other computers on the network. It just reads/writes to a text file that the script interprets/formats appropriately. I will put the script it in a shared network folder and then any of the computers can open and use it.

For displaying the "chat" I'm currently using an embedded IE browser and formatting the text via HTML, but I've realized that this will cause problems with opening the links because it will use IE instead of the system's default browser (Chrome in our case). Any suggestions? (To be clear, I'm specifically looking for assistance on having text with clickable links that will open in the default browser.)

 

For anyone interested, here's the code so far:

#include <GUIConstants.au3>
#include <GUIEdit.au3>
#include <IE.au3>

Opt('TrayIconDebug', 1)

Global $CHAT_FILE = @ScriptDir & '\NetworkChat.txt'

Main()

Func Main()
    Local $hGUIMain = GUICreate('Network Chat', 500, 500, Default, Default, $WS_OVERLAPPEDWINDOW)

    Local $oEmbedIE = _IECreateEmbedded()
    Local $ob_EmbedIE = GUICtrlCreateObj($oEmbedIE, 5, 5, 490, 300)
        GUICtrlSetResizing(-1, $GUI_DOCKBORDERS)
    _IENavigate($oEmbedIE, 'about:blank')

    Local $dm_AccelTab = GUICtrlCreateDummy()
    Local $dm_AccelCtrlA = GUICtrlCreateDummy()
    Local $dm_AccelEnter = GUICtrlCreateDummy()
    Local $dm_AccelShiftEnter = GUICtrlCreateDummy()
    Local $dm_AccelPgUp = GUICtrlCreateDummy()
    Local $dm_AccelPgDn = GUICtrlCreateDummy()
    Local $ed_Chat = GUICtrlCreateEdit('', 5, 310, 470, 60, BitOR($ES_WANTRETURN, $WS_VSCROLL, $ES_AUTOVSCROLL))
        GUICtrlSetResizing(-1, BitOR($GUI_DOCKSTATEBAR, $GUI_DOCKLEFT, $GUI_DOCKRIGHT))
        Local $aTabStop = [ 4 * 4 ]
        _GUICtrlEdit_SetTabStops($ed_Chat, $aTabStop)
    Local $bt_Send = GUICtrlCreateButton('>', 475, 310, 20, 60)
        GUICtrlSetResizing(-1, BitOR($GUI_DOCKSTATEBAR, $GUI_DOCKSIZE, $GUI_DOCKRIGHT))
        GUICtrlSetState(-1, $GUI_DEFBUTTON)

    Local $ch_Timestamps = GUICtrlCreateCheckbox('Show &timestamps', 5, 370, 200, 20)
        GUICtrlSetResizing(-1, BitOR($GUI_DOCKSTATEBAR, $GUI_DOCKSIZE, $GUI_DOCKLEFT))
    Local $ra_Enter = GUICtrlCreateRadio('&1. Enter to send / Shift+Enter for new line', 280, 370, 215, 20)
        GUICtrlSetResizing(-1, BitOR($GUI_DOCKSTATEBAR, $GUI_DOCKSIZE, $GUI_DOCKRIGHT))
        GUICtrlSetState(-1, $GUI_CHECKED)
    Local $ra_ShiftEnter = GUICtrlCreateRadio('&2. Shift+Enter to send / Enter for new line', 280, 390, 215, 20)
        GUICtrlSetResizing(-1, BitOR($GUI_DOCKSTATEBAR, $GUI_DOCKSIZE, $GUI_DOCKRIGHT))

    Local $aAccel = [ _
        [ '{enter}', $dm_AccelEnter ], _
        [ '+{enter}', $dm_AccelShiftEnter ], _
        [ '{tab}', $dm_AccelTab ], _
        [ '{pgup}', $dm_AccelPgUp ], _
        [ '{pgdn}', $dm_AccelPgDn ], _
        [ '^a', $dm_AccelCtrlA ] ]
    Local $aAccelSwap = $aAccel
    $aAccelSwap[0][0] = '+{enter}'
    $aAccelSwap[1][0] = '{enter}'

    GUISetAccelerators($aAccel)
    GUISetState()
    GUICtrlSetState($ed_Chat, $GUI_FOCUS)

    Local $sHTML, $aChatTime[2], $hFocused, $hIEControl = ControlGetHandle($hGUIMain, '', '[CLASS:Internet Explorer_Server; INSTANCE:1]')
    While 1
        $hFocused = _WinAPI_GetFocus()

        $aChatTime[0] = FileGetTime($CHAT_FILE, 0, 1)
        If $aChatTime[0] <> $aChatTime[1] Then
            $sHTML = _LoadChat(BitAND(GUICtrlRead($ch_Timestamps), $GUI_CHECKED))
            _IEDocWriteHTML($oEmbedIE, $sHTML)
            _IEAction($oEmbedIE, 'refresh')
            $oEmbedIE.document.parentwindow.scrollTo(0, $oEmbedIE.document.body.scrollHeight)
            $aChatTime[1] = $aChatTime[0]
        EndIf

        Local $iMsg = GUIGetMsg()
        If $iMsg > 0 Then ConsoleWrite($iMsg & @CRLF)
        Switch $iMsg
            Case $ch_Timestamps
                $aChatTime[1] = 0
            Case $ra_Enter
                GUISetAccelerators($aAccel)
            Case $ra_ShiftEnter
                GUISetAccelerators($aAccelSwap)
            Case $dm_AccelPgUp
                $oEmbedIE.document.parentwindow.scrollBy(0, -200)
            Case $dm_AccelPgDn
                $oEmbedIE.document.parentwindow.scrollBy(0, 200)
            Case $dm_AccelCtrlA
                If $hFocused = GUICtrlGetHandle($ed_Chat) Then _GUICtrlEdit_SetSel($ed_Chat, 0, -1)
            Case $dm_AccelEnter
                If $hFocused = GUICtrlGetHandle($ed_Chat) Then
                    If BitAND(GUICtrlRead($ra_Enter), $GUI_CHECKED) Then
                        _SendChat($ed_Chat)
                    Else
                        _GUICtrlEdit_ReplaceSel($ed_Chat, @CRLF)
                    EndIf
                EndIf
            Case $dm_AccelShiftEnter
                If $hFocused = GUICtrlGetHandle($ed_Chat) Then
                    If BitAND(GUICtrlRead($ra_ShiftEnter), $GUI_CHECKED) Then
                        _SendChat($ed_Chat)
                    Else
                        _GUICtrlEdit_ReplaceSel($ed_Chat, @CRLF)
                    EndIf
                EndIf
            Case $bt_Send
                If $hFocused = GUICtrlGetHandle($ed_Chat) Then
                    _SendChat($ed_Chat)
                Else
                    GUICtrlSetState($ed_Chat, $GUI_FOCUS)
                EndIf
            Case $dm_AccelTab
                If $hFocused = GUICtrlGetHandle($ed_Chat) Then
                    _GUICtrlEdit_ReplaceSel($ed_Chat, @TAB)
                Else
                    GUICtrlSetState($ed_Chat, $GUI_FOCUS)
                EndIf
            Case $GUI_EVENT_CLOSE
                ExitLoop
        EndSwitch
    WEnd
EndFunc

Func _EncodeForFile($sString)
    $sString = StringStripCR($sString)
    $sString = StringReplace($sString, '\', '\\')
    $sString = StringReplace($sString, @LF, '\n')
    $sString = StringReplace($sString, @TAB, '\t')
    Return $sString
EndFunc

Func _EncodeFromFile($sString)
    $sString = StringReplace($sString, '<', '<')
    $sString = StringReplace($sString, '>', '>')
    $sString = StringFormat($sString)
    $sString = StringReplace($sString, @TAB, '    ')
    $sString = StringReplace($sString, @LF, '<br />')
    $sString = StringRegExpReplace($sString, '(http://\S+)', '<a href="\1" target="_blank">\1</a>')
    Return $sString
EndFunc

Func _SendChat($iCtrl)
    Local $sChat = StringStripWS(GUICtrlRead($iCtrl), 3)
    If $sChat Then
        FileWrite($CHAT_FILE, @CRLF & @YEAR & @MON & @MDAY & @HOUR & @MIN & @SEC & @TAB & @ComputerName & @TAB & _EncodeForFile($sChat))
        GUICtrlSetData($iCtrl, '')
        Return True
    EndIf
EndFunc

Func _LoadChat($iShowTS)
    Local $aLines = FileReadToArray($CHAT_FILE), _
    $sOutput  = '<style>'
    $sOutput &= 'body, table { margin: 0; font-family: Arial; font-size: 0.8em; border-collapse: collapse; width: 100%; } '
    $sOutput &= 'tr { vertical-align: top; text-align: left; } '
    $sOutput &= '.name_column { white-space: nowrap; } '
    $sOutput &= '.text_column { width: 100%; } '
    $sOutput &= '.row1 { background: #eee; } '
    $sOutput &= '.date { background: #bef; text-align: center; border: solid #000; border-width: 1px 0; } '
    If Not $iShowTS Then $sOutput &= '.timestamp { display: none }'
    $sOutput &= '</style>'
    $sOutput &= '<table>'

    Local $sDateMem
    For $L = 0 To @extended-1
        If Not $aLines[$L] Then ContinueLoop

        Local $aRegExLine = StringRegExp($aLines[$L], '(.+)\t(.+)\t(.+)', 1), $sChat
        If Not @error Then
            $aDateTime = _FormatTime($aRegExLine[0])
            If $aDateTime[0] <> $sDateMem Then
                $sOutput &= '<tr><th class="date" colspan="2">' & $aDateTime[0] & '</th></tr>'
                $sDateMem = $aDateTime[0]
            EndIf

            $sOutput &= '<tr class="row' & Mod($L, 2) & '" title="' & $aDateTime[1] & '">' & _
                '<th class="name_column"><span class="timestamp">[' & $aDateTime[1] & '] </span>' & $aRegExLine[1] & '</th>' & _
                '<td class="text_column">' & _EncodeFromFile($aRegExLine[2]) & '</td></tr>' & @CRLF
        EndIf
    Next
    $sOutput &= '</table>'
    Return $sOutput
EndFunc

Func _FormatTime($sTime)
    Local $aMonths = StringSplit('Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec', '|')
    Local $aReturn[2]
    Local $aRegEx = StringRegExp($sTime, '(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})', 1)
    If Not @error Then
        $aReturn[0] = $aRegEx[0] &'-'& $aMonths[Int($aRegEx[1])] &'-'& $aRegEx[2]
        $aReturn[1] = $aRegEx[3] &':'& $aRegEx[4] &':'& $aRegEx[5]
    EndIf
    Return $aReturn
EndFunc

QrITWa6.png

 

Edited by therks

Share this post


Link to post
Share on other sites
Earthshine

you may be able to work with this and adapt it. 

Edited by Earthshine
  • Sad 1

My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
therks

Maybe I wasn't clear, but that doesn't have clickable links either which is the issue I'm looking for a solution for.

Also, I did search the forum. Found this post: 

But there's no script to be seen. It looks like maybe Jon removed it back in 2012?

Edited by therks

Share this post


Link to post
Share on other sites
Earthshine

so you can't use any of that messenger app code or patterns? keep going with your embedded browser approach I guess.

Edited by Earthshine

My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
therks

In reference to your first post, I saw nothing in there that will help me achieve what I'm looking for sadly. I'm looking at the RichEdit control now, but it's going off the rails very quickly. Not being a standard AutoIt control there's a lot I would have to handle manually. Also it seems the URL detecting doesn't work properly for 32 bit (at least the example for _GUICtrlRichEdit_AutoDetectURL doesn't work).

Concerning that last one, that wiki entry just links back to the same topic I linked to (with the missing script). But yes, that seems to be right on track with what I'd like to do.

Edited by therks

Share this post


Link to post
Share on other sites
Earthshine

ok. see what you mean. well, maybe we could look up if someone did a DLL for this stuff

Edited by Earthshine

My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
therks

That's the post I linked to. :blink: Did you not see my post? Or am I missing something? I see no UDF scripts in that topic.

Edited by therks

Share this post


Link to post
Share on other sites
Earthshine

nope, you were right on. so, what about we make a function that can determine the default browser and embed the appropriate browser in your gui? we can do that for chrome, can we not? i could be off base here, I am not a gui guy, sorry. I rarely deal with this stuff, if ever. I'm mostly build and testing.

this will tell you what the default is set to.

$myDefaultBrowser = RegRead("HKEY_CURRENT_USER\Software\Clients\StartMenuInternet", "")

 

Edited by Earthshine

My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
therks

Hmm, I don't think Chrome can be embedded. When I looked around it seemed it could only be IE as it's so ingrained with the OS, but I'd love to proven wrong. :)

What I'd really like is to know how Gary's UDF worked back in the day. That image on the wiki is such a tease.

Edited by therks

Share this post


Link to post
Share on other sites
Earthshine

oooh! oooh!! how about this. it work in a message box, why not a rich edit control! i just tested with latest AutoIt, works.

#NoTrayIcon
#include <Constants.au3>
#include <GUIConstants.au3>

Opt("GUICloseOnESC",1)
Opt("GUIOnEventMode",1)

$about = GuiCreate("About",215,150,-1,-1,BitOR($WS_CAPTION,$WS_SYSMENU))
GUISetOnEvent ($GUI_EVENT_CLOSE, "AboutOK" )
GUICtrlCreateIcon (@AutoItExe,-1,11,11)
GUICtrlCreateLabel ("App name 1.0",59,11,135,20)
GUICtrlSetFont (-1,10, 800, 0, "Arial"); bold
GUICtrlCreateLabel ("(c) 2005" & @CRLF & @CRLF & "Zedna",59,30,135,40)
$email = GUICtrlCreateLabel ("author@somewhere.com",59,70,135,15)
GuiCtrlSetFont($email, 8.5, -1, 4); underlined
GuiCtrlSetColor($email,0x0000ff)
GuiCtrlSetCursor($email,0)
GUICtrlSetOnEvent(-1, "OnEmail")
$www = GUICtrlCreateLabel ("www.autoitscript.com/forum/",59,85,140,15)
GuiCtrlSetFont($www, 8.5, -1, 4); underlined
GuiCtrlSetColor($www,0x0000ff)
GuiCtrlSetCursor($www,0)
GUICtrlSetOnEvent(-1, "OnWWW")
GUICtrlCreateButton ("OK",65,115,75,23,BitOr($GUI_SS_DEFAULT_BUTTON, $BS_DEFPUSHBUTTON))
GUICtrlSetState (-1, $GUI_FOCUS)
GUICtrlSetOnEvent(-1, "AboutOK")
GUISetState(@SW_SHOW, $about)

While 1
    Sleep(100)
WEnd

Func OnEmail()
    Run(@ComSpec & " /c " & 'start mailto:author@somewhere.com?subject=Something', "", @SW_HIDE)
EndFunc

Func OnWWW()
    Run(@ComSpec & " /c " & 'start www.autoitscript.com/forum/', "", @SW_HIDE)
EndFunc

Func AboutOK()
    Exit
EndFunc

Func OnAutoItExit()
    GUIDelete($about)
EndFunc

 

Edited by Earthshine

My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
therks

Yeah I've done something like that before, but it won't work here. That's making a label look like a link and then just handling the notification, basically like a button or other notifying control. I can't think of a way to embed something like that within normal text. If I could somehow get the embedded browser to pass the notification of a clicked link back to the AutoIt script I could handle it like that... but.. I just came up with an idea actually.

  • Like 1

Share this post


Link to post
Share on other sites
Earthshine

i hope it works out for you. if it does, please share it for others.


My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
therks

Oh for sure. It's working. Just wanted to test it first. It's kind of hacky cus it's not just AutoIt it uses JavaScript too.

So basically it goes like this. Instead of actually using links (<a href="">) in the HTML, I'm wrapping the URLs in <span> tags, styled to look like links. When clicking on the <span>, they set a <div> element's innerText to the URL from the span. The AutoIt script is constantly monitoring the <div> tag for changes and when it detects a change, it reads the content and then ShellExecute's it.

  • Like 1

Share this post


Link to post
Share on other sites
Earthshine

Nice. More than one way to skin a cat


My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
therks

Turns out that UDF was for naught as it doesn't work the way I hoped it would. However, I've been having a great deal of success with the method I figured out above. This is still a work in progress, but here's what I have so far.

#include <GUIConstants.au3>
#include <GUIEdit.au3>
#include <IE.au3>
#include <GuiRichEdit.au3>
;~ #include <Variable.au3>

Opt('TrayIconDebug', 1)

If $CmdLine[0] And StringInStr(FileGetAttrib($CmdLine[1]), 'D') Then
    FileChangeDir($CmdLine[1])
EndIf

Global $CHAT_FILE = @WorkingDir & '\NetworkChat.txt'
ConsoleWrite($CHAT_FILE & @CRLF)

Main()

Func Main()
    Local $hGUIMain = GUICreate('Network Chat', 500, 440, Default, Default, $WS_OVERLAPPEDWINDOW)

    Local $oEmbedIE = _IECreateEmbedded()
    Local $ob_EmbedIE = GUICtrlCreateObj($oEmbedIE, 5, 5, 490, 300)
        GUICtrlSetResizing(-1, $GUI_DOCKBORDERS)

    _IENavigate($oEmbedIE, 'about:blank')

    Local $dm_AccelTab = GUICtrlCreateDummy()
    Local $dm_AccelCtrlA = GUICtrlCreateDummy()
    Local $dm_AccelEnter = GUICtrlCreateDummy()
    Local $dm_AccelShiftEnter = GUICtrlCreateDummy()
    Local $dm_AccelPgUp = GUICtrlCreateDummy()
    Local $dm_AccelPgDn = GUICtrlCreateDummy()
    Local $ed_Chat = GUICtrlCreateEdit('', 5, 310, 470, 60, BitOR($ES_WANTRETURN, $WS_VSCROLL, $ES_AUTOVSCROLL))
        GUICtrlSetResizing(-1, BitOR($GUI_DOCKSTATEBAR, $GUI_DOCKLEFT, $GUI_DOCKRIGHT))
        Local $aTabStop = [ 4 * 4 ]
        _GUICtrlEdit_SetTabStops($ed_Chat, $aTabStop)
    Local $bt_Send = GUICtrlCreateButton('>', 475, 310, 20, 60)
        GUICtrlSetResizing(-1, BitOR($GUI_DOCKSTATEBAR, $GUI_DOCKSIZE, $GUI_DOCKRIGHT))
        GUICtrlSetState(-1, $GUI_DEFBUTTON)

    Local $ch_Timestamps = GUICtrlCreateCheckbox('Show &timestamps', 5, 375, 200, 20)
        GUICtrlSetResizing(-1, BitOR($GUI_DOCKSTATEBAR, $GUI_DOCKSIZE, $GUI_DOCKLEFT))
    Local $ch_PromptURL = GUICtrlCreateCheckbox('&Confirm before opening links', 5, 395, 200, 20)
        GUICtrlSetResizing(-1, BitOR($GUI_DOCKSTATEBAR, $GUI_DOCKSIZE, $GUI_DOCKLEFT))
    Local $ra_Enter = GUICtrlCreateRadio('&1. Enter to send / Shift+Enter for new line', 280, 375, 215, 20)
        GUICtrlSetResizing(-1, BitOR($GUI_DOCKSTATEBAR, $GUI_DOCKSIZE, $GUI_DOCKRIGHT))
        GUICtrlSetState(-1, $GUI_CHECKED)
    Local $ra_ShiftEnter = GUICtrlCreateRadio('&2. Shift+Enter to send / Enter for new line', 280, 395, 215, 20)
        GUICtrlSetResizing(-1, BitOR($GUI_DOCKSTATEBAR, $GUI_DOCKSIZE, $GUI_DOCKRIGHT))
    Local $lb_Status = GUICtrlCreateLabel(' Chat file: ' & $CHAT_FILE, 0, 420, 500, 20, BitOR($SS_SUNKEN, $SS_CENTERIMAGE))
        GUICtrlSetResizing(-1, BitOR($GUI_DOCKSTATEBAR, $GUI_DOCKLEFT, $GUI_DOCKRIGHT))
        GUICtrlSetCursor(-1, 0)

    Local $aAccel = [ _
        [ '{enter}', $dm_AccelEnter ], _
        [ '+{enter}', $dm_AccelShiftEnter ], _
        [ '{tab}', $dm_AccelTab ], _
        [ '{pgup}', $dm_AccelPgUp ], _
        [ '{pgdn}', $dm_AccelPgDn ], _
        [ '^a', $dm_AccelCtrlA ] ]

    GUISetAccelerators($aAccel)
    GUISetState()
    GUICtrlSetState($ed_Chat, $GUI_FOCUS)


    Local $sHTML, $aChatTime[2], $hFocused, $hIEControl = ControlGetHandle($hGUIMain, '', '[CLASS:Internet Explorer_Server; INSTANCE:1]')
    While 1
        $hFocused = _WinAPI_GetFocus()

        $aChatTime[0] = FileGetTime($CHAT_FILE, 0, 1)
        If $aChatTime[0] <> $aChatTime[1] Then
            $sHTML = _LoadChat(BitAND(GUICtrlRead($ch_Timestamps), $GUI_CHECKED))
            _IEDocWriteHTML($oEmbedIE, $sHTML)
            _IEAction($oEmbedIE, 'refresh')
            $oEmbedIE.document.parentwindow.scrollTo(0, $oEmbedIE.document.body.scrollHeight)
            $aChatTime[1] = $aChatTime[0]
        EndIf

        If $oEmbedIE.document.location.href <> 'about:blank' Then
            _IENavigate($oEmbedIE, 'about:blank')
            $aChatTime[1] = 0
        EndIf

        Local $oAutoItMonitor = $oEmbedIE.document.getElementById('autoit_monitor')
        If IsObj($oAutoItMonitor) And $oAutoItMonitor.value Then
            Local $sVal = $oAutoItMonitor.value
            If StringLeft($sVal, 4) = 'http' Then
                Local $sVal = StringReplace($sVal, '&amp;', '&') ; For some reason the JavaScript copying the URL always encodes ampersands to html entities
                If Not BitAND(GUICtrlRead($ch_PromptURL), $GUI_CHECKED) Or (MsgBox(0x124, 'URL', 'Open URL?' & @LF & $sVal, 0, $hGUIMain) = 6) Then
                    ShellExecute($sVal)
                EndIf
            ElseIf $sVal = 27 Then ; Escape
                ExitLoop
            ElseIf Not ($sVal = 17 Or $sVal >= 35 And $sVal <= 40) Then ; Ctrl, Home, End, Arrow keys
                ConsoleWrite($sVal & @CRLF)
                GUICtrlSetState($ed_Chat, $GUI_FOCUS)
            EndIf
            $oAutoItMonitor.value = ''
        EndIf

        Local $iMsg = GUIGetMsg()
        Switch $iMsg
            Case $lb_Status
                ShellExecute($CHAT_FILE)
            Case $ch_Timestamps
                $aChatTime[1] = 0
            Case $dm_AccelPgUp
                $oEmbedIE.document.parentwindow.scrollBy(0, -200)
            Case $dm_AccelPgDn
                $oEmbedIE.document.parentwindow.scrollBy(0, 200)
            Case $dm_AccelCtrlA
                If $hFocused = GUICtrlGetHandle($ed_Chat) Then _GUICtrlEdit_SetSel($ed_Chat, 0, -1)
            Case $dm_AccelEnter
                If $hFocused = GUICtrlGetHandle($ed_Chat) Then
                    If BitAND(GUICtrlRead($ra_Enter), $GUI_CHECKED) Then
                        _SendChat($ed_Chat)
                    Else
                        _GUICtrlEdit_ReplaceSel($ed_Chat, @CRLF)
                    EndIf
                EndIf
            Case $dm_AccelShiftEnter
                If $hFocused = GUICtrlGetHandle($ed_Chat) Then
                    If BitAND(GUICtrlRead($ra_ShiftEnter), $GUI_CHECKED) Then
                        _SendChat($ed_Chat)
                    Else
                        _GUICtrlEdit_ReplaceSel($ed_Chat, @CRLF)
                    EndIf
                EndIf
            Case $bt_Send
                _SendChat($ed_Chat)
            Case $dm_AccelTab
                If $hFocused = GUICtrlGetHandle($ed_Chat) Then
                    _GUICtrlEdit_ReplaceSel($ed_Chat, @TAB)
                Else
                    GUICtrlSetState($ed_Chat, $GUI_FOCUS)
                EndIf
            Case $GUI_EVENT_CLOSE
                ExitLoop
        EndSwitch
    WEnd
EndFunc

Func _EncodeForFile($sString)
    $sString = StringStripCR($sString)
    $sString = StringReplace($sString, '\', '\\')
    $sString = StringReplace($sString, @LF, '\n')
    $sString = StringReplace($sString, @TAB, '\t')
    Return $sString
EndFunc

Func _EncodeFromFile($sString)
    $sString = StringReplace($sString, '<', '&lt;')
    $sString = StringReplace($sString, '>', '&gt;')
    $sString = StringFormat($sString)
    $sString = StringReplace($sString, @TAB, '&nbsp;&nbsp;&nbsp;&nbsp;')
    $sString = StringReplace($sString, @LF, '<br />')
    $sString = StringRegExpReplace($sString, '(https?://\S+)', '<span class="fakelink" onclick="document.getElementById(''autoit_monitor'').value=this.innerHTML">\1</span>') ;
    Return $sString
EndFunc

Func _SendChat($iCtrl)
    Local $sChat = StringStripWS(GUICtrlRead($iCtrl), 3)
    If $sChat Then
        FileWrite($CHAT_FILE, @CRLF & @YEAR & @MON & @MDAY & @HOUR & @MIN & @SEC & @TAB & @ComputerName & @TAB & _EncodeForFile($sChat))
        GUICtrlSetData($iCtrl, '')
        Return True
    EndIf
EndFunc

Func _LoadChat($iShowTS)
    Local $aLines = FileReadToArray($CHAT_FILE), _
    $sOutput  = '<style>' & @CRLF
    $sOutput &= 'body, table { margin: 0; font-family: Arial; font-size: 0.8em; border-collapse: collapse; width: 100%; } ' & @CRLF
    $sOutput &= 'tr { vertical-align: top; text-align: left; } ' & @CRLF
    $sOutput &= '.name_column { white-space: nowrap; } ' & @CRLF
    $sOutput &= '.text_column { width: 100%; } ' & @CRLF
    $sOutput &= '.row1 { background: #eee; } ' & @CRLF
    $sOutput &= '.date { background: #bef; text-align: center; border: solid #000; border-width: 1px 0; } ' & @CRLF
    $sOutput &= '.fakelink { text-decoration: underline; cursor: pointer; color: #08f; } ' & @CRLF
    If Not $iShowTS Then $sOutput &= '.timestamp { display: none }' & @CRLF
    $sOutput &= '</style>' & @CRLF
    $sOutput &= '<body onkeydown="document.getElementById(''autoit_monitor'').value=event.keyCode">' & @CRLF
    $sOutput &= '<table>' & @CRLF

    Local $sDateMem
    For $L = 0 To @extended-1
        If Not $aLines[$L] Then ContinueLoop

        Local $aRegExLine = StringRegExp($aLines[$L], '(.+)\t(.+)\t(.+)', 1), $sChat
        If Not @error Then
            $aDateTime = _FormatTime($aRegExLine[0])
            If $aDateTime[0] <> $sDateMem Then
                $sOutput &= '<tr><th class="date" colspan="2">' & $aDateTime[0] & '</th></tr>'
                $sDateMem = $aDateTime[0]
            EndIf

            $sOutput &= '<tr class="row' & Mod($L, 2) & '">' & _
                '<th class="name_column"><span class="timestamp">[' & $aDateTime[1] & '] </span>&lt;' & $aRegExLine[1] & '&gt;</th>' & _
                '<td class="text_column">' & _EncodeFromFile($aRegExLine[2]) & '</td></tr>' & @CRLF
        EndIf
    Next
    $sOutput &= '</table>'
    $sOutput &= '<input type="hidden" id="autoit_monitor" />'
    Return $sOutput
EndFunc

Func _FormatTime($sTime)
    Local $aMonths = StringSplit('Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec', '|')
    Local $aReturn[2]
    Local $aRegEx = StringRegExp($sTime, '(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})', 1)
    If Not @error Then
        $aReturn[0] = $aRegEx[0] &'-'& $aMonths[Int($aRegEx[1])] &'-'& $aRegEx[2]
        $aReturn[1] = $aRegEx[3] &':'& $aRegEx[4] &':'& $aRegEx[5]
    EndIf
    Return $aReturn
EndFunc
  • Like 1

Share this post


Link to post
Share on other sites
KickStarter15

Hi @therks,

Thanks for the code you have, I used it and very satisfied with the outcome also it was perfect for my project and everything is good. However, is there a way that your code can be modify that who ever runs the program it will create label somewhere in the GUI that "@username is active".

I would like to see who is using the program and I need to know the username of that user.^_^ Thanks if that would be fine with you.:sweating:

 

KS15


Programming is "To make it so simple that there are obviously no deficiencies" or "To make it so complicated that there are no obvious deficiencies" by C.A.R. Hoare.

Share this post


Link to post
Share on other sites
therks

It would take a significant modification to do that. Currently this is really nothing more than a front end for reading/writing a fancy log file.

To monitor users that are "online" so to speak it would have to record when a user opens the program, remove them when the program closes, and in case the program crashes it would have to ping active users.

You're welcome to modify it however you see fit, but for me currently it's doing what I need. :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • rcmaehl
      By rcmaehl
      A UDF to connect to IRC using TCP Functions, as well as perform actions once connected.
      WANTED: Technical Writer able to create / maintain a helpfile (.chm) using the Autoit helpfile layout for an negotiated rate.

      Notes:
      Originally created by Chip.
      UDF Headers updated compared to old script.
      Error and Parameter Handling updated compared to old script.
      If you need to bypass the RFC compliance of this UDF, use _IRCRaw.
      The majority of the old functions have been modified. It will break most, if not all, scripts using the old UDF.
      These commands should work on every server following either RFC 1459 (legacy) or RFC 2812 (preferred).
       
      Potential Uses:
      IRC Chat Clients
      Chatroom Integration for software
      IRC Bots for Channel / Server Administration
      IRC Bots for Games such as Hangman, Mafia, and WereWolf
      Remote Administration without having to setup your own AutoIt server


      Functions:
      _IRCChannelInvite
      _IRCChannelJoin
      _IRCChannelKick
      _IRCChannelPart
      _IRCChannelTopic
      _IRCConnect
      _IRCDisconnect
      _IRCGetMsg
      _IRCMultiMode
      _IRCMultiSendMsg
      _IRCRaw
      _IRCSelfOper
      _IRCSelfSetNick
      _IRCSelfSetStatus
      _IRCServerPing
      _IRCServerPong
      _IRCServerTime
      _IRCServerVersion
       
      Extra Functions:
      _IRCReplyTo (IRCExtras.au3)
      _IRCStripSpecial (IRCExtras.au3)
       
      Downloads:
       
      Additional Links:
      Chips' Old UDF Topic:

       
      DISCLAIMER:
      While these downloads are more stable than the ones above, I do not have time to thoroughly test all functions and variable entries. If something doesn't work as expected or gives you an error please check @error and @extended variables then create a reply to this topic.

      Changelog:
      09/06/2016: IRC.au3 Fixed : Updated Headers to UDF-spec (- instead of =) _IRCGetMsg Fixed : Incorrect Return Value On Error _IRCStripSpecial Added : Better documentation of Flags _IRCMultiSendMsg Added : Better documentation of Flags _IRCMultiSendMsg Fixed : Max Message Size based on https://forums.unrealircd.org/viewtopic.php?t=6811 Updated all files to consider themselves a standalone install by default All Functions that didn't Return anything now return Number of bytes sent Slight Performance Improvements by using Parameter Gating instead of Single Input Single Output 07/21/2016: Example.au3 Fixed : Includes Example.au3 Renamed: IRC_Example.au3 IRC.au3 Changed: Minor Performance Improvements 04/18/2016: IRCConstants.au3 Updated: A Ton of New Constants added IRCMultiSendMsg Added : Color Example Increased TCP Timeout in all Examples 04/13/2016: CUI.au3 Updated: Errors now output to Error Stream in Console (C/G)UI.au3 Fixed : Userlists (FOR REAL THIS TIME) by being sure to get the current channel Removed: Duplicate Constants File Include Removed: Local Declaration inside of While loop for Performance Updated: TCPTimeout Increased Updated: $sTemp renamed $sStrip for Readibility Example.au3 Updated: TCPTimeout Increased GUI_Client.au3 Renamed: GUI.au3 _IRCStripSpecial Added : Parameter Checking Updated: Documentation _IRCMultiSendMsg Added : Additional flags for Message Type (POSSIBLY SCRIPT BREAKING if using $_bTrim!) Updated: Example to show new flags Updated: Increase Max Message Size from 368 To 436 04/09/2016: IRC.au3 Updated: All Documentation Added : Now has a Constaznts file _IRCConnnect Fixed : Now PROPERLY returns any errors _IRCGetMsg Removed: $_iChars parameter since it gets one packet at a time and parsing is easier _IRCReplyTo Fixed : Now properly returns username _IRCStripSpecial Added : Now uses Constants File All files are now in a single ZIP Includes 2 basic IRC "clients", a CUI, and a GUI 07/15/2015: Example.au3 Added : Improved Debugging   Updated: All Space Indents to Tab Idents   IRC.au3 Removed: Exception skipping @error = -1 in IRCGetMsg() as 3.3.14.0 fixed it 07/15/2015: Example.au3 Added : Ping Timeout Fixed : Userlist clipping of last user IRC.au3 Fixed : IRCGetMsg() Hang 07/08/2015: Example.au3 Fixed : User Lists   Fixed : Nickname now switches to backup nickname if first choice is already in use IRC.au3 Added : UDF Index Added : #include-once Updated: All Functions updated to Single Entry, Single Exit Updated: Now passes Au3Check on -q -d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7 01/15/2015: Example.au3 Fixed : Ampersand channels causing a crash 12/20/2014: Example.au3 Fixed : Nicks not updating on all channel lists when a user changed their nick Fixed : Nicks not deleting on all channel lists when a user quits the network 12/19/2014: Example.au3 Added : User lists Added : Channel lists Added : Bot keeps track of own nick Added : Secondary nick in case first nick choice is in use. Added : Extremely Minor performance improvements _IRCConnect Added : Improved parameter checking _IRCGetMsg Updated: Now only retrieves one packet by default (MAY be script breaking) 10/14/2014: Example.au3 Added : Shutdown TCP on exit Fixed : $Recipient now gets the actual Recipient instead of the 3rd message Added : Now exits when told to quit. IRC.au3 Added : Improved Error Reporting (Includes @extended on error) _IRCDisconnect Added : Close Socket on Disconnect _IRCStripSpecial Added : Improved Color Stripping 09/28/2014: _IRCConnect Fixed : Checking if Mode was blank. _IRCGetMsg Fixed : Spamming of 0 and incorrectly thinking there was an error. 09/28/2014: IRC.au3 Fixed : All functions now return when errors are encountered instead of continuing _IRCConnect Added : Now returns an error if optional password failed to send _IRCGetMsg Added : Now returns an error if it failed to receive a custom amount of data _IRCServerVersion Fixed : Capitalized "Version" 09/26/2014: Example.au3 Fixed : Pings not ending with @CRLF IRCExtras.au3 Added : _IRCStripSpecial(), Cleans special characters sometimes seen in IRC 09/24/2014: Example.au3 Added : Checking for PrivMsg Fixed : Infinite loop if you removed _IRCDisconnect Updated: Bot now disconnects when receiving "!quit" instead of automatically Discontinuted BETA UDF project. 04/20/2014: IRCExtras.au3 Added : Additional IRC Functions _IRChangeNick Renamed: _IRCSelfSetNick (SCRIPT BREAKING! Fix: Replace _IRCChangeNick with _IRCSelfSetNick) _IRCGetMsg Fixed : Now no longer Splits Packets if Default option is used _IRCChannelInvite Added : Invites a User to a Channel _IRCChannelKick Added : Kick a User from a channel _IRCJoinChannel Renamed: _IRCChannelJoin (SCRIPT BREAKING! Fix: Replace _IRCJoinChannel with _IRCChannelJoin) _IRCMode Renamed: _IRCMultiMode (SCRIPT BREAKING! Fix: Replace _IRCMode with _IRCMultiMode) _IRCOper Renamed: _IRCSelfOper (SCRIPT BREAKING! Fix: Replace _IRCOper with _IRCSelfOper) _IRCPartChannel Renamed: _IRCChannelPart (SCRIPT BREAKING! Fix: Replace _IRCPartChannel with _IRCChannelPart) _IRCPing Renamed: _IRCServerPing (SCRIPT BREAKING! Fix: Replace _IRCPing with _IRCServerPing) _IRCPong Renamed: _IRCServerPong (SCRIPT BREAKING! Fix: Replace _IRCPong with _IRCServerPong) _IRCSelfSetStatus Added : Sets you AFK and un-AFK _IRCSendMessage Renamed: Renamed _IRCMultiSendMsg. (SCRIPT BREAKING Fix: Replace IRCSendMessage with IRCMultiSendMsg) _IRCSendMessageRaw Renamed: Renamed _IRCRaw (SCRIPT BREAKING! Fix: Replace _IRCSendMessageRaw with _IRCRaw) _IRCServerTime Added : Get time from a Server _IRCServerVersion Added : Get Software Version from a Server _IRCTopic Renamed: _IRCChannelTopic (SCRIPT BREAKING! Fix: Replace _IRCTopic with _IRCChannelTopic) Improved Parameter detection in all Functions Renamed Functions to show who/what they effect, MASSIVE Script Breaking. Sorry! :/ 04/06/2014: _IRCGetMsg Added : Use to get IRC Messages. _IRCSetTopic Changed: Now named _IRCTopic (SCRIPT BREAKING! Fix: Replace _IRCSetTopic with _IRCTopic) Changed: Can now be used to query topic and does so by default. Use "" to blank the topic All functions now thoroughly check their parameters Updated all functions to use @extended to some errors Fixed @error returning 0 by starting all errors at 1 instead of 0 03/20/2014: _IRCChangeMode Changed: Now named _IRCMode (SCRIPT BREAKING! Fix: Replace _IRCChangeMode with _IRCMode) Changed: $_sMode is now OPTIONAL. Allowing the command to be used to Query current mode as well _IRCConnect Fixed : Missing Colon Before $_sRealName. It should now allow Real Names with spaces _IRCDisconnect Fixed : Issue with Blank Messages. Should now properly blank to Default _IRCPing Changed: $_Server is now REQUIRED. (SCRIPT BREAKING! Fix: Specify a server as Parameter 2) _IRCSendMessage Added : $_bTrim, Trims message if too long instead of breaking up the message, Default is true _IRCSetTopic Added : Command for setting a Channel Topic Updated Most Functions to include better error checking Updated Most Channel Related Functions to check for valid channels 03/16/2014: _IRCChangeMode Added : Optional parameters for channel modes Changed: Parameter ordering Target is now before Mode (SCRIPT BREAKING! Fix: Swap Parameters 2 and 3) _IRCConnect Changed: No longer exits the script on error, instead returns TCPConnect Error Code _IRCJoinChannel Added : Now Supports Channel Passwords _IRCOper Added : Command for IRC Server Operator Login Updated All Functions to have UDF standard error codes 02/24/2014: _IRCSendMessage Changed: Split Into _IRCSendMessage and _IRCSendMessageRaw (SCRIPT BREAKING! No Simple Fix Available) 02/23/2014: Made variables comply to UDF Standards http://www.autoitscript.com/autoit3/udfs/UDF_Standards.htm Removed MsgBoxes left over from old UDF Updated / Uploaded IRC.au3 Known and Reported Bugs:
      Message output only displays ANSI characters in CUI. (Can't Fix) Freenode requires registration for part messages thus the part message in example doesn't show up (Can't fix) Messages (e.g. PRIVMSG) are not forwarded?, when it contains umlauts/german mutations and when the message only contains a dot '.' (Unconfirmed) Warnings:
      Do NOT send a lot of messages at once. MOST networks will disconnect you. SOME networks will permanently ban you. A MINORITY will harshly retailiate. Do NOT use the Sleep() function in your scripts. It prevents you from receiving any new data, can disconnect your from the network, and have other undesired consequences. Use the TimerInit() and TimerDiff() functions and possibly a message queue. To Do:
      Possibly add in SSL functionality Create More Functions for IRC commands An entire IRC daemon written in AutoIt Possibly Include Kips TCP UDF for ASync Port Listening in Example Create Additional UDFs for extras such as CTCP, DCC, and Error Lookup Experiment with having functions check for the reply and see if reliable. Upcoming Changes:
      To Be Decided
    • Cormin
      By Cormin
      My script currently reads a text file line by line. I want it to look for this the chat message below and skip the session messages. 
      There are some garbage lines that I want it to skip over. So if a line doesnt match that format then skip it. I tried experimenting with StringRegExp but I think I'm using it wrong. Heres my code
      If StringRegExp($read, '\W\d\d\w\d\d\D.\W') = Not @error Then I was hoping that this would be able to see the open bracket, 2 digits, a colon, 2 digits,  close bracket, a space and a <. But it doesn't seem to be working.
       
      Eventually I want to be able to extract the username and chat message into separate strings but I haven't got that far yet.
    • Messy_Code_Guy
      By Messy_Code_Guy
      All,
      I need some help with the following:
      1. Finding an image in a Word doc.  I have read the help file but I cannot figure out how to reference the image in the Word doc.
      2. Adding a hyperlink to that image.
      3. How would I loop the add hyperlink (text) and add hyperlink (image) to replace multiple links in a document.
      I have the add image and hyperlink working with the following code:
      $pic = "<PHOTO>" $picpath = IniRead(@ScriptDir & "\Config\Config.ini", "User Info", "Picture", 0) Local $oRange = _Word_DocFind($oDoc, $pic) _Word_DocPictureAdd($oDoc, $picpath, Default, Default, $oRange) _Word_DocFindReplace($oDoc, $pic, "", Default, 0, True, True) If @error Then $file1 = FileOpen("C:\Tech\Log_Files\_Error_Logs\Error_LOG.txt", 9) _FileWriteLog($file1, "," & @ComputerName & "," & @UserName & ",Error adding a picture to the document. " & $picpath & " " & " @error = " & @error & " @extended = " & @extended) FileClose($file1) EndIf $Link = "<LINKEDIN>" $LinkedIn = IniRead(@ScriptDir & "\Config\Config.ini", "User Info", "LinkedIn", 0) Local $oRange = _Word_DocFind($oDoc, $Link) _Word_DocLinkAdd($oDoc, $oRange, $LinkedIn, Default, "Click here to visit my LinkedIn page. " & @CRLF & $LinkedIn, "LinkedIn") If @error Then $file1 = FileOpen("C:\Tech\Log_Files\_Error_Logs\Error_LOG.txt", 9) _FileWriteLog($file1, "," & @ComputerName & "," & @UserName & ",Error adding a link to the document. " & $LinkedIn & " " & " @error = " & @error & " @extended = " & @extended) FileClose($file1) EndIf I just can't figure out how to find the images in a Word doc.
      Thanks for reading my post!
    • InunoTaishou
      By InunoTaishou
      I think RichEdit has been my favorite thing I've ever discovered on AutoIt lol. In my quest to add in more html tags to my _StringToRichEditArray I needed a way to do href! There was an example I found that I followed but it didn't format correctly and didn't work 100% but it gave me a good base. Think I'll tackle inserting an image next, not looking forward to that. If anyone has an idea on how to do it let me know.
      Known issues (these will cause the hyperlink to lose the +li attribute after the RichEdit is updated):
      The hyperlink and friendly text are appended/inserted (directly adjacent to a non whitespace) but the hyperlink is not a valid hyperlink. Changing the char color for the control causes the hyperlink to lose it's hyperlink color (the light blue). Fix for Issue 1:
      Use the full URL for the hyperlink (https://www.autoitscript.com/site/ instead of www.autoitscript.com/site) Use any hyperlink with any friendly text that does not have www at the beginning (Hyperlink: www.google.com, Friendly Text: google.com) Use any hyperlink with any, or no, friendly text, but have a whitespace to the left of the hyperlink. Fix for Issue 2:
      I have no fix. Updated RichEdit Hyperlink.au3
      Demo
      Original Post, outdated: Had a problem with inserting/appending hyperlinks that pointed to the local computer. (C:\Windows\)
       
       
    • AoRaToS
      By AoRaToS
      s!mpL3 LAN Messenger as the name suggests is a messenger designed and developed to offer chat communication over Local Area Networks while being as simple to use as possible. This project started way back in 2008 with only basic functionality and is regularly updated with new features in order to make it more useful and user friendly. What I wanted was a simple, small, serverless program that would work without installation cause that was the ideal combination for my workplace back then, so I ended up with this!

      I have attached some images from various versions:
      Check the rest below! (from various versions)

      Previous downloads: 7430 (Without counting the ones from the Downloads section.)

      Current version 2.9.8.8! [30/09/2015]  s!mpL3 LAN Messenger.zip
      [Attachment version updated to 2.9.8.8]  

      s!mpL3 LAN Messenger version 2.9.8.8 - [30/09/2015]

      1. Removed some test code that could cause message boxes to pop up for Windows versions prior to Windows 10.


      You can view/download the full change log here: ChangeLog.txt

      Tested and working on Windows XP, Windows Vista, Windows 7, Windows 8, Windows 8.1 and Windows 10.


      Things you need to know before trying it:

      1. Start the program, select one or more connections from what's available and click Connect (If a firewall notice comes up, click 'Allow' or 'Add Exception')
      When someone else on your network does the same, they will appear in your TreeView and you will appear in theirs, double click their name and chat!

      2. s!mpL3 LAN Messenger does not require a server to be running, it's standalone.

      3. On the first run an .ini file is created at @LocalAppDataDirs!mpL3 LAN Messenger which stores the settings so that they are used every time you run the application. If you delete the .ini file it will be created again (with default settings at program startup or with your selected settings if you press Save from the Preferences window).

      4. All communication is encrypted using AES so it's quite secure against Network sniffers.

      5. You can send files and folders by dragging and dropping them in a conversation window. Folders are compressed before being sent. You can also drop multiple items to be sent.

      6. There is a "Hide" button located in the tray right click context menu that will hide all open windows. You can assign a Hotkey combination from Preferences. The default combination is Ctrl+H.

      7. s!mpL3 LAN Messenger uses port 60000 by default. You can change the port used by adding "Port=****" (without quotes, stars represent numbers) to the Config file described above. Communication is UDP.

      8. There is an Updater feature you can use to always have the latest available version, you only need an internet connection for that to work. You might need to clear your Internet Explorer Temporary Files in order for it to find an updated version.

      9. You can Hide + Lock s!mpL3 LAN Messenger so it'll require a password in order to "Appear". To enable this, go to the Security Preferences.

      10. Note that versions after 2.9.8.1 are not compatible with previous versions due to the encryption used being changed. I recommend using the latest version, or at least use the same version over the LAN.


      Important Notice:

      I will not be releasing the source code, however, I might share some parts of code if requested...
      If you choose to decompile this software, don't release the source code.



×