private void onChat(object sender, PlayerChattedEventArgs e)
        {
            Task.Run(async() =>
            {
                if (Client.State == ConnectionState.Connected)
                {
                    foreach (string s in Config.TerrariaChannels)
                    {
                        Channel c = Client.CurrentServer.FindChannels(s, exactMatch: true).FirstOrDefault();
                        try
                        {
                            Message m = await c?.SendMessage(e.Message.SetFormat(Config.DiscordChatFormat).ToString().FormatChat(e.ChatFormatters).StripTags(true));
                            if (m.State == MessageState.Failed)
                            {
                                TShock.Log.ConsoleError($"discord-bridge: Message broadcasting to channel '{c.Name}' failed!");
                            }
                        }
                        catch (Exception ex)
                        {
                            TShock.Log.Error(ex.ToString());
                        }
                    }

                    // Multi-Server Broadcast
                    foreach (ConfigFile.ServerBot bot in Config.ServerBots.FindAll(b => b.Id > 0))
                    {
                        User botUser = Client.CurrentServer.GetUser(bot.Id);

                        if (botUser == null || !botUser.IsBot /* Apparently bots can be "Offline" while being connected?? || botUser.Status == UserStatus.Offline*/)
                        {
                            // We only support active bots, mang
                            Client.Log.Warning("OnChat", $"Broadcasting to bot {bot.Id} failed (null: {botUser == null} | IsBot: {botUser?.IsBot} | Status: {botUser?.Status?.Value})");
                            return;
                        }

                        var colorDictionary = e.ColorFormatters;

                        #region Format Colors

                        var botNick = new ChatMessage.Section(String.IsNullOrWhiteSpace(botUser.Nickname) ? botUser.Name : botUser.Nickname);
                        if (bot.Broadcast.Colors.BotNick == ServerBroadcastColor.Specific)
                        {
                            Discord.Color discordColor = botUser.Roles.OrderBy(r => r.Position).Last()?.Color;
                            if (discordColor != null && discordColor != Discord.Color.Default)
                            {
                                botNick.Color = new Color(discordColor.R, discordColor.G, discordColor.B);
                            }
                        }
                        else if (bot.Broadcast.Colors.BotNick == ServerBroadcastColor.Group || bot.Broadcast.Colors.BotNick == ServerBroadcastColor.Message)
                        {
                            botNick.Color = colorDictionary[bot.Broadcast.Colors.BotNick.ToString()];
                        }

                        var prefixes = new List <ChatMessage.Section>(e.Message.Prefixes);
                        if (bot.Broadcast.Colors.Prefixes == ServerBroadcastColor.None)
                        {
                            prefixes.ForEach(p => p.Color = null);
                        }
                        else if (bot.Broadcast.Colors.Prefixes == ServerBroadcastColor.Group || bot.Broadcast.Colors.Prefixes == ServerBroadcastColor.Message)
                        {
                            prefixes.ForEach(p => p.Color = colorDictionary[bot.Broadcast.Colors.Prefixes.ToString()]);
                        }

                        ChatMessage.Section name = e.Message.Name;
                        if (bot.Broadcast.Colors.Name == ServerBroadcastColor.None)
                        {
                            name.Color = null;
                        }
                        else if (bot.Broadcast.Colors.Name == ServerBroadcastColor.Group || bot.Broadcast.Colors.Name == ServerBroadcastColor.Message)
                        {
                            name.Color = colorDictionary[bot.Broadcast.Colors.Name.ToString()];
                        }

                        var suffixes = new List <ChatMessage.Section>(e.Message.Suffixes);
                        if (bot.Broadcast.Colors.Suffixes == ServerBroadcastColor.None)
                        {
                            suffixes.ForEach(s => s.Color = null);
                        }
                        else if (bot.Broadcast.Colors.Suffixes == ServerBroadcastColor.Group || bot.Broadcast.Colors.Suffixes == ServerBroadcastColor.Message)
                        {
                            suffixes.ForEach(s => s.Color = colorDictionary[bot.Broadcast.Colors.Suffixes.ToString()]);
                        }

                        string text = e.Message.Text;

                        #endregion

                        try
                        {
                            Message m = await botUser.SendMessage(ChatHandler.CreateMessage(bot.Broadcast.Format)
                                                                  .SetHeader(botNick.ToString())
                                                                  .Prefix(prefixes)
                                                                  .SetName(name.ToString())
                                                                  .Suffix(suffixes)
                                                                  .SetText(text).ToString()
                                                                  .FormatChat(e.ChatFormatters)
                                                                  .ParseColors(colorDictionary));
                            if (m?.State == MessageState.Failed)
                            {
                                Client.Log.Warning("OnChat", $"Broadcasting to bot {bot.Id} failed (null: {botUser == null} | IsBot: {botUser?.IsBot} | Status: {botUser?.Status?.Value})");
                            }
                        }
                        catch (Exception ex)
                        {
                            TShock.Log.Error(ex.ToString());
                        }
                    }
                }
            });
        }
