Skip to content

Commit

Permalink
Code refactor, client upgrades, TShock nuget
Browse files Browse the repository at this point in the history
- Removed unnecessary usings where possible
- Now using TShock nuget package instead of lib folder references
- Add framework version to t!version command
- Game status now supports custom string variables such as playercount and maxplayers
- Json formatter now indents Json to make it easier to read
- Adjust Json help names to make file easier to read
- Tick internal version to 2.3.0.2
  • Loading branch information
xNarnia committed Jan 21, 2025
1 parent 20b8f10 commit 9d99169
Show file tree
Hide file tree
Showing 46 changed files with 192 additions and 307 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@
using TerrariaChatRelay.Clients;
using TerrariaChatRelay.Command;
using TerrariaChatRelay.Helpers;
using Game = TerrariaChatRelay.Helpers.Game;
using System.Timers;
using Discord.Net;
using Terraria;
using System.Configuration;
using TerrariaChatRelay.Clients.DiscordClient.Helpers;
using TerrariaChatRelay.Clients.DiscordClient.Messaging;
using static Terraria.GameContent.Animations.Actions;

namespace TerrariaChatRelay.Clients.DiscordClient
{
Expand All @@ -34,7 +37,7 @@ public class DiscordChatClient : BaseClient
private string BOT_TOKEN;
private ChatParser chatParser { get; set; }
private DiscordMessageQueue messageQueue { get; set; }
public Timer channelTitleTimer { get; set; }
public Timer botUpdateTimer { get; set; }

// TCR Variables
private List<IChatClient> parent { get; set; }
Expand All @@ -55,7 +58,7 @@ public DiscordChatClient(List<IChatClient> _parent, Endpoint _endpoint)
chatParser = new ChatParser();
Channel_IDs = _endpoint.Channel_IDs.ToList();
Endpoint = _endpoint;
channelTitleTimer = new Timer(60000);
botUpdateTimer = new Timer(30000);

messageQueue = new DiscordMessageQueue(500);
messageQueue.OnReadyToSend += OnMessageReadyToSend;
Expand Down Expand Up @@ -125,50 +128,66 @@ public override async void ConnectAsync()
Socket.MessageReceived += ClientMessageReceived;
Socket.Connected += ConnectionSuccessful;
Socket.Disconnected += ScheduleRetry;
await Socket.SetGameAsync(DiscordPlugin.Config.BotStatus);
channelTitleTimer.Elapsed += ChannelTitleTimer_Elapsed;
channelTitleTimer.Start();

if (DiscordPlugin.Config.BotGameStatus != null && DiscordPlugin.Config.BotGameStatus != "")
botUpdateTimer.Elapsed += GameStatusTimer_Elapsed;

if (DiscordPlugin.Config.BotChannelDescription != null && DiscordPlugin.Config.BotChannelDescription != "")
botUpdateTimer.Elapsed += ChannelTitleTimer_Elapsed;

botUpdateTimer.Start();
}

private async void ChannelTitleTimer_Elapsed(object sender, ElapsedEventArgs e)
/// <summary>
/// Continuously updates the Game Status of the bot.
/// </summary>
private async void GameStatusTimer_Elapsed(object sender, ElapsedEventArgs e)
{
var status = DiscordPlugin.Config.BotGameStatus;
status = chatParser.ReplaceCustomStringVariables(status);

// Don't send an update if the status hasn't changed
if (Socket.CurrentUser.Activities?.FirstOrDefault()?.Name != status)
await Socket.SetGameAsync(status);
}

