-
Notifications
You must be signed in to change notification settings - Fork 2
/
ReadTwitchChat.cs
87 lines (71 loc) · 2.31 KB
/
ReadTwitchChat.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.ComponentModel;
using System.Net.Sockets;
using System.IO;
public class ReadTwitchChat : MonoBehaviour
{
[Header("Settings")]
[SerializeField] private float _RefreshConnectionTimer = 60;
private float _Timer;
[Header("Twitch")]
private TcpClient twitchClient;
private StreamReader reader;
private StreamWriter writer;
[SerializeField] private string _Username = ""; //Twitch user name
[SerializeField] private string _OauthToken = ""; //Get token from https://twitchapps.com/tmi
[SerializeField] private string _Channelname = ""; //Twitch channel name
void Start()
{
Connect();
}
void Update()
{
//Check connection
if (!twitchClient.Connected)
Connect();
_Timer -= 1 * Time.deltaTime;
if (_Timer <= 0)
{
Connect();
_Timer = _RefreshConnectionTimer;
}
ReadChat();
}
private void Connect()
{
twitchClient = new TcpClient("irc.chat.twitch.tv", 6667);
reader = new StreamReader(twitchClient.GetStream());
writer = new StreamWriter(twitchClient.GetStream());
writer.WriteLine("PASS " + _OauthToken);
writer.WriteLine("NICK " + _Username);
writer.WriteLine("USER " + _Username + " 8 * :" + _Username);
writer.WriteLine("JOIN #" + _Channelname);
writer.Flush();
}
private void ReadChat()
{
if (twitchClient.Available > 0)
{
var message = reader.ReadLine();
if (message.Contains("PRIVMSG"))
{
//Split
var splitPoint = message.IndexOf("!", 1);
var chatName = message.Substring(0, splitPoint);
//Name
chatName = chatName.Substring(1);
//Message
splitPoint = message.IndexOf(":", 1);
message = message.Substring(splitPoint + 1);
print(string.Format("{0}: {1}", chatName, message));
if (message.ToLower().Contains("example"))
{
Debug.Log("<color=green>" + chatName + " has used the command example </color>");
}
}
}
}
}