Ejemplo n.º 2
0
        private async void onMessageReceived(object sender, MessageEventArgs e)
        {
            if (e.Message.IsAuthor)
            {
                return;
            }

            try
            {
                // Ignore commands
                if (e.Message.IsMentioningMe() || e.Message.Text.StartsWith(_main.Config.BotPrefix.ToString()))
                {
                    return;
                }

                // We don't need to process attachments; in fact, this crashes the server
                if (e.Message.Attachments.Length > 0 || e.Message.Embeds.Length > 0)
                {
                    return;
                }

                if (e.Channel.IsPrivate)
                {
                    if (e.User.IsBot && _main.Config.ServerBots.Exists(b => b.Id == e.User.Id))
                    {
                        // Message is Multi-Server Broadcast
                        TSPlayer.All.SendMessage(e.Message.Text, _main.ChatHandler.ChatColorOverride ?? Color.White);

                        // Strip tags when sending to console
                        TSPlayer.Server.SendMessage(e.Message.Text.StripTags(), _main.ChatHandler.ChatColorOverride ?? Color.White);
                    }
                }

                // We don't want to broadcast what other bots are saying; when we do, we use multi-server chat
                else if (e.User.IsBot)
                {
                    // If the channel is a Terraria channel, log the message
                    if (_main.Config.TerrariaChannels.Contains(e.Channel.Name))
                    {
                        Log.Info(e.Channel.Name, $"{e.User.Name}> {e.Message.Text}");
                    }

                    return;
                }

                else
                {
                    // Only broadcast non-self messages sent in game channels
                    if (_main.Config.TerrariaChannels.Contains(e.Channel.Name))
                    {
                        if (!String.IsNullOrWhiteSpace(_main.Config.MinimumRoleToBroadcast))
                        {
                            // Check for talk permission based on role
                            Role role = e.Server.FindRoles(_main.Config.MinimumRoleToBroadcast, true).FirstOrDefault();

                            // If role is null, incorrect setup, so disregard (should probably notify the log, however...)
                            if (role != null && !e.User.Roles.Contains(role))
                            {
                                // If the user doesn't have the set role, check role positions
                                int highestRolePosition = e.User.Roles.OrderBy(r => r.Position).Last().Position;
                                if (highestRolePosition < role.Position)
                                {
                                    // Todo: notify the user that their messages are not being broadcasted, but only nag them once
                                    return;
                                }
                            }
                        }

                        Role  topRole   = e.User.Roles.OrderBy(r => r.Position).Last();
                        Color roleColor = topRole.IsEveryone ? Color.Gray : new Color(topRole.Color.R, topRole.Color.G, topRole.Color.B);

                        BridgeUser player = await LoadUser(e.User);

                        // Setting up the color dictionary - if there is need for more colors, they may be added later
                        var colorDictionary = new Dictionary <string, Color?>
                        {
                            ["Role"]  = roleColor,
                            ["Group"] = player.IsLoggedIn ? new Color(player.Group.R, player.Group.G, player.Group.B) : roleColor,
                        };

                        #region Format Colors

                        var roleName = new ChatMessage.Section(topRole.IsEveryone ? _main.Config.DefaultRoleName : topRole.Name);
                        if (_main.Config.Broadcast.Colors.Role == DiscordBroadcastColor.Role || _main.Config.Broadcast.Colors.Role == DiscordBroadcastColor.Group)
                        {
                            roleName.Color = colorDictionary[_main.Config.Broadcast.Colors.Role.ToString()];
                        }

                        var name = new ChatMessage.Section(e.User.Name);
                        if (_main.Config.Broadcast.Colors.Name == DiscordBroadcastColor.Role || _main.Config.Broadcast.Colors.Name == DiscordBroadcastColor.Group)
                        {
                            name.Color = colorDictionary[_main.Config.Broadcast.Colors.Name.ToString()];
                        }

                        var nick = new ChatMessage.Section(String.IsNullOrWhiteSpace(e.User.Nickname) ? e.User.Name : e.User.Nickname);
                        if (_main.Config.Broadcast.Colors.Nickname == DiscordBroadcastColor.Role || _main.Config.Broadcast.Colors.Nickname == DiscordBroadcastColor.Group)
                        {
                            nick.Color = colorDictionary[_main.Config.Broadcast.Colors.Nickname.ToString()];
                        }

                        string text = e.Message.Text;

                        #endregion

                        string msg = String.Format(_main.Config.Broadcast.Format.ParseColors(colorDictionary),
                                                   roleName, name, nick, text);

                        TSPlayer.All.SendMessage(msg, _main.ChatHandler.ChatColorOverride ?? Color.White);

                        // Strip tags when sending to console
                        TSPlayer.Server.SendMessage(msg.StripTags(), _main.ChatHandler.ChatColorOverride ?? Color.White);
                    }

                    Log.Info(e.Channel.Name, $"Discord> {e.User.Name}: {e.Message.Text}");
                }
            }
            catch (Exception ex)
            {
                Log.Error("OnMessageReceived", ex.Message, ex);
            }
        }