Esempio n. 1
0
        /// <summary>
        /// Handles the heartbeat acknowledgement when the server asks for it.
        /// </summary>
        private void Socket_OnHeartbeatReceived(object sender, MessageEventArgs e)
        {
            var json = e.Data;

            if (json.Length <= 1)
            {
                return;
            }

            if (!DiscordMessageFactory.TryParseMessage(json, out var msg))
            {
                return;
            }

            if (msg.OpCode == GatewayOpcode.Hello)
            {
                if (heartbeatTimer != null)
                {
                    heartbeatTimer.Dispose();
                }

                heartbeatTimer          = new System.Timers.Timer(((JObject)msg.Data).Value <int>("heartbeat_interval") / 2);
                heartbeatTimer.Elapsed += (senderr, ee) =>
                {
                    Socket.Send(DiscordMessageFactory.CreateHeartbeat(GetLastSequenceNumber()));
                    if (errorCounter > 0)
                    {
                        errorCounter--;
                    }
                };
                heartbeatTimer.Start();

                Socket.Send(DiscordMessageFactory.CreateHeartbeat(GetLastSequenceNumber()));
            }
        }
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();
            }
        }
Esempio n. 3
0
        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);
            }
        }
Esempio n. 4
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);
            }
        }