-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwitchConnection.cs
598 lines (546 loc) · 25.7 KB
/
TwitchConnection.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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
using Newtonsoft.Json;
using System.Net.Sockets;
using Terraria;
using TShockAPI;
using TwitchLib.Api.Core.Models.Undocumented.Chatters;
using TwitchLib.Api.Helix.Models.Charity.GetCharityCampaign;
using TwitchLib.Api.Helix.Models.Chat.GetChatters;
using TwitchLib.Client;
using TwitchLib.Client.Events;
using TwitchLib.Client.Models;
using TwitchLib.Communication.Clients;
using TwitchLib.Communication.Models;
namespace TerrariaKitchen
{
public class TwitchConnection
{
public string? ChannelName { get; private set; }
public Func<int, int, string, string?, bool, bool>? SpawnUnit { get; set; }
private TwitchClient? TwitchClient;
private string? apiKey;
private readonly KitchenCreditsStore Store;
private readonly KitchenConfig Config;
private readonly KitchenOverlay Overlay;
private int MessageRateLimit;
private DateTime? NextRateLimitRefresh;
public Dictionary<string, DateTime> ChatTimeout { get; private set; }
private Timer? incomeTimer;
public TwitchConnection(KitchenCreditsStore store, KitchenConfig config, KitchenOverlay overlay)
{
Store = store;
Config = config;
Overlay = overlay;
ChatTimeout = new Dictionary<string, DateTime>();
Config = config;
MessageRateLimit = 0;
Overlay.NewConnection += UpdateOverlay;
}
private void UpdateOverlay(object? sender, NetworkStream stream)
{
if (stream.CanWrite && TwitchClient?.IsConnected == true)
{
try
{
var response = KitchenOverlay.GetFrameFromString(JsonConvert.SerializeObject(new
{
@event = "initialize",
pools = Store.Pools.Select(p => new { idx = p.Index, name = p.PoolName, current = p.TotalContributions(), target = p.TargetValue() }),
waves = Store.Waves.Select(w => new { chatter = w.Chatter, current = w.CurrentMobs.Count, target = w.TargetNumber }),
}));
stream.Write(response, 0, response.Length);
}
catch
{
}
}
}
public void Announce(string txt, int Threshold = 95)
{
if (TwitchClient?.IsConnected != true)
{
return;
}
if (NextRateLimitRefresh == null || NextRateLimitRefresh < DateTime.Now)
{
NextRateLimitRefresh = DateTime.Now.AddSeconds(30);
MessageRateLimit = 0;
}
if (MessageRateLimit >= Threshold)
{
return;
}
++MessageRateLimit;
TwitchClient.SendMessage(ChannelName, txt);
}
private void Reply(ChatMessage msg, string txt, int Threshold = 95)
{
if (TwitchClient?.IsConnected != true)
{
return;
}
if (NextRateLimitRefresh == null || NextRateLimitRefresh < DateTime.Now)
{
NextRateLimitRefresh = DateTime.Now.AddSeconds(30);
MessageRateLimit = 0;
}
if (MessageRateLimit >= Threshold)
{
return;
}
++MessageRateLimit;
TwitchClient.SendReply(msg.Channel, msg.Id, txt);
}
public void Initialize(string channelName, Action onConnected, Action onDisconnected)
{
if (TwitchClient?.IsConnected == true)
{
if (TwitchClient.ConnectionCredentials.TwitchUsername == channelName)
{
return;
}
TwitchClient.Disconnect();
}
ChannelName = channelName;
var clientOptions = new ClientOptions
{
MessagesAllowedInPeriod = 95,
ThrottlingPeriod = TimeSpan.FromSeconds(30)
};
WebSocketClient customClient = new WebSocketClient(clientOptions);
TwitchClient = new TwitchClient(customClient);
TwitchClient.Initialize(new ConnectionCredentials(ChannelName, apiKey, disableUsernameCheck: true), ChannelName);
Store.CurrentChatters.Clear();
TwitchClient.OnConnected += (sender, e) =>
{
onConnected();
incomeTimer?.Dispose();
if (Config.IncomeInterval < 5)
{
// Minimum 5 seconds interval.
Config.IncomeInterval = 5;
}
incomeTimer = new Timer(Store.Income, null, TimeSpan.FromSeconds(Config.IncomeInterval), TimeSpan.FromSeconds(Config.IncomeInterval));
};
TwitchClient.OnJoinedChannel += (sender, e) =>
{
Announce("Terraria Kitchen started! Use !t buy <name> <quantity> to spawn mobs!");
};
TwitchClient.OnDisconnected += (sender, e) =>
{
onDisconnected();
incomeTimer?.Dispose();
incomeTimer = null;
Overlay.SendPacket(new { @event = "disconnect" });
};
TwitchClient.OnMessageReceived += HandleMessage;
TwitchClient.OnExistingUsersDetected += (sender, e) => {
foreach (var user in e.Users)
{
Store.CurrentChatters.Add(user.ToLower());
}
};
TwitchClient.OnUserJoined += (sender, e) => Store.CurrentChatters.Add(e.Username.ToLower());
TwitchClient.OnUserLeft += (sender, e) => Store.CurrentChatters.Remove(e.Username.ToLower());
TwitchClient.Connect();
Store.ChangeWorld(Main.worldID);
Console.WriteLine($"(Terraria Kitchen) Kitchen started for worldID: {Main.worldID}");
}
public void UpdateTime()
{
if (incomeTimer != null)
{
if (Config.IncomeInterval < 5)
{
// Minimum 5 seconds interval.
Config.IncomeInterval = 5;
}
incomeTimer.Change(TimeSpan.FromSeconds(Config.IncomeInterval), TimeSpan.FromSeconds(Config.IncomeInterval));
}
}
private void HandleMessage(object? sender, OnMessageReceivedArgs e)
{
try
{
string chatter = e.ChatMessage.Username.ToLower();
Store.CurrentChatters.Add(chatter);
if (e.ChatMessage.Message.StartsWith("!t "))
{
if (ChatTimeout.TryGetValue(chatter, out var expiry))
{
if (expiry > DateTime.Now)
{
return;
}
}
ChatTimeout[chatter] = DateTime.Now.AddSeconds(5);
var buyParams = e.ChatMessage.Message.Split(' ');
if (buyParams.Length < 2)
{
return;
}
switch (buyParams[1])
{
case "buy":
Buy(e.ChatMessage);
break;
case "pool":
Pool(e.ChatMessage);
break;
case "wave":
Wave(e.ChatMessage);
break;
case "event":
PoolEvent(e.ChatMessage);
break;
case "balance":
case "bal":
var amount = Store.GetBalance(chatter);
if (amount != -1)
{
Reply(e.ChatMessage, $"You have {amount} kitchen credits.", Threshold: 80);
}
break;
case "give":
if (buyParams.Length == 4)
{
if (Store.Give(chatter, buyParams[2].ToLower(), buyParams[3]))
{
Reply(e.ChatMessage, $"Sent {buyParams[3]} credits to {buyParams[2]}. You have {Store.GetBalance(chatter)} kitchen credits remaining.");
}
else
{
Reply(e.ChatMessage, $"Failed to give credits. You have {Store.GetBalance(chatter)} kitchen credits.");
}
}
break;
case "say":
for (int i = 0; i < Main.npc.Length; i++)
{
if (Main.npc[i].active && Main.npc[i].townNPC)
{
if (Main.npc[i].GivenName.ToLower() == chatter.ToLower())
{
NetMessage.SendData(119, -1, -1, Terraria.Localization.NetworkText.FromLiteral(string.Join(" ", buyParams.Skip(2))), number: 255, number2: Main.npc[i].position.X, number3: Main.npc[i].position.Y);
}
}
}
break;
default:
return;
}
}
}
catch (Exception ex)
{
TShock.Log.Error("(Terraria Kitchen Error) - " + ex.Message);
TShock.Log.Error(ex.StackTrace);
Console.WriteLine("(Terraria Kitchen) Invalid Chat message detected. Unable to process.");
}
}
private void PoolEvent(ChatMessage chatMessage)
{
var buyParams = chatMessage.Message.Split(' ');
if (buyParams.Length != 4)
{
return;
}
if (int.TryParse(buyParams[3], out var amount) && amount > 0 && Config.FindEvent(buyParams[2]) is KitchenEvent kEvent)
{
string chatter = chatMessage.Username.ToLower();
if (amount > Store.GetBalance(chatter))
{
Reply(chatMessage, $"Not enough credits! You have {Store.GetBalance(chatter)} kitchen credits remaining.");
return;
}
var newPool = false;
var existingPool = Store.Pools.Where(p => p.TargetEvent != null).FirstOrDefault(p => p.TargetEvent?.EventId == kEvent.EventId);
if (existingPool == null)
{
existingPool = new KitchenPool(kEvent);
Store.Pools.Add(existingPool);
newPool = true;
Overlay.SendPacket(new { @event = "poolStart", idx = existingPool.Index, name = existingPool.PoolName, target = existingPool.TargetValue() });
}
var contributed = Store.ContributePool(chatter, amount, existingPool.Index);
if (existingPool.TargetReached)
{
Overlay.SendPacket(new { @event = "poolEnd", idx = existingPool.Index });
if (existingPool.TargetEvent?.Start() == true)
{
Store.ResolvePoolPayment(existingPool);
}
}
else
{
Overlay.SendPacket(new { @event = "poolUpdate", idx = existingPool.Index, lastContribution = contributed, lastContributor = chatter, current = existingPool.TotalContributions() });
if (newPool)
{
Reply(chatMessage, $"Started a new {existingPool.PoolName} event pool with id {existingPool.Index}, you now have {Store.GetBalance(chatter)} kitchen credits remaining. Contribution: {contributed}/{existingPool.TargetValue()}.");
}
}
}
}
private void Pool(ChatMessage chatMessage)
{
var buyParams = chatMessage.Message.Split(' ');
if (buyParams.Length != 4)
{
return;
}
if (int.TryParse(buyParams[2], out var poolIdx) && int.TryParse(buyParams[3], out var amt) && amt > 0)
{
if (Store.GetPool(poolIdx) is KitchenPool existingPool)
{
var chatter = chatMessage.Username.ToLower();
if (amt > Store.GetBalance(chatter))
{
Reply(chatMessage, $"Not enough credits! You have {Store.GetBalance(chatter)} kitchen credits remaining.");
return;
}
var contributed = Store.ContributePool(chatter, amt, existingPool.Index);
if (existingPool.TargetReached)
{
Overlay.SendPacket(new { @event = "poolEnd", idx = existingPool.Index });
if (existingPool.TargetEntry is KitchenConfig.KitchenEntry entry)
{
if (SpawnUnit?.Invoke(entry.InternalName, 1, $"{existingPool.Contributions.Count(c => c.Value > 0)} customers have ", existingPool.Customer, false) == true)
{
Store.ResolvePoolPayment(existingPool);
}
else
{
Announce($"Pool #{existingPool.Index} failed to spawn due to spawn conditions not being met, please attempt to complete it later.");
}
}
else if (existingPool.TargetEvent is KitchenEvent kitchenEvent)
{
if (kitchenEvent.Start())
{
Store.ResolvePoolPayment(existingPool);
}
else
{
Announce($"Event pool #{existingPool.Index} failed to start due to conditions not being met, please attempt to complete it later.");
}
}
}
else
{
Overlay.SendPacket(new { @event = "poolUpdate", idx = existingPool.Index, lastContribution = contributed, lastContributor = chatter, current = existingPool.TotalContributions() });
}
}
}
}
private void Wave(ChatMessage chatMessage)
{
var buyParams = chatMessage.Message.Split(' ');
if (buyParams.Length < 3 || buyParams.Length > 6)
{
return;
}
var chatter = chatMessage.Username.ToLower();
var waveCommand = buyParams[2];
switch (waveCommand)
{
case "start":
if (Store.Waves.Any(a => a.Chatter == chatter))
{
Reply(chatMessage, $"You cannot start a wave when you have an existing wave in progress. You have {Store.GetBalance(chatter)} kitchen credits remaining.");
}
if (int.TryParse(buyParams[3], out var targetNumber) && targetNumber > 0 && targetNumber < 100)
{
Store.Waves.Add(new KitchenWave(chatter, targetNumber));
Overlay.SendPacket(new { @event = "waveStart", chatter, current = 0, target = targetNumber });
Reply(chatMessage, $"A new wave of size {targetNumber} has been started. You have {Store.GetBalance(chatter)} kitchen credits remaining. Chatters may use '!t wave buy {chatter} <mob_name> <amount>' to add mobs to your wave.");
}
break;
case "buy":
if (buyParams.Length != 6)
{
return;
}
if (int.TryParse(buyParams[5], out var amt) && amt > 0 && Store.Waves.FirstOrDefault(a => a.Chatter == buyParams[3]) is KitchenWave wave)
{
var mob = Config.FindEntry(buyParams[4]);
if (mob == null || mob.InternalName == 113)
{
Reply(chatMessage, $"Invalid mob. You have {Store.GetBalance(chatter)} kitchen credits remaining.");
return;
}
if (amt > mob.MaxBuys)
{
amt = mob.MaxBuys;
}
var price = mob.Price * amt;
if (chatMessage.IsSubscriber)
{
price = (int)Math.Floor(price * Config.SubscriberPriceMultiplier);
}
if (price < 0)
{
// Overflow protection
return;
}
if (Store.GetBalance(chatter) < price)
{
Reply(chatMessage, $"Not enough credits, need {price}! You have {Store.GetBalance(chatter)} kitchen credits remaining.");
return;
}
wave.AddContribution(chatter, price);
wave.AddMobs(mob.InternalName, amt);
if (wave.TargetHit)
{
foreach (var mobId in wave.CurrentMobs)
{
SpawnUnit?.Invoke(mobId, 1, "", null, true);
}
Store.ResolveWavePayment(wave);
TSPlayer.All.SendInfoMessage($"A wave of {wave.CurrentMobs.Count} has been spawned by {wave.Contributions.Count(c => c.Value > 0)} chatters.");
Overlay.SendPacket(new { @event = "waveEnd", chatter = wave.Chatter });
}
else
{
Overlay.SendPacket(new { @event = "waveUpdate", chatter = wave.Chatter, by = chatter, current = wave.CurrentMobs.Count, increment = amt, mob = mob.MobName });
//Reply(chatMessage, $"Added {amt} {buyParams[4]} to {wave.Chatter}'s wave ({wave.CurrentMobs.Count}/{wave.TargetNumber})! You have {Store.GetBalance(chatter)} kitchen credits remaining.");
}
}
else
{
Reply(chatMessage, $"Wave purchase failed. The player may not be starting a wave or invalid amount. You have {Store.GetBalance(chatter)} kitchen credits remaining.");
return;
}
break;
case "cancel":
if (Store.Waves.FirstOrDefault(a => a.Chatter == chatter) is KitchenWave cancelWave)
{
Store.Waves.Remove(cancelWave);
Reply(chatMessage, $"Wave request cancelled, a total of {cancelWave.TotalContributions()} credits has been refunded. You have {Store.GetBalance(chatter)} kitchen credits remaining.");
Overlay.SendPacket(new { @event = "waveEnd", chatter });
}
break;
}
}
private void Buy(ChatMessage chatMessage)
{
var buyParams = chatMessage.Message.Split(' ');
if (buyParams.Length < 4 || buyParams.Length > 5)
{
return;
}
var mobName = buyParams[2];
var mobAmount = buyParams[3];
var buyTarget = buyParams.Length == 5 ? buyParams[4] : null;
var chatter = chatMessage.Username.ToLower();
//Console.WriteLine($"(Terraria Kitchen) {chatter} attempts to buy {mobAmount}, {mobName}");
if (int.TryParse(mobAmount, out var amount))
{
if (amount <= 0)
{
// Invalid number
return;
}
var mob = Config.FindEntry(mobName);
if (mob == null)
{
// Mob not found.
Reply(chatMessage, $"Unknown mob. You have {Store.GetBalance(chatter)} kitchen credits remaining.");
return;
}
if (mob.Pooling)
{
if (amount > Store.GetBalance(chatter))
{
Reply(chatMessage, $"Not enough credits! You have {Store.GetBalance(chatter)} kitchen credits remaining.");
return;
}
var newPool = false;
var existingPool = Store.Pools.Where(p => p.TargetEntry != null).FirstOrDefault(p => p.TargetEntry?.InternalName == mob.InternalName);
if (existingPool == null)
{
existingPool = new KitchenPool(mob);
existingPool.Customer = buyTarget;
Store.Pools.Add(existingPool);
newPool = true;
Overlay.SendPacket(new { @event = "poolStart", idx = existingPool.Index, name = existingPool.PoolName, target = existingPool.TargetValue() });
}
var contributed = Store.ContributePool(chatter, amount, existingPool.Index);
if (existingPool.TargetReached)
{
Overlay.SendPacket(new { @event = "poolEnd", idx = existingPool.Index });
if (SpawnUnit?.Invoke(mob.InternalName, 1, $"{existingPool.Contributions.Count(c => c.Value > 0)} customers have ", existingPool.Customer, false) == true)
{
Store.ResolvePoolPayment(existingPool);
}
else
{
Announce($"Pool #{existingPool.Index} failed to spawn due to spawn conditions not being met, please attempt to complete it later.");
}
}
else
{
Overlay.SendPacket(new { @event = "poolUpdate", idx = existingPool.Index, lastContribution = contributed, lastContributor = chatter, current = existingPool.TotalContributions() });
if (newPool)
{
Reply(chatMessage, $"Started a new pool for {mob.MobName} with id {existingPool.Index}, you now have {Store.GetBalance(chatter)} kitchen credits remaining. Contribution: {contributed}/{existingPool.TargetValue()}.");
}
else
{
//Reply(chatMessage, $"Contributed {contributed} credits to pool id {existingPool.Index}, you now have {Store.GetBalance(chatter)} kitchen credits remaining. Contribution: {existingPool.TotalContributions()}/{existingPool.TargetValue()}.");
}
}
}
else
{
if (amount > mob.MaxBuys)
{
amount = mob.MaxBuys;
}
var price = mob.Price * amount;
if (chatMessage.IsSubscriber)
{
price = (int)Math.Floor(price * Config.SubscriberPriceMultiplier);
}
if (price < 0)
{
// Overflow protection
return;
}
if (Config.ModAbuse && (chatMessage.UserType == TwitchLib.Client.Enums.UserType.Moderator || chatMessage.UserType == TwitchLib.Client.Enums.UserType.Broadcaster))
{
SpawnUnit?.Invoke(mob.InternalName, amount, chatter, buyTarget, false);
}
else
{
if (Store.GetBalance(chatter) < price)
{
// Not enough money.
Reply(chatMessage, $"Not enough credits, need {price}! You have {Store.GetBalance(chatter)} kitchen credits remaining.");
return;
}
if (SpawnUnit?.Invoke(mob.InternalName, amount, chatter, buyTarget, false) == true)
{
Store.ModBalance(chatter, -price);
}
else
{
Reply(chatMessage, $"Failed to buy! You will not be charged and have {Store.GetBalance(chatter)} kitchen credits remaining.");
}
}
}
}
}
public void SetAPIKey(string apiKey)
{
this.apiKey = apiKey;
}
public bool HasAPIKey() => apiKey != null;
public void Dispose()
{
if (TwitchClient?.IsConnected == true)
{
TwitchClient.Disconnect();
}
incomeTimer?.Dispose();
}
}
}