/// <summary>
/// Continuously updates the Channel Descriptions the bot is relaying in.
/// </summary>
private async void ChannelTitleTimer_Elapsed(object sender, ElapsedEventArgs e)
{
foreach (var channelId in Channel_IDs)
{
var channel = await Socket.GetChannelAsync(channelId);
if (channel is SocketTextChannel)
{
var textChannel = (SocketTextChannel)channel;
var players = Terraria.Main.player.Where(x => x.name.Length != 0);
var topic = DiscordPlugin.Config.BotChannelDescription;
topic =
topic.Replace("%worldname%", GameHelper.World.GetName())
.Replace("%playercount%", players.Count().ToString())
.Replace("%maxplayers%", Terraria.Main.maxNetPlayers.ToString());

topic = chatParser.ReplaceCustomStringVariables(topic);

if (topic == textChannel.Topic)
{
return;
}

try
{
await textChannel.ModifyAsync(x => x.Topic = topic);
}
catch (HttpException ex)
{
if (ex.Message.ToLower().Contains("missing permissions"))
if (ex.Message.ToLower().Contains("missing permission"))
{
PrettyPrint.Log("Discord", "Missing Permission - Manage Channels: Could not update channel description.", ConsoleColor.Red);
PrettyPrint.Log("Discord", $" Update permissions then restart using {DiscordPlugin.Config.CommandPrefix}restart.", ConsoleColor.Red);
channelTitleTimer.Stop();
botUpdateTimer.Stop();
}
else
{
channelTitleTimer.Stop();
botUpdateTimer.Stop();
throw;
}
}
}
await Task.Delay(50);
}
}

Expand Down Expand Up @@ -204,19 +223,20 @@ public override void Disconnect()

// Detach events
if (Socket != null)
{
Task.Run(async () =>
{
await Socket.StopAsync();
await Socket.DisposeAsync();
});
Socket.MessageReceived -= ClientMessageReceived;
{
var SocketToDestroy = Socket;
SocketToDestroy.MessageReceived -= ClientMessageReceived;
Task.Run(async () => {
await SocketToDestroy.StopAsync();
await SocketToDestroy.LogoutAsync();
SocketToDestroy.Dispose();
});
}

Socket = null;

channelTitleTimer.Stop();
channelTitleTimer.Dispose();
botUpdateTimer.Stop();
botUpdateTimer.Dispose();
}

/// <summary>
Expand Down Expand Up @@ -311,11 +331,6 @@ private Task ClientMessageReceived(SocketMessage msg)
return Task.CompletedTask;
}

public void ForceFail()
{
//Socket_OnError(this, null);
}

/// <summary>
/// Sets a timer to retry after a specified time in the configuration.
/// </summary>
Expand Down Expand Up @@ -447,7 +462,7 @@ public override void GameMessageReceivedHandler(object sender, TerrariaChatEvent
outMsg = outMsg.Replace("%playername%", playerName);
}

outMsg = outMsg.Replace("%worldname%", GameHelper.World.GetName());
outMsg = outMsg.Replace("%worldname%", Game.World.GetName());
outMsg = outMsg.Replace("%message%", msg.Message);

if (outMsg == "" || outMsg == null)
Expand Down
40 changes: 17 additions & 23 deletions TModLoader/TerrariaChatRelay/Clients/DiscordClient/DiscordConfig.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TerrariaChatRelay.Helpers;

