-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
322 lines (295 loc) · 10.5 KB
/
Program.cs
File metadata and controls
322 lines (295 loc) · 10.5 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
using System.Timers;
using Fleck;
using TwitchLib.Client;
using TwitchLib.Api;
using TwitchLib.Client.Events;
using TwitchLib.Client.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
// when publishing, use the command dotnet publish /p:Configuration=Release /p:PublishProfile=FolderProfile
namespace TwitchInteract
{
public class Program
{
public static IWebSocketConnection pub_socket;
static ManualResetEvent _quitEvent = new ManualResetEvent(false);
public static System.Timers.Timer ChatCheckTimer;
public static System.Timers.Timer UpdateViewerCount;
public static WebSocketServer server;
public static TwitchAPI API;
public static bool VotingTime = false;
public static bool AnarchyMode = false;
public static bool ChatBossMode = false;
public static ConnectionCredentials creds;
public static Config config;
public static void Main(string[] args)
{
Console.Title = "Twitch Interact";
LoadConfig();
Console.CancelKeyPress += (sender, eArgs) => {
_quitEvent.Set();
eArgs.Cancel = true;
};
TGM_Init();
_quitEvent.WaitOne();
Console.WriteLine("Program has ended, press any key to close this window.");
Console.ReadKey();
}
private static void LoadConfig()
{
config = new Config();
string configPath = Path.Combine(Directory.GetCurrentDirectory(), "config.json");
if (File.Exists(configPath))
{
Console.WriteLine("config.json exists, loading...");
config = JsonConvert.DeserializeObject<Config>(File.ReadAllText(configPath), new JsonSerializerSettings
{
Error = delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs e)
{
Console.WriteLine("Could not read config.json correctly, error: ");
Console.WriteLine(e.ToString());
Console.WriteLine("You will be prompted for the bot's info again, and this will delete the previous config.json file. If you do not wish to continue, press CTRL + C or close the window.");
e.ErrorContext.Handled = true;
PromptForNewConfig(configPath);
}
});
}
else
{
PromptForNewConfig(configPath);
}
creds = new ConnectionCredentials(config.BotName, config.BotOauth);
API = new TwitchAPI() { Settings = { ClientId = config.BotName, AccessToken = config.BotOauth } };
}
static void PromptForNewConfig(string configPath)
{
Console.WriteLine("Enter your bot's name.");
config.BotName = Console.ReadLine();
Console.WriteLine("Enter your bot's access token. You can paste by right clicking in the console window. (https://twitchtokengenerator.com)");
config.BotOauth = Console.ReadLine();
Console.WriteLine("Enter your bot's client ID.");
config.BotClientID = Console.ReadLine();
Console.WriteLine("What Twitch channel do you want to monitor?");
config.TwitchChannel = Console.ReadLine();
Console.WriteLine("What's the maximum amount of seconds between any two chat messages in your stream? (If you have frequent chatters, set this to 10 or lower. 30 is a good default.)");
config.ConfirmConnectionIntervalInSeconds = Int32.Parse(Console.ReadLine());
File.WriteAllText(configPath, JsonConvert.SerializeObject(config));
}
static void TGM_Init()
{
UpdateViewerCount = new System.Timers.Timer();
UpdateViewerCount.Elapsed += UpdateViewers;
UpdateViewerCount.Interval = 15000;
UpdateViewerCount.Enabled = false;
ChatCheckTimer = new System.Timers.Timer();
ChatCheckTimer.Elapsed += Program.TGM_Close;
ChatCheckTimer.Interval = config.ConfirmConnectionIntervalInSeconds * 1000;
ChatCheckTimer.Enabled = false;
Program.server = new WebSocketServer("ws://0.0.0.0:8765")
{
RestartAfterListenError = true
};
Bot bot = new Bot(creds, config.TwitchChannel);
server.Start(socket =>
{
Program.pub_socket = socket;
socket.OnOpen = () =>
{
Console.WriteLine("Open server");
ChatCheckTimer.Start();
//UpdateViewerCount.Start();
};
socket.OnClose = () =>
{
Console.WriteLine("Close server");
ChatCheckTimer.Stop();
//UpdateViewerCount.Stop();
};
socket.OnMessage = message => MessageHandler(message, socket);
socket.OnError = (Exception) =>
{
Console.WriteLine("Socket error: ", Exception.ToString());
};
});
void MessageHandler(string message, IWebSocketConnection socket)
{
if (message != "ConnTest")
{
ConsoleColor prevColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(message + " " + DateTime.Now.ToString("hh:mm:ss"));
Console.ForegroundColor = prevColor;
}
switch (message)
{
case "Connected Message":
Console.WriteLine("WOO HOO! We connected!");
break;
case "VoteTime":
VotingTime = true;
break;
case "VoteOver":
VotingTime = false;
break;
case "anarchymode":
AnarchyMode = true;
Console.WriteLine("Anarchy Mode: On");
break;
case "democracymode":
AnarchyMode = false;
Console.WriteLine("Democracy Mode: On");
break;
default:
if (message.StartsWith("VoteActions"))
{
var actions = message.Split(';');
for (int i = 0; i < actions.Count(); i++)
{
if (i == 0) continue;
if (!Bot.SilentMode) Bot.client.SendMessageAsync(config.TwitchChannel, actions[i]);
//socket.Send(actions[i]);
}
}
if (message.StartsWith("ChatBossStatus"))
{
var args = message.Split(';');
ChatBossMode = Boolean.Parse(args[1]);
}
break;
}
}
//TODO: BROKEN
async void UpdateViewers(object source, ElapsedEventArgs e)
{
if (pub_socket != null && pub_socket.IsAvailable)
{
var chatters = await Task.Run(() => API.Helix.Chat.GetChattersAsync(config.TwitchChannel, config.TwitchChannel));
Console.WriteLine("Viewers: " + chatters.Total);
try
{
await pub_socket.Send("Viewers;" + chatters.Total.ToString());
}
catch (Fleck.ConnectionNotAvailableException)
{
Console.WriteLine("Cannot send viewer info if we are closing!");
}
}
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Initialized...");
}
static void TGM_Close(object source, ElapsedEventArgs e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(String.Format("No chat messages have been posted in the last {0} seconds! This is a bug, restarting.", ChatCheckTimer.Interval / 1000));
Console.ForegroundColor = ConsoleColor.Gray;
UpdateViewerCount.Dispose();
ChatCheckTimer.Dispose();
pub_socket?.Close();
server.Dispose();
Bot.client.DisconnectAsync();
TGM_Init();
}
}
class Bot
{
public static TwitchClient client;
readonly bool PrintTwitchChat = true;
public static bool SilentMode = false;
public Bot(ConnectionCredentials credentials, string TwitchChannel)
{
client = new TwitchClient();
client.Initialize(credentials, TwitchChannel);
Console.WriteLine($"Attempting to connect to ${TwitchChannel}");
client.OnJoinedChannel += Client_OnJoinedChannel;
client.OnMessageReceived += Client_OnMessageReceived;
client.OnNewSubscriber += Client_OnNewSubscriber;
client.OnConnected += Client_OnConnected;
client.ConnectAsync();
}
private async Task Client_OnJoinedChannel(object sender, OnJoinedChannelArgs e)
{
Console.WriteLine("Connected to chat successfully!");
if (!SilentMode) await client.SendMessageAsync(e.Channel, "Connected to chat successfully!");
}
private async Task Client_OnConnected(object sender, OnConnectedEventArgs e)
{
Console.WriteLine($"Connected to Twitch!");
}
private async Task Client_OnMessageReceived(object sender, OnMessageReceivedArgs e)
{
if (e.ChatMessage.Message[0] == '!')
{
string cmd = e.ChatMessage.Message.Substring(1);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(DateTime.Now.ToString("hh:mm:ss") + " - Received command: " + cmd);
if (cmd == "attack")
{
if (Program.ChatBossMode)
{
int damage = 1;
if (e.ChatMessage.UserDetail.IsSubscriber) damage = 2;
if (e.ChatMessage.Bits >= 100) damage += e.ChatMessage.Bits / 50;
damage *= Math.Min(Math.Max(e.ChatMessage.SubscribedMonthCount, 3), 1); // max believable damage is around 66 (1000 bits), i might clamp it
string message = "{0} has dealt {1} damage to the boss!";
Console.WriteLine(String.Format(message, e.ChatMessage.Username, damage));
if (Program.pub_socket != null) await Program.pub_socket.Send("AttackBoss;" + damage + ";" + e.ChatMessage.Username);
}
}
else if (cmd == "silentmode")
{
if (e.ChatMessage.UserDetail.IsModerator)
{
SilentMode = !SilentMode;
await client.SendMessageAsync(Program.config.TwitchChannel, "Silent mode: " + SilentMode);
}
}
else if (cmd != "attack")
{
if (Program.VotingTime)
{
if (Program.pub_socket != null) await Program.pub_socket.Send("VoteInfo\n" + e.ChatMessage.Username + "\n" + cmd);
}
else if (Program.AnarchyMode)
{
if (Program.pub_socket != null) await Program.pub_socket.Send(cmd.ToLower());
}
}
}
else
{
if (PrintTwitchChat)
{
if (Program.pub_socket != null && Program.pub_socket.IsAvailable)
{
await Program.pub_socket.Send("PrintTwitchChat\n" + e.ChatMessage.Username + "\n" + e.ChatMessage.Message);
}
}
}
Program.ChatCheckTimer.Stop();
Program.ChatCheckTimer.Start();
}
private Task Client_OnNewSubscriber(object sender, OnNewSubscriberArgs e)
{
if (Program.ChatBossMode)
{
int damage = 5;
if (e.Subscriber.MsgParamSubPlan == TwitchLib.Client.Enums.SubscriptionPlan.Tier2) damage *= 2;
else if (e.Subscriber.MsgParamSubPlan == TwitchLib.Client.Enums.SubscriptionPlan.Tier3) damage *= 4;
string message = "{0} has subscribed and dealt {1} damage to the boss!";
Console.WriteLine(String.Format(message, e.Subscriber.DisplayName, damage));
Program.pub_socket.Send("AttackBoss;" + damage + ";" + e.Subscriber.DisplayName);
}
return Task.CompletedTask;
}
}
[Serializable]
public class Config
{
public string BotName { get; set; }
public string BotOauth { get; set; }
public string BotClientID { get; set; }
public string TwitchChannel { get; set; }
public int ConfirmConnectionIntervalInSeconds { get; set; } = 30;
}
}