public static void ConnectClients() { PrettyPrint.Log("Connecting clients..."); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { var references = assembly.GetReferencedAssemblies().ToList(); foreach (var reference in references) { if (reference.Name.Contains("TCR-TerrariaChatRelay")) { foreach (var type in assembly.GetTypes()) { if (type.BaseType == typeof(TCRPlugin)) { Activator.CreateInstance(type); break; } } ((CommandService)CommandServ).ScanForCommands(assembly); break; } } } for (var i = 0; i < Subscribers.Count; i++) { PrettyPrint.Log(Subscribers[i].GetType().ToString() + " Connecting..."); Subscribers[i].Connect(); } Console.ResetColor(); }
public void LoadConfigs() { foreach (StoredConfig data in configs) { data.Config.GetOrCreateConfiguration(); PrettyPrint.Log(LogSeverity.Info, "ConfigurationService", $"{data.Namespace} {data.Name} - Config loaded."); } }
/// <summary> /// Create a new WebSocket and initiate connection with Discord servers. /// Utilizes BOT_TOKEN and CHANNEL_ID found in Mod Config. /// </summary> public override void Connect() { if (BOT_TOKEN == "BOT_TOKEN" || Channel_IDs.Contains(0)) { PrettyPrint.Log("Discord", "Please update your Mod Config. Mod reload required."); if (BOT_TOKEN == "BOT_TOKEN") { PrettyPrint.Log("Discord", " Invalid Token: BOT_TOKEN", ConsoleColor.Yellow); } if (Channel_IDs.Contains(0)) { PrettyPrint.Log("Discord", " Invalid Channel Id: 0", ConsoleColor.Yellow); } PrettyPrint.Log("Discord", "Config path: " + new Configuration().FileName); Console.ResetColor(); Dispose(); return; } if (Main.Config.OwnerUserId == 0) { PrettyPrint.Log("Discord", " Invalid Owner Id: 0", ConsoleColor.Yellow); } errorCounter = 0; Socket = new WebSocket(GATEWAY_URL); Socket.Compression = CompressionMethod.Deflate; Socket.OnOpen += (object sender, EventArgs e) => { PrettyPrint.Log("Discord", "Connection established. Logging in!"); Socket.Send(DiscordMessageFactory.CreateLogin(BOT_TOKEN)); }; Socket.OnMessage += Socket_OnDataReceived; Socket.OnMessage += Socket_OnHeartbeatReceived; Socket.OnError += Socket_OnError; if (!debug) { Socket.Log.Output = (_, __) => { } } ; Socket.Connect(); if (Main.Config.ShowPoweredByMessageOnStartup) { messageQueue.QueueMessage(Channel_IDs, $"**This bot is powered by TerrariaChatRelay**\nUse **{Main.Config.CommandPrefix}help** for more commands!"); Main.Config.ShowPoweredByMessageOnStartup = true; Main.Config.SaveJson(); } }
private void OnServerLeave(LeaveEventArgs args) { try { EventManager.RaiseTerrariaMessageReceived(this, -1, $"{Main.player[args.Who].name} has left."); } catch (Exception) { PrettyPrint.Log("OnServerLeave could not be broadcasted."); } }
/// <summary> /// Attempts to reconnect after receiving an error. /// </summary> private void Socket_OnError(object sender, WebSocketSharp.ErrorEventArgs e) { Disconnect(); var restartClient = new ChatClient(parent, BOT_TOKEN, Channel_IDs.ToArray()); PrettyPrint.Log("Discord", "Client disconnected. Attempting to reconnect..."); restartClient.Connect(); parent.Add(restartClient); Dispose(); }
public static void ConnectClients() { PrettyPrint.Log("Connecting clients..."); for (var i = 0; i < Subscribers.Count; i++) { PrettyPrint.Log(Subscribers[i].GetType().ToString() + " Connecting..."); Subscribers[i].Connect(); } Console.ResetColor(); }
/// <summary> /// Attempts to reconnect after receiving an error. /// </summary> private void Socket_OnError(object sender, WebSocketSharp.ErrorEventArgs e) { PrettyPrint.Log("Discord", e.Message, ConsoleColor.Red); Disconnect(); var restartClient = new ChatClient(parent, BOT_TOKEN, Channel_IDs.ToArray()); PrettyPrint.Log("Discord", "Restarting client...", ConsoleColor.Yellow); restartClient.Connect(); parent.Add(restartClient); Dispose(); }
/// <summary> /// Create a new WebSocket and initiate connection with Discord servers. /// Utilizes BOT_TOKEN and CHANNEL_ID found in Mod Config. /// </summary> public override void Connect() { if (BOT_TOKEN == "BOT_TOKEN" || Channel_IDs.Contains(0)) { PrettyPrint.Log("Discord", "Please update your Mod Config. Mod reload required."); if (BOT_TOKEN == "BOT_TOKEN") { Console.WriteLine(" Invalid Token: BOT_TOKEN"); } if (Channel_IDs.Contains(0)) { Console.WriteLine(" Invalid Channel Id: 0"); } Console.WriteLine(" Config path: " + new Configuration().FileName); Console.ResetColor(); Dispose(); return; } errorCounter = 0; Socket = new WebSocket(GATEWAY_URL); Socket.Compression = CompressionMethod.Deflate; Socket.OnOpen += (object sender, EventArgs e) => { PrettyPrint.Log("Discord", "Connection complete!"); Socket.Send(DiscordMessageFactory.CreateLogin(BOT_TOKEN)); }; Socket.OnMessage += Socket_OnDataReceived; Socket.OnMessage += Socket_OnHeartbeatReceived; Socket.OnError += Socket_OnError; if (!debug) { Socket.Log.Output = (_, __) => { } } ; Socket.Connect(); if (!Main.Config.FirstTimeMessageShown || Main.Config.AlwaysShowFirstTimeMessage) { messageQueue.QueueMessage(Channel_IDs, $"**This bot is powered by TerrariaChatRelay**\nUse {Main.Config.CommandPrefix}info for more commands!"); Main.Config.FirstTimeMessageShown = true; Main.Config.SaveJson(); } }
public async Task MessageReceivedAsync(SocketMessage rawMsg) { // Ignore system messages, or messages from other bots if (!(rawMsg is SocketUserMessage msg)) { return; } if (msg.Source != MessageSource.User) { return; } PrettyPrint.Log((SocketUserMessage)rawMsg); }
/// <summary> /// <para>Loads the build.txt from GitHub to check if there is a newer version of TCR available. </para> /// If there is, a message will be displayed on the console and prepare a message for sending when the world is loading. /// </summary> public async Task GetLatestVersionNumber() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; var http = HttpWebRequest.CreateHttp("https://raw.githubusercontent.com/xPanini/TCR-TerrariaChatRelay/master/version.txt"); WebResponse res = null; try { res = await http.GetResponseAsync(); } catch (Exception e) { PrettyPrint.Log("Error checking for version update: " + e.Message, ConsoleColor.Red); return; } using (StreamReader sr = new StreamReader(res.GetResponseStream())) { string buildtxt = sr.ReadToEnd(); buildtxt = buildtxt.ToLower(); string line = ""; using (StringReader stringreader = new StringReader(buildtxt)) { do { line = stringreader.ReadLine(); if (line.Contains("version")) { line = line.Replace(" ", ""); line = line.Replace("version=", ""); LatestVersion = new Version(line); if (LatestVersion > Version) { PrettyPrint.Log($"A new version of TCR is available: V.{LatestVersion.ToString()}"); } line = null; } }while (line != null); } } }
private void OnServerLeave(LeaveEventArgs args) { try { if (Main.player[args.Who].name != "" && Main.player[args.Who].name != " " && Main.player[args.Who].name != null && Main.player[args.Who].name.Replace("*", "") != "") { var player = Main.player[args.Who]; // -1 is hacky, but works Core.RaiseTerrariaMessageReceived(this, player.ToTCRPlayer(-1), $"{player.name} has left."); } } catch (Exception) { PrettyPrint.Log("OnServerLeave could not be broadcasted."); } }
private void OnServerJoin(JoinEventArgs args) { try { var player = Main.player[args.Who]; // -1 is hacky, but works NetPacket packet = Terraria.GameContent.NetModules.NetTextModule.SerializeServerMessage( NetworkText.FromFormattable("This chat is powered by TerrariaChatRelay."), Color.LawnGreen, byte.MaxValue); NetManager.Instance.SendToClient(packet, args.Who); Core.RaiseTerrariaMessageReceived(this, Main.player[args.Who].ToTCRPlayer(-1), $"{Main.player[args.Who].name} has joined."); } catch (Exception) { PrettyPrint.Log("OnServerJoin could not be broadcasted."); } }
/// <summary> /// <para>Loads the build.txt from GitHub to check if there is a newer version of TCR available. </para> /// If there is, a message will be displayed on the console and prepare a message for sending when the world is loading. /// </summary> public async Task GetLatestVersionNumber() { var http = HttpWebRequest.CreateHttp("https://raw.githubusercontent.com/xPanini/TCR-TerrariaChatRelay/master/build.txt"); WebResponse res = null; try { res = await http.GetResponseAsync(); } catch (Exception e) { return; } using (StreamReader sr = new StreamReader(res.GetResponseStream())) { string buildtxt = sr.ReadToEnd(); buildtxt = buildtxt.ToLower(); string line = ""; using (StringReader stringreader = new StringReader(buildtxt)) { do { line = stringreader.ReadLine(); if (line.Contains("version")) { line = line.Replace(" ", ""); line = line.Replace("version=", ""); LatestVersion = new Version(line); if (LatestVersion > Version) { PrettyPrint.Log($"A new version of TCR is available: V.{LatestVersion.ToString()}"); } line = null; } }while (line != null); } } }
public bool LoadConfig(string name) { var dataSet = configs.Where(data => data.Name == name); if (dataSet.Count() == 1) { var data = dataSet.First(); data.Config.GetOrCreateConfiguration(); PrettyPrint.Log(LogSeverity.Info, "ConfigurationService", $"{data.Namespace} {data.Name} - Config loaded."); return(true); } else if (dataSet.Count() > 1) { PrettyPrint.Log(LogSeverity.Error, "ConfigurationService", $"More than one config found. No config loaded."); return(false); } else { PrettyPrint.Log(LogSeverity.Error, "ConfigurationService", $"No config found."); return(false); } }
public override void Load() { base.Load(); ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; Global.Config = (TCRConfig) new TCRConfig().GetOrCreateConfiguration(); // Intercept DeserializeAsServer method NetTextModule.DeserializeAsServer += NetTextModule_DeserializeAsServer; On.Terraria.NetMessage.BroadcastChatMessage += NetMessage_BroadcastChatMessage; On.Terraria.IO.WorldFile.LoadWorld_Version2 += OnWorldLoadStart; On.Terraria.Netplay.StopListening += OnServerStop; On.Terraria.NetMessage.SyncConnectedPlayer += OnPlayerJoin_NetMessage_SyncConnectedPlayer; On.Terraria.RemoteClient.Reset += RemoteClient_Reset; On.Terraria.NetMessage.greetPlayer += NetMessage_greetPlayer; PlayerJoinEndingString = Language.GetText("LegacyMultiplayer.19").Value.Split(new string[] { "{0}" }, StringSplitOptions.None).Last(); PlayerLeaveEndingString = Language.GetText("LegacyMultiplayer.20").Value.Split(new string[] { "{0}" }, StringSplitOptions.None).Last(); Mod NoMoreTombs = ModLoader.GetMod("NoMoreTombs"); if (NoMoreTombs != null) { PrettyPrint.Log("[NoMoreTombs] Incompatibility : Death messages can not be routed.", ConsoleColor.Red); } // Add subscribers to list Core.Initialize(new tModLoaderAdapter()); ((CommandService)Core.CommandServ).ScanForCommands(this); Core.ConnectClients(); if (Global.Config.CheckForLatestVersion) { Task.Run(GetLatestVersionNumber); } }
public async void SendMessageToDiscordChannel(string message, ulong channelId) { message = message.Replace("\\", "\\\\"); message = message.Replace("\"", "\\\""); message = message.Replace("\n", "\\n"); string json = DiscordMessageFactory.CreateTextMessage(message); string response = null; try { response = await SimpleRequest.SendJsonDataAsync($"{API_URL}/channels/{channelId}/messages", new WebHeaderCollection() { { "Authorization", $"Bot {BOT_TOKEN}" } }, json); } catch (Exception e) { if (e.Message.Contains("(401) Unauthorized")) { PrettyPrint.Log("Discord", "Unauthorized access to Discord server. Is your BOT_TOKEN correct?", ConsoleColor.Red); } else if (e.Message.Contains("(403) Forbidden")) { PrettyPrint.Log("Discord", "Forbidden access to Discord channel. Are your Channel IDs & BOT permissions correct?", ConsoleColor.Red); } else { PrettyPrint.Log("Discord", e.Message, ConsoleColor.Red); } } if (debug) { Console.WriteLine(response); } }
/// <summary> /// Hooks onto the World Load method to send a message when the server is starting. /// </summary> private int OnWorldLoadStart(On.Terraria.IO.WorldFile.orig_LoadWorld_Version2 orig, BinaryReader reader) { try { if (!Netplay.disconnect) { if (Global.Config.ShowServerStartMessage) { Core.RaiseTerrariaMessageReceived(this, TCRPlayer.Server, "The server is starting!"); } if (LatestVersion > Version) { Core.RaiseTerrariaMessageReceived(this, TCRPlayer.Server, $"A new version of TCR is available: V.{LatestVersion.ToString()}"); } } } catch (Exception e) { PrettyPrint.Log("Error checking for version update: " + e.Message, ConsoleColor.Red); } return(orig(reader)); }
/// <summary> /// Parses data when Discord sends a message. /// </summary> private void Socket_OnDataReceived(object sender, MessageEventArgs e) { try { var json = e.Data; if (json == null) { return; } if (json.Length <= 1) { return; } if (debug) { Console.WriteLine("\n" + json + "\n"); } if (!DiscordMessageFactory.TryParseDispatchMessage(json, out var msg)) { return; } LastSequenceNumber = msg.SequenceNumber; var chatmsg = msg.GetChatMessageData(); if (chatmsg != null && chatmsg.Message != "" && Channel_IDs.Contains(chatmsg.ChannelId)) { if (!chatmsg.Author.IsBot) { string msgout = chatmsg.Message; // Lazy add commands until I take time to design a command service properly //if (ExecuteCommand(chatmsg)) // return; if (!Core.CommandServ.IsCommand(msgout, Main.Config.CommandPrefix)) { msgout = chatParser.ConvertUserIdsToNames(msgout, chatmsg.UsersMentioned); msgout = chatParser.ShortenEmojisToName(msgout); } Permission userPermission; if (chatmsg.Author.Id == Main.Config.OwnerUserId) { userPermission = Permission.Owner; } else if (Main.Config.AdminUserIds.Contains(chatmsg.Author.Id)) { userPermission = Permission.Admin; } else if (Main.Config.ManagerUserIds.Contains(chatmsg.Author.Id)) { userPermission = Permission.Manager; } else { userPermission = Permission.User; } var user = new TCRClientUser("Discord", chatmsg.Author.Username, userPermission); TerrariaChatRelay.Core.RaiseClientMessageReceived(this, user, "[c/7489d8:Discord] - ", msgout, Main.Config.CommandPrefix, chatmsg.ChannelId); msgout = $"<{chatmsg.Author.Username}> {msgout}"; if (Channel_IDs.Count > 1) { messageQueue.QueueMessage( Channel_IDs.Where(x => x != chatmsg.ChannelId), $"**[Discord]** <{chatmsg.Author.Username}> {chatmsg.Message}"); } Console.ForegroundColor = ConsoleColor.Blue; Console.Write("[Discord] "); Console.ResetColor(); Console.Write(msgout); Console.WriteLine(); } } } catch (Exception ex) { PrettyPrint.Log("Discord", ex.Message, ConsoleColor.Red); } }