Advertisement
ShadowTzu

Connect to Twitch

Mar 12th, 2015
626
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 17.45 KB | None | 0 0
  1. 'Coded by ShadowTzu
  2. 'Free to use
  3.  
  4. 'Website: http://tzu3d.weebly.com
  5. 'Youtube: https://www.youtube.com/user/shadowtzu
  6. 'Twitter: https://twitter.com/shadowtzu
  7. 'Facebook: https://www.facebook.com/Tzu3d
  8. 'Twitch: http://www.twitch.tv/shadowtzu
  9. 'my 3D engine, Tzu3D: http://shadowtzu.free.fr
  10.  
  11. 'Example:
  12. ' Private mTwitchChat As TwitchChat
  13.  
  14. ' [...]
  15.  
  16. ' mTwitchChat = New TwitchChat("username", "oauth:TOKEN", "#shadowtzu", AddressOf Communicate)
  17. ' mTwitchChat.Connect()
  18. '
  19. ' [...]
  20. '
  21.  
  22. ' Public Function Communicate(user As String, Message As String) As String
  23. ' Console.WriteLine("User '" & user & "' Say: " & Message)
  24.  
  25. ' if you return a string, your bot say it in the chat
  26. ' Return String.Empty
  27. ' End Function
  28.  
  29. Imports System.Net
  30. Imports System.Text
  31. Imports System.Net.Sockets
  32.  
  33. ''' <summary>
  34. ''' Connecting to Twitch Chat (IRC protocol)
  35. ''' </summary>
  36. ''' <remarks></remarks>
  37. Public Class TwitchChat
  38.     Private WithEvents mSocket As SocketClient
  39.     Private mNick As String
  40.     Private mPass As String
  41.     Private mPort As Integer
  42.     Private mIp As String
  43.     Private mChannel As String
  44.  
  45.     Private IsWaitingConnected As Boolean = True
  46.  
  47.     Public Structure struct_Message
  48.         Public Who As String
  49.         Public User As String
  50.         Public Code As String
  51.         Public Message As String
  52.     End Structure
  53.     Public Delegate Function User_Message(User As String, Message As String) As String
  54.     Private mCom As User_Message
  55.  
  56.     ''' <summary>
  57.     ''' Constructor
  58.     ''' </summary>
  59.     ''' <param name="Nick">username</param>
  60.     ''' <param name="OAuth_token">OAuth token can be get here http://www.twitchapps.com/tmi </param>
  61.     ''' <param name="Channel">channel : #channelname</param>
  62.     ''' <param name="CallBack_Communicate">create a callback function: Public Function Communicate(User As String, Message As String) As String ... End Function and give address: AddressOf Communicate</param>
  63.     ''' <remarks></remarks>
  64.     Public Sub New(Nick As String, OAuth_token As String, Channel As String, CallBack_Communicate As User_Message)
  65.         mIp = "irc.twitch.tv"
  66.         mPort = 6667
  67.         mPass = OAuth_token
  68.         mNick = Nick
  69.         mChannel = Channel
  70.         mCom = CallBack_Communicate
  71.         mSocket = New SocketClient()
  72.     End Sub
  73.  
  74.     Public Sub Connect()
  75.         mSocket.Connect(mIp, mPort)
  76.     End Sub
  77.  
  78.     Public Sub Write(Data As String)
  79.         mSocket.Write(Data & vbCrLf)
  80.     End Sub
  81.  
  82.     Public Sub Say(Message As String)
  83.         If Message = "" Then Exit Sub
  84.         Write(String.Format("PRIVMSG {0} :{1}", mChannel, Message))
  85.     End Sub
  86.  
  87.     Public Sub Quit(Message As String)
  88.         Write(String.Format("QUIT :{0}", Message))
  89.     End Sub
  90.  
  91.     Private Sub Console_WriteLine(Message As String)
  92.         If Not Debug Then Exit Sub
  93.         Console.WriteLine(Message)
  94.     End Sub
  95.  
  96.     Private Sub NetworkCom(Stream As String)
  97.         Dim data() As String = Split(Stream, vbCrLf)
  98.         For i As Integer = 0 To data.Count - 1
  99.             Analyse_Stream(data(i))
  100.         Next
  101.     End Sub
  102.  
  103.     Private Rep As struct_Message
  104.     Private Viewers_list As String = Nothing
  105.     Private End_List_Receive As Boolean = False
  106.     Private Sub Analyse_Stream(stream As String)
  107.         If stream = "" Then Exit Sub
  108.         Rep = Decode(stream)
  109.  
  110.         Select Case Rep.Code.ToUpper
  111.             Case "353"
  112.                 Dim Viewers As String = Split(Rep.Message, ":")(1)
  113.                 Viewers_list &= Viewers
  114.             Case "366"
  115.                 Console_WriteLine("Viewers List: " & Viewers_list)
  116.                 End_List_Receive = True
  117.             Case "PING"
  118.                 Write("PONG " & Clean_Message(Rep.Message))
  119.             Case "PRIVMSG"
  120.                 Say(mCom(Rep.User, Clean_Message(Rep.Message)))
  121.             Case "JOIN"
  122.                 If End_List_Receive Then
  123.                     Say("Hello!")
  124.                 End If
  125.         End Select
  126.     End Sub
  127.  
  128.     Private Function Decode(line As String) As struct_Message
  129.         Dim Msg As struct_Message = Nothing
  130.  
  131.         If line = "" Then Return Msg
  132.         Dim splitted() As String = Split(line, " ")
  133.  
  134.         Msg.Who = splitted(0)
  135.         Dim EndName As Integer = Msg.Who.IndexOf("!")
  136.         If EndName > -1 Then
  137.             Msg.User = Clean_Message(Msg.Who.Substring(0, EndName))
  138.         End If
  139.         Msg.Code = splitted(1)
  140.         For i As Integer = 2 To splitted.Count - 1
  141.             Msg.Message &= splitted(i)
  142.             If i < splitted.Count - 1 Then Msg.Message &= " "
  143.         Next
  144.         Return Msg
  145.     End Function
  146.  
  147.     Private Function Clean_Message(message As String) As String
  148.         If message.Contains(":") Then
  149.             Return Split(message, ":")(1)
  150.         Else
  151.             Return message
  152.         End If
  153.     End Function
  154.  
  155. #Region "Event"
  156.     Private Sub mSocket_OnClose() Handles mSocket.OnClose
  157.         Console_WriteLine("Closed!")
  158.     End Sub
  159.  
  160.     Private Sub mSocket_OnCloseFailed(Exception As Exception) Handles mSocket.OnCloseFailed
  161.         Console_WriteLine(Exception.Message)
  162.     End Sub
  163.  
  164.     Private Sub mSocket_OnConnect() Handles mSocket.OnConnect
  165.         Console_WriteLine("Connected!")
  166.  
  167.         mSocket.Write(String.Format("PASS {0} {1}", mPass, vbCrLf))
  168.         mSocket.Write("NICK " & mNick.ToLower & vbCrLf)
  169.         mSocket.Write("JOIN #shadowtzu" & vbCrLf)
  170.  
  171.         IsWaitingConnected = False
  172.     End Sub
  173.  
  174.     Private Sub mSocket_OnConnectFailed(Exception As Exception) Handles mSocket.OnConnectFailed
  175.         Console_WriteLine(Exception.Message)
  176.     End Sub
  177.  
  178.     Private Sub mSocket_OnRead(Stream As String) Handles mSocket.OnRead
  179.         NetworkCom(Stream)
  180.     End Sub
  181.  
  182.     Private Sub mSocket_OnReadFailed(Exception As Exception) Handles mSocket.OnReadFailed
  183.         Console_WriteLine(Exception.Message)
  184.     End Sub
  185.  
  186.     Private Sub mSocket_OnWrite() Handles mSocket.OnWrite
  187.         Console_WriteLine("Send data")
  188.     End Sub
  189.  
  190.     Private Sub mSocket_OnWriteFailed(Exception As Exception) Handles mSocket.OnWriteFailed
  191.         Console_WriteLine(Exception.Message)
  192.     End Sub
  193. #End Region
  194.  
  195. #Region "Properties"
  196.     Public ReadOnly Property Connected As Boolean
  197.         Get
  198.             Return mSocket.IsConnected Or IsWaitingConnected
  199.         End Get
  200.     End Property
  201.  
  202.     Public Property Debug As Boolean
  203. #End Region
  204. End Class
  205.  
  206.  
  207. ''' <summary>
  208. ''' Socket class, I don't write it, I do not know where I found this code
  209. ''' </summary>
  210. ''' <remarks></remarks>
  211. Public Class SocketClient
  212.     Implements IDisposable
  213.  
  214.  
  215. #Region "Declares"
  216.     Private TcpClient As TcpClient
  217.     Private ReadBuffer(1023) As Byte
  218.     Private SyncInvoke As System.ComponentModel.ISynchronizeInvoke
  219. #End Region
  220.  
  221. #Region "Events"
  222.  
  223.     Public Event OnConnect()
  224.     Public Event OnConnectFailed(ByVal Exception As Exception)
  225.  
  226.     Public Event OnWrite()
  227.     Public Event OnWriteFailed(ByVal Exception As Exception)
  228.  
  229.     Public Event OnRead(ByVal Stream As String)
  230.     Public Event OnReadFailed(ByVal Exception As Exception)
  231.  
  232.     Public Event OnClose()
  233.     Public Event OnCloseFailed(ByVal Exception As Exception)
  234.  
  235. #End Region
  236.  
  237. #Region "Constructors"
  238.  
  239.     Public Sub New(Optional ByVal Sync As System.ComponentModel.ISynchronizeInvoke = Nothing)
  240.         TcpClient = New TcpClient
  241.         SyncInvoke = Sync
  242.     End Sub
  243.  
  244.     Public Sub New(ByVal TcpClient As TcpClient, Optional ByVal Sync As System.ComponentModel.ISynchronizeInvoke = Nothing)
  245.         Me.TcpClient = TcpClient
  246.         SyncInvoke = Sync
  247.         BeginRead()
  248.     End Sub
  249.  
  250. #End Region
  251.  
  252. #Region "Functions"
  253.  
  254.     Public Sub Connect(ByVal Ip As String, ByVal Port As Integer)
  255.         BeginConnect(Ip, Port)
  256.     End Sub
  257.  
  258.     Public Sub Write(ByVal Data As String)
  259.         BeginWrite(Data)
  260.     End Sub
  261.  
  262.     Public Sub Close()
  263.  
  264.         If (TcpClient Is Nothing) Then Exit Sub
  265.  
  266.         Try
  267.  
  268.             TcpClient.Close()
  269.             TcpClient = New TcpClient
  270.  
  271.             OnCloseInvoker()
  272.  
  273.         Catch Exception As Exception
  274.             OnCloseFailedInvoker(Exception)
  275.         End Try
  276.  
  277.     End Sub
  278.  
  279. #End Region
  280.  
  281. #Region "Begins"
  282.  
  283.     Private Sub BeginConnect(ByVal Ip As String, ByVal Port As Integer)
  284.  
  285.         If (TcpClient Is Nothing) Then Exit Sub
  286.  
  287.         Try
  288.  
  289.             TcpClient.BeginConnect(Ip, Port, AddressOf ConnectCallBack, Nothing)
  290.  
  291.         Catch Exception As Exception
  292.             OnConnectFailedInvoker(Exception)
  293.         End Try
  294.  
  295.     End Sub
  296.  
  297.     Private Sub BeginRead()
  298.  
  299.         If (TcpClient Is Nothing) OrElse (NetworkStream Is Nothing) OrElse (Not IsConnected) OrElse (Not NetworkStream.CanRead) Then Exit Sub
  300.  
  301.         Try
  302.  
  303.             NetworkStream.BeginRead(ReadBuffer, 0, ReadBuffer.Length, AddressOf ReadCallBack, Nothing)
  304.  
  305.         Catch Exception As Exception
  306.             OnReadFailedInvoker(Exception)
  307.         End Try
  308.  
  309.     End Sub
  310.  
  311.     Private Sub BeginWrite(ByVal Data As String)
  312.  
  313.         If (TcpClient Is Nothing) OrElse (NetworkStream Is Nothing) OrElse (Not IsConnected) OrElse (Not NetworkStream.CanWrite) Then Exit Sub
  314.  
  315.         Try
  316.  
  317.             Dim WriteBuffer() As Byte = Encoding.ASCII.GetBytes(Data)
  318.             NetworkStream.BeginWrite(WriteBuffer, 0, WriteBuffer.Length, AddressOf WriteCallBack, Nothing)
  319.  
  320.         Catch Exception As Exception
  321.             OnWriteFailedInvoker(Exception)
  322.         End Try
  323.  
  324.     End Sub
  325.  
  326. #End Region
  327.  
  328. #Region "CallBacks"
  329.  
  330.     Private Sub ConnectCallBack(ByVal IAsyncResult As IAsyncResult)
  331.  
  332.         If (TcpClient Is Nothing) OrElse (IAsyncResult Is Nothing) Then Exit Sub
  333.  
  334.         Try
  335.  
  336.             TcpClient.EndConnect(IAsyncResult)
  337.             BeginRead()
  338.  
  339.             OnConnectInvoker()
  340.  
  341.         Catch Exception As Exception
  342.             OnConnectFailedInvoker(Exception)
  343.         End Try
  344.  
  345.     End Sub
  346.  
  347.     Private Sub ReadCallBack(ByVal IAsyncResult As IAsyncResult)
  348.  
  349.         If (TcpClient Is Nothing) OrElse (NetworkStream Is Nothing) OrElse (IAsyncResult Is Nothing) OrElse (Not IsConnected) Then Exit Sub
  350.  
  351.         Try
  352.  
  353.             Dim ReadBytes As Integer = NetworkStream.EndRead(IAsyncResult)
  354.  
  355.             If ReadBytes > 0 Then
  356.  
  357.                 Dim Stream As String = Encoding.Default.GetString(ReadBuffer).Replace(Chr(0), String.Empty)
  358.  
  359.                 Array.Clear(ReadBuffer, 0, ReadBuffer.Length - 1)
  360.                 BeginRead()
  361.  
  362.                 OnReadInvoker(Stream)
  363.  
  364.             Else
  365.                 Close()
  366.             End If
  367.  
  368.         Catch Exception As Exception
  369.             OnReadFailedInvoker(Exception)
  370.         End Try
  371.  
  372.     End Sub
  373.  
  374.     Private Sub WriteCallBack(ByVal IAsyncResult As IAsyncResult)
  375.  
  376.         If (TcpClient Is Nothing) OrElse (NetworkStream Is Nothing) OrElse (IAsyncResult Is Nothing) OrElse (Not IsConnected) Then Exit Sub
  377.  
  378.         Try
  379.  
  380.             NetworkStream.EndWrite(IAsyncResult)
  381.             OnWriteInvoker()
  382.  
  383.         Catch Exception As Exception
  384.             OnWriteFailedInvoker(Exception)
  385.         End Try
  386.  
  387.     End Sub
  388.  
  389. #End Region
  390.  
  391. #Region "Inter-Threading"
  392.  
  393.     Private Delegate Sub DelegateOnConnectHandler()
  394.     Private Delegate Sub DelegateOnConnectFailedHandler(ByVal Exception As Exception)
  395.  
  396.     Private Delegate Sub DelegateOnWriteHandler()
  397.     Private Delegate Sub DelegateOnWriteFailedHandler(ByVal Exception As Exception)
  398.  
  399.     Private Delegate Sub DelegateOnReadHandler(ByVal Stream As String)
  400.     Private Delegate Sub DelegateOnReadFailedHandler(ByVal Exception As Exception)
  401.  
  402.     Private Delegate Sub DelegateOnCloseHandler()
  403.     Private Delegate Sub DelegateOnCloseFailedHandler(ByVal Exception As Exception)
  404.  
  405.     Private DelegateOnConnect As New DelegateOnConnectHandler(AddressOf RaiseOnConnectEvent)
  406.     Private DelegateOnConnectFailed As New DelegateOnConnectFailedHandler(AddressOf RaiseOnConnectFailedEvent)
  407.  
  408.     Private DelegateOnWrite As New DelegateOnWriteHandler(AddressOf RaiseOnWriteEvent)
  409.     Private DelegateOnWriteFailed As New DelegateOnWriteFailedHandler(AddressOf RaiseOnWriteFailedEvent)
  410.  
  411.     Private DelegateOnRead As New DelegateOnReadHandler(AddressOf RaiseOnReadEvent)
  412.     Private DelegateOnReadFailed As New DelegateOnReadFailedHandler(AddressOf RaiseOnReadFailedEvent)
  413.  
  414.     Private DelegateOnClose As New DelegateOnCloseHandler(AddressOf RaiseOnCloseEvent)
  415.     Private DelegateOnCloseFailed As New DelegateOnCloseFailedHandler(AddressOf RaiseOnCloseFailedEvent)
  416.  
  417.     Private Sub RaiseOnConnectEvent()
  418.         RaiseEvent OnConnect()
  419.     End Sub
  420.  
  421.     Private Sub RaiseOnConnectFailedEvent(ByVal Exception As Exception)
  422.         RaiseEvent OnConnectFailed(Exception)
  423.     End Sub
  424.  
  425.     Private Sub RaiseOnWriteEvent()
  426.         RaiseEvent OnWrite()
  427.     End Sub
  428.  
  429.     Private Sub RaiseOnWriteFailedEvent(ByVal Exception As Exception)
  430.         RaiseEvent OnWriteFailed(Exception)
  431.     End Sub
  432.  
  433.     Private Sub RaiseOnReadEvent(ByVal Stream As String)
  434.         RaiseEvent OnRead(Stream)
  435.     End Sub
  436.  
  437.     Private Sub RaiseOnReadFailedEvent(ByVal Exception As Exception)
  438.         RaiseEvent OnReadFailed(Exception)
  439.     End Sub
  440.  
  441.     Private Sub RaiseOnCloseEvent()
  442.         RaiseEvent OnClose()
  443.     End Sub
  444.  
  445.     Private Sub RaiseOnCloseFailedEvent(ByVal Exception As Exception)
  446.         RaiseEvent OnCloseFailed(Exception)
  447.     End Sub
  448.  
  449.     Private Sub OnConnectInvoker()
  450.  
  451.         If (Not SyncInvoke Is Nothing) AndAlso SyncInvoke.InvokeRequired Then
  452.             SyncInvoke.BeginInvoke(DelegateOnConnect, Nothing)
  453.         Else
  454.             RaiseOnConnectEvent()
  455.         End If
  456.  
  457.     End Sub
  458.  
  459.     Private Sub OnConnectFailedInvoker(ByVal Exception As Exception)
  460.  
  461.         If (Not SyncInvoke Is Nothing) AndAlso SyncInvoke.InvokeRequired Then
  462.             SyncInvoke.BeginInvoke(DelegateOnConnectFailed, New Object() {Exception})
  463.         Else
  464.             RaiseOnConnectFailedEvent(Exception)
  465.         End If
  466.  
  467.     End Sub
  468.  
  469.     Private Sub OnWriteInvoker()
  470.  
  471.         If (Not SyncInvoke Is Nothing) AndAlso SyncInvoke.InvokeRequired Then
  472.             SyncInvoke.BeginInvoke(DelegateOnWrite, Nothing)
  473.         Else
  474.             RaiseOnWriteEvent()
  475.         End If
  476.  
  477.     End Sub
  478.  
  479.     Private Sub OnWriteFailedInvoker(ByVal Exception As Exception)
  480.  
  481.         If (Not SyncInvoke Is Nothing) AndAlso SyncInvoke.InvokeRequired Then
  482.             SyncInvoke.BeginInvoke(DelegateOnWriteFailed, New Object() {Exception})
  483.         Else
  484.             RaiseOnWriteFailedEvent(Exception)
  485.         End If
  486.  
  487.     End Sub
  488.  
  489.     Private Sub OnReadInvoker(ByVal Stream As String)
  490.  
  491.         If (Not SyncInvoke Is Nothing) AndAlso SyncInvoke.InvokeRequired Then
  492.  
  493.             SyncInvoke.BeginInvoke(DelegateOnRead, New Object() {Stream})
  494.         Else
  495.             RaiseOnReadEvent(Stream)
  496.         End If
  497.  
  498.     End Sub
  499.  
  500.     Private Sub OnReadFailedInvoker(ByVal Exception As Exception)
  501.  
  502.         If (Not SyncInvoke Is Nothing) AndAlso SyncInvoke.InvokeRequired Then
  503.             SyncInvoke.BeginInvoke(DelegateOnReadFailed, New Object() {Exception})
  504.         Else
  505.             RaiseOnReadFailedEvent(Exception)
  506.         End If
  507.  
  508.     End Sub
  509.  
  510.     Private Sub OnCloseInvoker()
  511.  
  512.         If (Not SyncInvoke Is Nothing) AndAlso SyncInvoke.InvokeRequired Then
  513.             SyncInvoke.BeginInvoke(DelegateOnClose, Nothing)
  514.         Else
  515.             RaiseOnCloseEvent()
  516.         End If
  517.  
  518.     End Sub
  519.  
  520.     Private Sub OnCloseFailedInvoker(ByVal Exception As Exception)
  521.  
  522.         If (Not SyncInvoke Is Nothing) AndAlso SyncInvoke.InvokeRequired Then
  523.             SyncInvoke.BeginInvoke(DelegateOnCloseFailed, New Object() {Exception})
  524.         Else
  525.             RaiseOnCloseFailedEvent(Exception)
  526.         End If
  527.  
  528.     End Sub
  529.  
  530. #End Region
  531.  
  532. #Region "Properties"
  533.  
  534.     Public ReadOnly Property IsConnected As Boolean
  535.         Get
  536.  
  537.             If (TcpClient Is Nothing) Then Return False
  538.  
  539.             Try
  540.                 Return TcpClient.Connected
  541.             Catch Exception As Exception
  542.                 Return False
  543.             End Try
  544.  
  545.         End Get
  546.     End Property
  547.  
  548.     Public ReadOnly Property Ip As String
  549.         Get
  550.  
  551.             If (TcpClient Is Nothing) Then Return Nothing
  552.  
  553.             Try
  554.                 Return CType(TcpClient.Client.RemoteEndPoint, IPEndPoint).Address.ToString
  555.             Catch Exception As Exception
  556.                 Return Nothing
  557.             End Try
  558.  
  559.         End Get
  560.     End Property
  561.  
  562.     Public ReadOnly Property Port As Integer
  563.         Get
  564.  
  565.             If (TcpClient Is Nothing) Then Return Nothing
  566.  
  567.             Try
  568.                 Return CType(TcpClient.Client.RemoteEndPoint, IPEndPoint).Port
  569.             Catch Exception As Exception
  570.                 Return Nothing
  571.             End Try
  572.  
  573.         End Get
  574.     End Property
  575.  
  576.     Private ReadOnly Property NetworkStream As NetworkStream
  577.         Get
  578.  
  579.             If (TcpClient Is Nothing) Then Return Nothing
  580.  
  581.             Try
  582.                 Return TcpClient.GetStream
  583.             Catch Exception As Exception
  584.                 Return Nothing
  585.             End Try
  586.  
  587.         End Get
  588.     End Property
  589.  
  590. #End Region
  591.  
  592. #Region "IDisposable Support"
  593.     Private disposedValue As Boolean
  594.     Protected Overridable Sub Dispose(disposing As Boolean)
  595.         If Not Me.disposedValue Then
  596.             If disposing Then
  597.             End If
  598.             TcpClient.Close()
  599.             TcpClient = Nothing
  600.             Erase ReadBuffer
  601.             ReadBuffer = Nothing
  602.             SyncInvoke = Nothing
  603.         End If
  604.         Me.disposedValue = True
  605.     End Sub
  606.  
  607.     Public Sub Dispose() Implements IDisposable.Dispose
  608.         Dispose(True)
  609.         GC.SuppressFinalize(Me)
  610.     End Sub
  611. #End Region
  612.  
  613. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement