/// <summary>
        /// Parses data when Discord sends a message.
        /// </summary>
        private void Socket_OnDataReceived(object sender, MessageEventArgs e)
        {
            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 && 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;

                    msgout = chatParser.ConvertUserIdsToNames(msgout, chatmsg.UsersMentioned);
                    msgout = chatParser.ShortenEmojisToName(msgout);
                    msgout = $"<{chatmsg.Author.Username}> {msgout}";

                    NetHelpers.BroadcastChatMessageWithoutTCRFormattable(
                        ("[c/7489d8:Discord] - " + msgout), -1);

                    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();
                }
            }
        }
Esempio n. 2
0
        /// <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();
            }
        }
        /// <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();
        }
Esempio n. 4
0
        /// <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();
            }
        }
Esempio n. 6
0
        /// <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);
            }
        }