namespace TerrariaChatRelay.Clients.DiscordClient
Expand All @@ -20,10 +16,6 @@ public class DiscordConfig : SimpleConfig<DiscordConfig>
public bool EnableDiscord { get; set; } = true;
[JsonProperty(Order = 50)]
public string CommandPrefix { get; set; } = "t!";
[JsonProperty(Order = 55)]
public string BotStatus { get; set; } = "TerrariaChatRelay";
[JsonProperty(Order = 57)]
public string BotChannelDescription { get; set; } = "%worldname% - **Players Online:** %playercount% / %maxplayers%";
[JsonProperty(Order = 60)]
public bool ShowPoweredByMessageOnStartup { get; set; } = true;
[JsonProperty(Order = 75)]
Expand All @@ -33,41 +25,43 @@ public class DiscordConfig : SimpleConfig<DiscordConfig>
[JsonProperty(Order = 120)]
public List<ulong> AdminUserIds { get; set; } = new List<ulong>();
[JsonProperty(Order = 130)]
public string EndpointHelp1 { get; set; } = "Use commands to handle denying sending and receiving! Use 't!help admin' for more information";
public string HelpEndpoint1 { get; set; } = "Use commands to handle denying sending and receiving! Use 't!help admin' for more information";
[JsonProperty(Order = 133)]
public List<Endpoint> EndPoints { get; set; } = new List<Endpoint>();
[JsonProperty(Order = 134)]
public string GameStatusHelp1 { get; set; } = "Sets the bots now playing status. Can be configured with variables";
public string HelpGameStatus1 { get; set; } = "Sets the bots now playing status. Can be configured with variables";
[JsonProperty(Order = 135)]
public string GameStatusHelp2 { get; set; } = "%playercount% = Number of current players on the server";
public string HelpGameStatus2 { get; set; } = "%playercount% = Number of current players on the server";
[JsonProperty(Order = 136)]
public string GameStatusHelp3 { get; set; } = "%maxplayers% = Maximum number of players allowed, based on serverconfig.txt or command prompt entry";
public string HelpGameStatus3 { get; set; } = "%maxplayers% = Maximum number of players allowed, based on serverconfig.txt or command prompt entry";
[JsonProperty(Order = 138)]
public string GameStatus { get; set; } = "with %playercount%/%maxplayers% players!";
[JsonProperty(Order = 140)]
public string BotGameStatus { get; set; } = "with %playercount%/%maxplayers% players!";
[JsonProperty(Order = 139)]
public string BotChannelDescription { get; set; } = "%worldname% - **Players Online:** %playercount% / %maxplayers%";
[JsonProperty(Order = 140)]
public string RetryHelp { get; set; } = "Set NumberOfTimesToRetryConnectionAfterError to -1 to retry infinitely";
[JsonProperty(Order = 150)]
public int NumberOfTimesToRetryConnectionAfterError { get; set; } = 5;
[JsonProperty(Order = 160)]
public int SecondsToWaitBeforeRetryingAgain { get; set; } = 10;
[JsonProperty(Order = 170)]
public string FormatHelp1 { get; set; } = "You can insert any of these formatters to change how your message looks! (CASE SENSITIVE)";
public string HelpFormat1 { get; set; } = "You can insert any of these formatters to change how your message looks! (CASE SENSITIVE)";
[JsonProperty(Order = 180)]
public string FormatHelp2 { get; set; } = "%playername% = Player Name";
public string HelpFormat2 { get; set; } = "%playername% = Player Name";
[JsonProperty(Order = 190)]
public string FormatHelp3 { get; set; } = "%worldname% = World Name";
public string HelpFormat3 { get; set; } = "%worldname% = World Name";
[JsonProperty(Order = 200)]
public string FormatHelp4 { get; set; } = "%message% = Initial message content";
public string HelpFormat4 { get; set; } = "%message% = Initial message content";
[JsonProperty(Order = 210)]
public string FormatHelp5 { get; set; } = "%bossname% = Name of boss being summoned (only for VanillaBossSpawned)";
public string HelpFormat5 { get; set; } = "%bossname% = Name of boss being summoned (only for VanillaBossSpawned)";
[JsonProperty(Order = 220)]
public string FormatHelp6 { get; set; } = "%groupprefix% = Group prefix";
public string HelpFormat6 { get; set; } = "%groupprefix% = Group prefix";
[JsonProperty(Order = 230)]
public string FormatHelp7 { get; set; } = "%groupsuffix% = Group suffix";
public string HelpFormat7 { get; set; } = "%groupsuffix% = Group suffix";
[JsonProperty(Order = 66)]
public string RegexHelp1 { get; set; } = "For more advanced users, you can use RegexMessageReplace to modify/filter the final message being sent.";
public string HelpRegex1 { get; set; } = "For more advanced users, you can use RegexMessageReplace to modify/filter the final message being sent.";
[JsonProperty(Order = 67)]
public string RegexHelp2 { get; set; } = "Example (Filtering nth mob kill annoucements): { \"^.+ has defeated the \\d+th .+$\": \"\" }";
public string HelpRegex2 { get; set; } = "Example (Filtering nth mob kill annoucements): { \"^.+ has defeated the \\d+th .+$\": \"\" }";

[JsonProperty(Order = 235)]
public static string TerrariaInGameDiscordPrefix = "[c/7489d8:Discord] - ";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Discord.WebSocket;
using Terraria;
using TerrariaChatRelay.Helpers;

namespace TerrariaChatRelay.Clients.DiscordClient.Helpers
{
Expand Down Expand Up @@ -71,5 +74,16 @@ public string RemoveTerrariaColorAndItemCodes(string chatMessage)

return chatMessage;
}

public string ReplaceCustomStringVariables(string input)
{
var players = Main.player.Where(x => x.name.Length != 0);

input = input.Replace("%worldname%", Game.World.GetName())
.Replace("%playercount%", players.Count().ToString())
.Replace("%maxplayers%", Main.maxNetPlayers.ToString());

return input;
}
}
}
2 changes: 0 additions & 2 deletions TModLoader/TerrariaChatRelay/Command/Commands/CmdHelp.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TerrariaChatRelay.Command.Commands
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria;
using Terraria.DataStructures;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TerrariaChatRelay.Command.Commands
{
Expand Down
16 changes: 2 additions & 14 deletions TModLoader/TerrariaChatRelay/Command/Commands/CmdVersion.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria.ModLoader;

namespace TerrariaChatRelay.Command.Commands
{
Expand All @@ -23,15 +19,7 @@ public class CmdVersion : ICommand

public string Execute(object sender, string input = null, TCRClientUser whoRanCommand = null)
{
string terraria = "";
#if TSHOCK
terraria = "TShock";
#endif
#if TMODLOADER
terraria = "tModLoader 1.4";
#endif

return $"</b>TerrariaChatRelay Version:</b> {terraria} - v{Core.TCRVersion}";
return $"</b>TerrariaChatRelay Version:</b> v{Core.TCRVersion}\n</b>tModLoader Version:</b> {ModLoader.versionedName}";
}
}
}
8 changes: 4 additions & 4 deletions TModLoader/TerrariaChatRelay/Command/Commands/CmdWorld.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ public string Execute(object sender, string input = null, TCRClientUser whoRanCo
var worldinfo = new System.Text.StringBuilder();

worldinfo.Append("</b>Information about the currently running world</b> </br>");
worldinfo.Append($"</box>World Name: {GameHelper.World.GetName()} </br>");
worldinfo.Append($"Evil: {GameHelper.World.GetEvilType()} </br>");
worldinfo.Append($"</box>World Name: {Game.World.GetName()} </br>");
worldinfo.Append($"Evil: {Game.World.GetEvilType()} </br>");
#if TSHOCK
worldinfo.Append($"Difficulty: {(TCRCore.Game.World.IsMasterMode() ? "Master" : (TCRCore.Game.World.IsExpertMode() ? "Expert" : "Normal"))} </br>");
#endif
worldinfo.Append($"Hardmode: {(GameHelper.World.IsHardMode() ? "Yes" : "No")} </br>");
worldinfo.Append($"World Size: {GameHelper.World.getWorldSize()}");
worldinfo.Append($"Hardmode: {(Game.World.IsHardMode() ? "Yes" : "No")} </br>");
worldinfo.Append($"World Size: {Game.World.getWorldSize()}");

#if TSHOCK
if(Global.Config.ShowWorldSeed)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class CmdRestart : ICommand

public string CommandKey { get; } = "restart";

public string[] Aliases { get; } = { "reset", "reboot" };
public string[] Aliases { get; } = { "reset", "reboot", "reload" };

public string Description { get; } = "Restarts the bot.";

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria.ModLoader;
using Terraria.ModLoader;
using Terraria;
using Microsoft.Xna.Framework;

Expand Down
2 changes: 1 addition & 1 deletion TModLoader/TerrariaChatRelay/Core.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class Core
public static List<IChatClient> Subscribers { get; set; }
public static ICommandService CommandServ { get; set; }

public static Version TCRVersion { get; set; } = new Version(2, 0, 0);
public static Version TCRVersion { get; set; } = new Version(2, 3, 0, 2);

public static event EventHandler<TerrariaChatEventArgs> OnGameMessageReceived;
public static event EventHandler<ClientChatEventArgs> OnClientMessageReceived;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

namespace TerrariaChatRelay.Helpers
{
public static class GameHelper
public static class Game
{
public static class World
{
Expand Down
3 changes: 2 additions & 1 deletion TModLoader/TerrariaChatRelay/Helpers/Global.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.IO;
using System;
using System.IO;

namespace TerrariaChatRelay
{
Expand Down
2 changes: 1 addition & 1 deletion TModLoader/TerrariaChatRelay/build.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
author = Lady Narnia
version = 2.3.0.1
version = 2.3.0.2
displayName = TerrariaChatRelay (Discord)
homepage = https://steamcommunity.com/sharedfiles/filedetails/?id=2669581349
includePDB=true
Expand Down
Loading

0 comments on commit 9d99169

Please sign in to comment.