FabioZumbi12 / SEDiscordBridge

A Torch plugin to connect the SE server to Discord
MIT License
13 stars 11 forks source link

Bot always offline on Win7 #22

Closed smooreace closed 5 years ago

smooreace commented 5 years ago

Added the plugin from inside the Torch launcher. Built application and added the bot. Configured everything. I'm not getting any errors that I can find, but the bot always shows offline. Am I missing something obvious? I know there are a million variables I'm not telling here. but I don't know what to offer to assist in getting assistance.

88tom commented 5 years ago

Same problem here

FabioZumbi12 commented 5 years ago

Probally something in your end. On the server when i play, (and no other people than you) isnt having a similar problem.

If no errors, the problem can be with discord or dshap lib too, i really dont know.

smooreace commented 5 years ago

I dont particularly think its NOT something on my end. But what? Discord is the same for everyone. And I have nothing to do with D#. So where do I go from here to fix this, or least start nailing down the problem?

On Mon, Apr 1, 2019 at 10:12 PM FabioZumbi12 notifications@github.com wrote:

Probally something in your end. On the server when i play, (and no other people than you) isnt having a similar problem.

If no errors, the problem can be with discord or dshap lib too, i really dont know.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22#issuecomment-478827405, or mute the thread https://github.com/notifications/unsubscribe-auth/Ah5OQxunxl3MxH8qv6BALlPBBHenJ2Ykks5vcsqxgaJpZM4cUAJy .

FabioZumbi12 commented 5 years ago

Humm, you can delete all SEDB configs and start from 0, and check all things about Bot setup in your Discord Dev Account.

Normally when we think is doing all ok is where is the problem.

About Bot configuration, dont confuse client secret with Bot Token:

image

smooreace commented 5 years ago

Bot token has 2 sectionswith a . in the middle Channel IDs are too straight forward to screw up

On Mon, Apr 1, 2019 at 10:46 PM FabioZumbi12 notifications@github.com wrote:

Humm, you can delete all SEDB configs and start from 0, and check all things about Bot setup in your Discord Dev Account.

Normally when we think is doing all ok is where is the problem.

About Bot configuration, dont confuse client secret with Bot Token:

[image: image] https://user-images.githubusercontent.com/5833818/55374974-ccfc3900-54e0-11e9-8e85-01d3c5af32ca.png

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22#issuecomment-478833275, or mute the thread https://github.com/notifications/unsubscribe-auth/Ah5OQwS8h41VEDgfmvrrtpyR2Tqz77Adks5vctKwgaJpZM4cUAJy .

88tom commented 5 years ago

I think the problem is with windows 7 or 2008 server and dotnet 462? Maybe we should use he core 2.2.3? EDIT: tried on windows 10 and work fine!, in windows 2008 r2 doesn't work EDIT2: Found a way to work on 2008 r2, i added in visual studio the dsharpplus websocket4net, and in DiscordBridge.cs before the discord.connectasync added this line: discord.SetWebSocketClient(); to change the connection method and it work..

FabioZumbi12 commented 5 years ago

thanks for tests... should i add this on release version?

88tom commented 5 years ago

If you add a check to identify the operating system yes! 😁

smooreace commented 5 years ago

My server is running on Win 7.

On Thu, Apr 4, 2019 at 1:41 AM 88tom notifications@github.com wrote:

If you add a check to identify the operating system yes! 😁

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22#issuecomment-479770783, or mute the thread https://github.com/notifications/unsubscribe-auth/Ah5OQ4nYhv9x7BigL3rUErdkzwQHr-Piks5vdZ6xgaJpZM4cUAJy .

88tom commented 5 years ago

try this pack SEDiscordBridge.zip

smooreace commented 5 years ago

If that was meant for me... it didnt solve the issue.

On Thu, Apr 4, 2019 at 8:40 AM 88tom notifications@github.com wrote:

try this pack SEDiscordBridge.zip https://github.com/FabioZumbi12/SEDiscordBridge/files/3043709/SEDiscordBridge.zip

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22#issuecomment-479901415, or mute the thread https://github.com/notifications/unsubscribe-auth/Ah5OQxBci8XZ3YOMUt2lXN7XCCzZXQRDks5vdgDbgaJpZM4cUAJy .

88tom commented 5 years ago

Mmm ok what version of dotnet have you installed? Try install the dotnet 4.7.2 also

smooreace commented 5 years ago

OK... stupid issue. This is a donated machine from a community member. He had Windows Updates turned off... so it was missing basically ALL .net shit Working on updating now. I'll get back to you once that's done. Thanks for your help thus far!

On Thu, Apr 4, 2019 at 5:18 PM 88tom notifications@github.com wrote:

Mmm ok what version of dotnet have you installed? Try install the dotnet 4.7.2 also

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22#issuecomment-480083934, or mute the thread https://github.com/notifications/unsubscribe-auth/Ah5OQ4G7EssUbnDJUOyvMLPVc0KvCgSSks5vdnojgaJpZM4cUAJy .

FabioZumbi12 commented 5 years ago

This issue will be available as reference for people with same issues ;)

smooreace commented 5 years ago

Sorry to open this back up, but even updated its having issues. With the plugin version thats linked in this issue thread I get an error in Torch...

17:08:49.1406 [ERROR] Torch.API.WebAPI.PluginQuery: Plugin query returned response NotFound

When I switch bac to the version that Torch grabs and restart Torch that error is no longer there, and the bot remains offline

88tom commented 5 years ago

Yes because i changed the guid on manifest due to the autoupdate, but is not an error

88tom commented 5 years ago

sorry my mistake, missing one dll! try this, it will work.. sorry again SEDiscordBridge.zip

smooreace commented 5 years ago

That one fixed it Took a bit for it to come online. But eventually, it popped up and is working great I think. At least it's working from Discord to the server. I'll hop on later and see that it works from that direction

Thanks for your work! If there is anything I can do to help in testing shit, or working through compatibility issues let me know

On Fri, Apr 5, 2019 at 8:53 AM 88tom notifications@github.com wrote:

sorry my mistake, missing one dll! try this, it will work.. sorry again SEDiscordBridge.zip https://github.com/FabioZumbi12/SEDiscordBridge/files/3048200/SEDiscordBridge.zip

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22#issuecomment-480283427, or mute the thread https://github.com/notifications/unsubscribe-auth/Ah5OQ8HF_Pxnw-liJt-y2BmJ4U49EP8nks5vd1U9gaJpZM4cUAJy .

smooreace commented 5 years ago

Sorry to open this again, but kinda needed to. Back a few messages up @88tom sent me a version that was slightly modified. Any chance I could con you out of the newest version with the same fix?

88tom commented 5 years ago

I see a lot of commit but no release, if is stable I can try to apply the fix to this version..

smooreace commented 5 years ago

Great!! Thanks. Wish I had the knowledge to do this myself.

On Thu, Sep 12, 2019 at 12:00 PM 88tom notifications@github.com wrote:

I see a lot of commit but no release, if is stable I can try to apply the fix to this version..

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22?email_source=notifications&email_token=AIPE4Q3FO7OXPZOLLMYFBD3QJJYUBA5CNFSM4HCQAJZKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD6SR7MQ#issuecomment-530915250, or mute the thread https://github.com/notifications/unsubscribe-auth/AIPE4Q7SD6UVB5JSZHXFAILQJJYUBANCNFSM4HCQAJZA .

FabioZumbi12 commented 5 years ago

@88tom i am releasing only on Torch plugin page now. https://torchapi.net/plugins/item/3cd3ba7f-c47c-4efe-8cf1-bd3f618f5b9c

smooreace commented 5 years ago

Good idea for the most part. Except in situations where people are running under Windows 7 still...

On Sat, Sep 14, 2019 at 2:04 PM FabioZumbi12 notifications@github.com wrote:

@88tom https://github.com/88tom i am releasing only on Torch plugin page now. https://torchapi.net/plugins/item/3cd3ba7f-c47c-4efe-8cf1-bd3f618f5b9c

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22?email_source=notifications&email_token=AIPE4Q53JFE6OQZ66SWZR3LQJUYSLA5CNFSM4HCQAJZKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD6XCCRY#issuecomment-531505479, or mute the thread https://github.com/notifications/unsubscribe-auth/AIPE4Q2ZAPIU436F4Z6TYYTQJUYSLANCNFSM4HCQAJZA .

FabioZumbi12 commented 5 years ago

If some of you find a way to support both Windows versions in only one sedb build, i can add to releases

smooreace commented 5 years ago

Will the version that runs on Win 7 not run on newer OSs?

On Sat, Sep 14, 2019 at 4:57 PM FabioZumbi12 notifications@github.com wrote:

If some of you find a way to support both Windows versions in only one sedb build, i can add to releases

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22?email_source=notifications&email_token=AIPE4Q4DJP2YJFIOYWTFMU3QJVM3PA5CNFSM4HCQAJZKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD6XE4RY#issuecomment-531516999, or mute the thread https://github.com/notifications/unsubscribe-auth/AIPE4Q6RK4TRSQ4H3LB4BYDQJVM3PANCNFSM4HCQAJZA .

88tom commented 5 years ago

SEDiscordBridge.zip

the only things that i add are: using DSharpPlus.Net.WebSocket; downloaded via nuget discord.SetWebSocketClient(); before the discord.ConnectAsync(); to change the default connection type and stop. Maybe you can add a condition when identify the system version.

smooreace commented 5 years ago

Thank you!

On Sun, Sep 15, 2019 at 7:22 AM 88tom notifications@github.com wrote:

SEDiscordBridge.zip https://github.com/FabioZumbi12/SEDiscordBridge/files/3613742/SEDiscordBridge.zip

the only things that i add are: using DSharpPlus.Net.WebSocket; downloaded via nuget discord.SetWebSocketClient(); before the discord.ConnectAsync(); to change the default connection type and stop. Maybe you can add a condition when identify the system version.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22?email_source=notifications&email_token=AIPE4Q5Z4WO4GHWEQIK5IW3QJYSHHA5CNFSM4HCQAJZKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD6XPVHQ#issuecomment-531561118, or mute the thread https://github.com/notifications/unsubscribe-auth/AIPE4Q6PEVAWBM6KADNERW3QJYSHHANCNFSM4HCQAJZA .

FabioZumbi12 commented 5 years ago

Did you built this zip under latest version? Can you post the code to i have some idea on how to add this?

88tom commented 5 years ago

this is the code of DiscordBridge.cs `using DSharpPlus; using DSharpPlus.Entities; using Sandbox.Game.Multiplayer; using Sandbox.Game.World; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Torch.API.Managers; using Torch.API.Session; using Torch.Commands; using VRage.Game; using VRage.Game.ModAPI; using DSharpPlus.Net.WebSocket;

namespace SEDiscordBridge { public class DiscordBridge { private static SEDiscordBridgePlugin Plugin; private static DiscordClient discord; private Thread thread; private DiscordGame game; private string lastMessage = ""; private ulong botId = 0;

    public bool Ready { get; set; } = false;
    public static int Cooldown;
    public static decimal Increment;
    public static decimal Factor;
    public static decimal CooldownNeutral;
    public static int FirstWarning;
    public static decimal MinIncrement;
    public static decimal Locked;
    public DiscordBridge(SEDiscordBridgePlugin plugin)
    {
        Plugin = plugin;

        Cooldown = plugin.Config.SimCooldown;
        Increment = (plugin.Config.StatusInterval / 1000);
        Factor = plugin.Config.SimCooldown / Increment;
        Increment = plugin.Config.SimCooldown / Increment;
        MinIncrement = 60 / (plugin.Config.StatusInterval / 1000);
        Locked = 0;

        thread = new Thread(() =>
        {
            RegisterDiscord().ConfigureAwait(false).GetAwaiter().GetResult();
        });
        thread.Start();
    }

    public void Stopdiscord()
    {
        thread = new Thread(() =>
        {
            DisconnectDiscord().ConfigureAwait(false).GetAwaiter().GetResult();
        });
        thread.Start();
    }

    private async Task DisconnectDiscord()
    {
        Ready = false;
        await discord?.DisconnectAsync();
    }

    private Task RegisterDiscord()
    {
        discord = new DiscordClient(new DiscordConfiguration
        {
            Token = Plugin.Config.BotToken,
            TokenType = TokenType.Bot
        });

        discord.SetWebSocketClient<WebSocket4NetClient>();
        discord.ConnectAsync();

        discord.MessageCreated += Discord_MessageCreated;
        game = new DiscordGame();

        discord.Ready += async e =>
        {
            Ready = true;
            await Task.CompletedTask;
        };
        return Task.CompletedTask;
    }

    public void SendStatus(string status)
    {
        if (Ready && status?.Length > 0)
        {
            game.Name = status;
            discord.UpdateStatusAsync(game);
        }
    }

    public void SendSimMessage(string msg)
    {
        try
        {
            if (Ready && Plugin.Config.SimChannel.Length > 0)
            {
                DiscordChannel chann = discord.GetChannelAsync(ulong.Parse(Plugin.Config.SimChannel)).Result;
                //mention
                msg = MentionNameToID(msg, chann);
                msg = Plugin.Config.SimMessage.Replace("{ts}", TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now).ToString());
                botId = discord.SendMessageAsync(chann, msg.Replace("/n", "\n")).Result.Author.Id;
            }
        }
        catch (Exception e)
        {
            DiscordChannel chann = discord.GetChannelAsync(ulong.Parse(Plugin.Config.SimChannel)).Result;
            botId = discord.SendMessageAsync(chann, e.ToString()).Result.Author.Id;
        }
    }

    public void SendChatMessage(string user, string msg)
    {
        try
        {
            if (lastMessage.Equals(user + msg)) return;

            if (Ready && Plugin.Config.ChatChannelId.Length > 0)
            {
                DiscordChannel chann = discord.GetChannelAsync(ulong.Parse(Plugin.Config.ChatChannelId)).Result;
                //mention
                msg = MentionNameToID(msg, chann);

                if (user != null)
                {
                    msg = Plugin.Config.Format.Replace("{msg}", msg).Replace("{p}", user).Replace("{ts}", TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now).ToString());
                }

                botId = discord.SendMessageAsync(chann, msg.Replace("/n", "\n")).Result.Author.Id;
            }
        }
        catch (Exception e)
        {
            DiscordChannel chann = discord.GetChannelAsync(ulong.Parse(Plugin.Config.ChatChannelId)).Result;
            botId = discord.SendMessageAsync(chann, e.ToString()).Result.Author.Id;
        }
    }

    public void SendFacChatMessage(string user, string msg, string facName)
    {
        IEnumerable<string> channelIds = Plugin.Config.FactionChannels.Where(c => c.Split(':')[0].Equals(facName));
        if (Ready && channelIds.Count() > 0)
        {
            foreach (string chId in channelIds)
            {
                DiscordChannel chann = discord.GetChannelAsync(ulong.Parse(chId.Split(':')[1])).Result;
                //mention
                msg = MentionNameToID(msg, chann);

                if (user != null)
                {
                    msg = Plugin.Config.FacFormat.Replace("{msg}", msg).Replace("{p}", user).Replace("{ts}", TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now).ToString());
                }
                botId = discord.SendMessageAsync(chann, msg.Replace("/n", "\n")).Result.Author.Id; ;
            }
        }
    }

    public void SendStatusMessage(string user, string msg)
    {
        if (Ready && Plugin.Config.StatusChannelId.Length > 0)
        {
            DiscordChannel chann = discord.GetChannelAsync(ulong.Parse(Plugin.Config.StatusChannelId)).Result;

            if (user != null)
            {
                if (user.StartsWith("ID:"))
                    return;

                msg = msg.Replace("{p}", user).Replace("{ts}", TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now).ToString());
            }

            botId = discord.SendMessageAsync(chann, msg.Replace("/n", "\n")).Result.Author.Id; 
        }
    }

    private Task Discord_MessageCreated(DSharpPlus.EventArgs.MessageCreateEventArgs e)
    {
        if (!e.Author.IsBot || (!botId.Equals(e.Author.Id) && Plugin.Config.BotToGame))
        {
            string comChannelId = Plugin.Config.CommandChannelId;
            if (comChannelId != "")
            {
                //execute commands
                if (e.Channel.Id.Equals(ulong.Parse(Plugin.Config.CommandChannelId)) && e.Message.Content.StartsWith(Plugin.Config.CommandPrefix))
                {
                    string cmd = e.Message.Content.Substring(Plugin.Config.CommandPrefix.Length);
                    var cmdText = new string(cmd.Skip(1).ToArray());

                    if (Plugin.Torch.CurrentSession?.State == TorchSessionState.Loaded)
                    {
                        var manager = Plugin.Torch.CurrentSession.Managers.GetManager<CommandManager>();
                        var command = manager.Commands.GetCommand(cmdText, out string argText);

                        if (command == null)
                        {
                            SendCmdResponse("Command not found: " + cmdText, e.Channel);
                        }
                        else
                        {
                            var cmdPath = string.Join(".", command.Path);
                            var splitArgs = Regex.Matches(argText, "(\"[^\"]+\"|\\S+)").Cast<Match>().Select(x => x.ToString().Replace("\"", "")).ToList();
                            SEDiscordBridgePlugin.Log.Trace($"Invoking {cmdPath} for server.");

                            var context = new SEDBCommandHandler(Plugin.Torch, command.Plugin, Sync.MyId, argText, splitArgs);
                            context.ResponeChannel = e.Channel;
                            context.OnResponse += OnCommandResponse;
                            var invokeSuccess = false;
                            Plugin.Torch.InvokeBlocking(() => invokeSuccess = command.TryInvoke(context));
                            SEDiscordBridgePlugin.Log.Debug($"invokeSuccess {invokeSuccess}");
                            if (!invokeSuccess)
                            {
                                SendCmdResponse("Error executing command: " + cmdText, e.Channel);
                            }
                            SEDiscordBridgePlugin.Log.Info($"Server ran command '{string.Join(" ", cmdText)}'");
                        }
                    }
                    else
                    {
                        SendCmdResponse("Error: Server is not running.", e.Channel);
                    }
                    return Task.CompletedTask;
                }
            }

            //send to global
            if (e.Channel.Id.Equals(ulong.Parse(Plugin.Config.ChatChannelId)))
            {
                string sender = Plugin.Config.ServerName;

                if (!Plugin.Config.AsServer)
                {
                    if (Plugin.Config.UseNicks)
                        sender = e.Guild.GetMemberAsync(e.Author.Id).Result.Nickname;
                    else
                        sender = e.Author.Username;
                }

                var manager = Plugin.Torch.CurrentSession.Managers.GetManager<IChatManagerServer>();
                var dSender = Plugin.Config.Format2.Replace("{p}", sender);
                var msg = MentionIDToName(e.Message);
                lastMessage = dSender + msg;
                manager.SendMessageAsOther(dSender, msg,
                    typeof(MyFontEnum).GetFields().Select(x => x.Name).Where(x => x.Equals(Plugin.Config.GlobalColor)).First());
            }

            //send to faction
            IEnumerable<string> channelIds = Plugin.Config.FactionChannels.Where(c => e.Channel.Id.Equals(ulong.Parse(c.Split(':')[1])));
            if (channelIds.Count() > 0)
            {
                foreach (string chId in channelIds)
                {
                    IEnumerable<IMyFaction> facs = MySession.Static.Factions.Factions.Values.Where(f => f.Name.Equals(chId.Split(':')[0]));
                    if (facs.Count() > 0)
                    {
                        IMyFaction fac = facs.First();
                        foreach (MyFactionMember mb in fac.Members.Values)
                        {
                            if (!MySession.Static.Players.GetOnlinePlayers().Any(p => p.Identity.IdentityId.Equals(mb.PlayerId)))
                                continue;

                            ulong steamid = MySession.Static.Players.TryGetSteamId(mb.PlayerId);
                            string sender = Plugin.Config.ServerName;
                            if (!Plugin.Config.AsServer)
                            {
                                if (Plugin.Config.UseNicks)
                                    sender = e.Guild.GetMemberAsync(e.Author.Id).Result.Nickname;
                                else
                                    sender = e.Author.Username;
                            }
                            var manager = Plugin.Torch.CurrentSession.Managers.GetManager<IChatManagerServer>();
                            var dSender = Plugin.Config.Format2.Replace("{p}", sender);
                            var msg = MentionIDToName(e.Message);
                            lastMessage = dSender + msg;
                            manager.SendMessageAsOther(dSender, msg,
                                typeof(MyFontEnum).GetFields().Select(x => x.Name).Where(x => x.Equals(Plugin.Config.FacColor)).First(), steamid);
                        }
                    }
                }
            }
        }
        return Task.CompletedTask;
    }

    private void SendCmdResponse(string response, DiscordChannel chann)
    {
        DiscordMessage dms = discord.SendMessageAsync(chann, response).Result;
        botId = dms.Author.Id;
        if (Plugin.Config.RemoveResponse > 0)
            Task.Delay(Plugin.Config.RemoveResponse * 1000).ContinueWith(t => dms?.DeleteAsync());
    }

    private string MentionNameToID(string msg, DiscordChannel chann)
    {
        try
        {

            var parts = msg.Split(' ');
            foreach (string part in parts)
            {
                if (part.Length > 2)
                {
                    if (part.StartsWith("@"))
                    {
                        string name = Regex.Replace(part.Substring(1), @"[,#]", "");
                        if (String.Compare(name, "everyone", true) == 0 && !Plugin.Config.MentEveryone)
                        {
                            msg = msg.Replace(part, part.Substring(1));
                            continue;
                        }
                        try
                        {
                            var members = chann.Guild.GetAllMembersAsync().Result;

                            if (!Plugin.Config.MentOthers)
                            {
                                continue;
                            }
                            var memberByNickname = members.FirstOrDefault((u) => String.Compare(u.Nickname, name, true) == 0);
                            if (memberByNickname != null)
                            {
                                msg = msg.Replace(part, $"<@{memberByNickname.Id}>");
                                continue;
                            }
                            var memberByUsername = members.FirstOrDefault((u) => String.Compare(u.Username, name, true) == 0);
                            if (memberByUsername != null)
                            {
                                msg = msg.Replace(part, $"<@{memberByUsername.Id}>");
                                continue;
                            }
                        }
                        catch (Exception)
                        {
                            SEDiscordBridgePlugin.Log.Warn("Error on convert a member id to name on mention other players.");
                            continue;
                        }
                    }

                    var emojis = chann.Guild.Emojis;
                    if (part.StartsWith(":") && part.EndsWith(":") && emojis.Any(e => String.Compare(e.GetDiscordName(), part, true) == 0))
                    {
                        msg = msg.Replace(part, "<" + part + emojis.Where(e => String.Compare(e.GetDiscordName(), part, true) == 0).First().Id + ">");
                    }
                }
            }
        }
        catch (Exception e)
        {
            SEDiscordBridgePlugin.Log.Warn(e, "Error on convert a member id to name on mention other players.");
        }
        return msg;
    }

    private string MentionIDToName(DiscordMessage ddMsg)
    {
        string msg = ddMsg.Content;
        var parts = msg.Split(' ');
        foreach (string part in parts)
        {
            if (part.StartsWith("<@") && part.EndsWith(">"))
            {
                try
                {
                    ulong id = ulong.Parse(part.Substring(2, part.Length - 3));

                    var name = discord.GetUserAsync(id).Result.Username;
                    if (Plugin.Config.UseNicks)
                        name = ddMsg.Channel.Guild.GetMemberAsync(id).Result.Nickname;

                    msg = msg.Replace(part, "@" + name);
                }
                catch (FormatException) { }
            }
            if (part.StartsWith("<:") && part.EndsWith(">"))
            {
                string id = part.Substring(2, part.Length - 3);
                msg = msg.Replace(part, ":" + id.Split(':')[0] + ":");
            }
        }
        return msg;
    }

    private void OnCommandResponse(DiscordChannel channel, string message, string sender = "Server", string font = "White")
    {
        SEDiscordBridgePlugin.Log.Debug($"response length {message.Length}");
        if (message.Length > 0)
        {
            message = message.Replace("_", "\\_")
                .Replace("*", "\\*")
                .Replace("~", "\\~");

            const int chunkSize = 2000 - 1; // Remove 1 just ensure everything is ok

            if (message.Length <= chunkSize)
            {
                SendCmdResponse(message, channel);
            }
            else
            {
                var index = 0;
                do
                {

                    SEDiscordBridgePlugin.Log.Debug($"while iteration index {index}");

                    /* if remaining part of message is small enough then just output it. */
                    if (index + chunkSize >= message.Length)
                    {
                        SendCmdResponse(message.Substring(index), channel);
                        break;
                    }

                    var chunk = message.Substring(index, chunkSize);
                    var newLineIndex = chunk.LastIndexOf("\n");
                    SEDiscordBridgePlugin.Log.Debug($"while iteration newLineIndex {newLineIndex}");

                    SendCmdResponse(chunk.Substring(0, newLineIndex), channel);
                    index += newLineIndex + 1;

                } while (index < message.Length);
            }
        }
    }
}

} `

smooreace commented 5 years ago

Thanks again... working perfectly!

On Sun, Sep 15, 2019 at 1:18 PM 88tom notifications@github.com wrote:

this is the code of DiscordBridge.cs `using DSharpPlus; using DSharpPlus.Entities; using Sandbox.Game.Multiplayer; using Sandbox.Game.World; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Torch.API.Managers; using Torch.API.Session; using Torch.Commands; using VRage.Game; using VRage.Game.ModAPI; using DSharpPlus.Net.WebSocket;

namespace SEDiscordBridge { public class DiscordBridge { private static SEDiscordBridgePlugin Plugin; private static DiscordClient discord; private Thread thread; private DiscordGame game; private string lastMessage = ""; private ulong botId = 0;

public bool Ready { get; set; } = false;
public static int Cooldown;
public static decimal Increment;
public static decimal Factor;
public static decimal CooldownNeutral;
public static int FirstWarning;
public static decimal MinIncrement;
public static decimal Locked;
public DiscordBridge(SEDiscordBridgePlugin plugin)
{
    Plugin = plugin;

    Cooldown = plugin.Config.SimCooldown;
    Increment = (plugin.Config.StatusInterval / 1000);
    Factor = plugin.Config.SimCooldown / Increment;
    Increment = plugin.Config.SimCooldown / Increment;
    MinIncrement = 60 / (plugin.Config.StatusInterval / 1000);
    Locked = 0;

    thread = new Thread(() =>
    {
        RegisterDiscord().ConfigureAwait(false).GetAwaiter().GetResult();
    });
    thread.Start();
}

public void Stopdiscord()
{
    thread = new Thread(() =>
    {
        DisconnectDiscord().ConfigureAwait(false).GetAwaiter().GetResult();
    });
    thread.Start();
}

private async Task DisconnectDiscord()
{
    Ready = false;
    await discord?.DisconnectAsync();
}

private Task RegisterDiscord()
{
    discord = new DiscordClient(new DiscordConfiguration
    {
        Token = Plugin.Config.BotToken,
        TokenType = TokenType.Bot
    });

    discord.SetWebSocketClient<WebSocket4NetClient>();
    discord.ConnectAsync();

    discord.MessageCreated += Discord_MessageCreated;
    game = new DiscordGame();

    discord.Ready += async e =>
    {
        Ready = true;
        await Task.CompletedTask;
    };
    return Task.CompletedTask;
}

public void SendStatus(string status)
{
    if (Ready && status?.Length > 0)
    {
        game.Name = status;
        discord.UpdateStatusAsync(game);
    }
}

public void SendSimMessage(string msg)
{
    try
    {
        if (Ready && Plugin.Config.SimChannel.Length > 0)
        {
            DiscordChannel chann = discord.GetChannelAsync(ulong.Parse(Plugin.Config.SimChannel)).Result;
            //mention
            msg = MentionNameToID(msg, chann);
            msg = Plugin.Config.SimMessage.Replace("{ts}", TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now).ToString());
            botId = discord.SendMessageAsync(chann, msg.Replace("/n", "\n")).Result.Author.Id;
        }
    }
    catch (Exception e)
    {
        DiscordChannel chann = discord.GetChannelAsync(ulong.Parse(Plugin.Config.SimChannel)).Result;
        botId = discord.SendMessageAsync(chann, e.ToString()).Result.Author.Id;
    }
}

public void SendChatMessage(string user, string msg)
{
    try
    {
        if (lastMessage.Equals(user + msg)) return;

        if (Ready && Plugin.Config.ChatChannelId.Length > 0)
        {
            DiscordChannel chann = discord.GetChannelAsync(ulong.Parse(Plugin.Config.ChatChannelId)).Result;
            //mention
            msg = MentionNameToID(msg, chann);

            if (user != null)
            {
                msg = Plugin.Config.Format.Replace("{msg}", msg).Replace("{p}", user).Replace("{ts}", TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now).ToString());
            }

            botId = discord.SendMessageAsync(chann, msg.Replace("/n", "\n")).Result.Author.Id;
        }
    }
    catch (Exception e)
    {
        DiscordChannel chann = discord.GetChannelAsync(ulong.Parse(Plugin.Config.ChatChannelId)).Result;
        botId = discord.SendMessageAsync(chann, e.ToString()).Result.Author.Id;
    }
}

public void SendFacChatMessage(string user, string msg, string facName)
{
    IEnumerable<string> channelIds = Plugin.Config.FactionChannels.Where(c => c.Split(':')[0].Equals(facName));
    if (Ready && channelIds.Count() > 0)
    {
        foreach (string chId in channelIds)
        {
            DiscordChannel chann = discord.GetChannelAsync(ulong.Parse(chId.Split(':')[1])).Result;
            //mention
            msg = MentionNameToID(msg, chann);

            if (user != null)
            {
                msg = Plugin.Config.FacFormat.Replace("{msg}", msg).Replace("{p}", user).Replace("{ts}", TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now).ToString());
            }
            botId = discord.SendMessageAsync(chann, msg.Replace("/n", "\n")).Result.Author.Id; ;
        }
    }
}

public void SendStatusMessage(string user, string msg)
{
    if (Ready && Plugin.Config.StatusChannelId.Length > 0)
    {
        DiscordChannel chann = discord.GetChannelAsync(ulong.Parse(Plugin.Config.StatusChannelId)).Result;

        if (user != null)
        {
            if (user.StartsWith("ID:"))
                return;

            msg = msg.Replace("{p}", user).Replace("{ts}", TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now).ToString());
        }

        botId = discord.SendMessageAsync(chann, msg.Replace("/n", "\n")).Result.Author.Id;
    }
}

private Task Discord_MessageCreated(DSharpPlus.EventArgs.MessageCreateEventArgs e)
{
    if (!e.Author.IsBot || (!botId.Equals(e.Author.Id) && Plugin.Config.BotToGame))
    {
        string comChannelId = Plugin.Config.CommandChannelId;
        if (comChannelId != "")
        {
            //execute commands
            if (e.Channel.Id.Equals(ulong.Parse(Plugin.Config.CommandChannelId)) && e.Message.Content.StartsWith(Plugin.Config.CommandPrefix))
            {
                string cmd = e.Message.Content.Substring(Plugin.Config.CommandPrefix.Length);
                var cmdText = new string(cmd.Skip(1).ToArray());

                if (Plugin.Torch.CurrentSession?.State == TorchSessionState.Loaded)
                {
                    var manager = Plugin.Torch.CurrentSession.Managers.GetManager<CommandManager>();
                    var command = manager.Commands.GetCommand(cmdText, out string argText);

                    if (command == null)
                    {
                        SendCmdResponse("Command not found: " + cmdText, e.Channel);
                    }
                    else
                    {
                        var cmdPath = string.Join(".", command.Path);
                        var splitArgs = Regex.Matches(argText, "(\"[^\"]+\"|\\S+)").Cast<Match>().Select(x => x.ToString().Replace("\"", "")).ToList();
                        SEDiscordBridgePlugin.Log.Trace($"Invoking {cmdPath} for server.");

                        var context = new SEDBCommandHandler(Plugin.Torch, command.Plugin, Sync.MyId, argText, splitArgs);
                        context.ResponeChannel = e.Channel;
                        context.OnResponse += OnCommandResponse;
                        var invokeSuccess = false;
                        Plugin.Torch.InvokeBlocking(() => invokeSuccess = command.TryInvoke(context));
                        SEDiscordBridgePlugin.Log.Debug($"invokeSuccess {invokeSuccess}");
                        if (!invokeSuccess)
                        {
                            SendCmdResponse("Error executing command: " + cmdText, e.Channel);
                        }
                        SEDiscordBridgePlugin.Log.Info($"Server ran command '{string.Join(" ", cmdText)}'");
                    }
                }
                else
                {
                    SendCmdResponse("Error: Server is not running.", e.Channel);
                }
                return Task.CompletedTask;
            }
        }

        //send to global
        if (e.Channel.Id.Equals(ulong.Parse(Plugin.Config.ChatChannelId)))
        {
            string sender = Plugin.Config.ServerName;

            if (!Plugin.Config.AsServer)
            {
                if (Plugin.Config.UseNicks)
                    sender = e.Guild.GetMemberAsync(e.Author.Id).Result.Nickname;
                else
                    sender = e.Author.Username;
            }

            var manager = Plugin.Torch.CurrentSession.Managers.GetManager<IChatManagerServer>();
            var dSender = Plugin.Config.Format2.Replace("{p}", sender);
            var msg = MentionIDToName(e.Message);
            lastMessage = dSender + msg;
            manager.SendMessageAsOther(dSender, msg,
                typeof(MyFontEnum).GetFields().Select(x => x.Name).Where(x => x.Equals(Plugin.Config.GlobalColor)).First());
        }

        //send to faction
        IEnumerable<string> channelIds = Plugin.Config.FactionChannels.Where(c => e.Channel.Id.Equals(ulong.Parse(c.Split(':')[1])));
        if (channelIds.Count() > 0)
        {
            foreach (string chId in channelIds)
            {
                IEnumerable<IMyFaction> facs = MySession.Static.Factions.Factions.Values.Where(f => f.Name.Equals(chId.Split(':')[0]));
                if (facs.Count() > 0)
                {
                    IMyFaction fac = facs.First();
                    foreach (MyFactionMember mb in fac.Members.Values)
                    {
                        if (!MySession.Static.Players.GetOnlinePlayers().Any(p => p.Identity.IdentityId.Equals(mb.PlayerId)))
                            continue;

                        ulong steamid = MySession.Static.Players.TryGetSteamId(mb.PlayerId);
                        string sender = Plugin.Config.ServerName;
                        if (!Plugin.Config.AsServer)
                        {
                            if (Plugin.Config.UseNicks)
                                sender = e.Guild.GetMemberAsync(e.Author.Id).Result.Nickname;
                            else
                                sender = e.Author.Username;
                        }
                        var manager = Plugin.Torch.CurrentSession.Managers.GetManager<IChatManagerServer>();
                        var dSender = Plugin.Config.Format2.Replace("{p}", sender);
                        var msg = MentionIDToName(e.Message);
                        lastMessage = dSender + msg;
                        manager.SendMessageAsOther(dSender, msg,
                            typeof(MyFontEnum).GetFields().Select(x => x.Name).Where(x => x.Equals(Plugin.Config.FacColor)).First(), steamid);
                    }
                }
            }
        }
    }
    return Task.CompletedTask;
}

private void SendCmdResponse(string response, DiscordChannel chann)
{
    DiscordMessage dms = discord.SendMessageAsync(chann, response).Result;
    botId = dms.Author.Id;
    if (Plugin.Config.RemoveResponse > 0)
        Task.Delay(Plugin.Config.RemoveResponse * 1000).ContinueWith(t => dms?.DeleteAsync());
}

private string MentionNameToID(string msg, DiscordChannel chann)
{
    try
    {

        var parts = msg.Split(' ');
        foreach (string part in parts)
        {
            if (part.Length > 2)
            {
                if (part.StartsWith("@"))
                {
                    string name = Regex.Replace(part.Substring(1), @"[,#]", "");
                    if (String.Compare(name, "everyone", true) == 0 && !Plugin.Config.MentEveryone)
                    {
                        msg = msg.Replace(part, part.Substring(1));
                        continue;
                    }
                    try
                    {
                        var members = chann.Guild.GetAllMembersAsync().Result;

                        if (!Plugin.Config.MentOthers)
                        {
                            continue;
                        }
                        var memberByNickname = members.FirstOrDefault((u) => String.Compare(u.Nickname, name, true) == 0);
                        if (memberByNickname != null)
                        {
                            msg = msg.Replace(part, $"<@{memberByNickname.Id}>");
                            continue;
                        }
                        var memberByUsername = members.FirstOrDefault((u) => String.Compare(u.Username, name, true) == 0);
                        if (memberByUsername != null)
                        {
                            msg = msg.Replace(part, $"<@{memberByUsername.Id}>");
                            continue;
                        }
                    }
                    catch (Exception)
                    {
                        SEDiscordBridgePlugin.Log.Warn("Error on convert a member id to name on mention other players.");
                        continue;
                    }
                }

                var emojis = chann.Guild.Emojis;
                if (part.StartsWith(":") && part.EndsWith(":") && emojis.Any(e => String.Compare(e.GetDiscordName(), part, true) == 0))
                {
                    msg = msg.Replace(part, "<" + part + emojis.Where(e => String.Compare(e.GetDiscordName(), part, true) == 0).First().Id + ">");
                }
            }
        }
    }
    catch (Exception e)
    {
        SEDiscordBridgePlugin.Log.Warn(e, "Error on convert a member id to name on mention other players.");
    }
    return msg;
}

private string MentionIDToName(DiscordMessage ddMsg)
{
    string msg = ddMsg.Content;
    var parts = msg.Split(' ');
    foreach (string part in parts)
    {
        if (part.StartsWith("<@") && part.EndsWith(">"))
        {
            try
            {
                ulong id = ulong.Parse(part.Substring(2, part.Length - 3));

                var name = discord.GetUserAsync(id).Result.Username;
                if (Plugin.Config.UseNicks)
                    name = ddMsg.Channel.Guild.GetMemberAsync(id).Result.Nickname;

                msg = msg.Replace(part, "@" + name);
            }
            catch (FormatException) { }
        }
        if (part.StartsWith("<:") && part.EndsWith(">"))
        {
            string id = part.Substring(2, part.Length - 3);
            msg = msg.Replace(part, ":" + id.Split(':')[0] + ":");
        }
    }
    return msg;
}

private void OnCommandResponse(DiscordChannel channel, string message, string sender = "Server", string font = "White")
{
    SEDiscordBridgePlugin.Log.Debug($"response length {message.Length}");
    if (message.Length > 0)
    {
        message = message.Replace("_", "\\_")
            .Replace("*", "\\*")
            .Replace("~", "\\~");

        const int chunkSize = 2000 - 1; // Remove 1 just ensure everything is ok

        if (message.Length <= chunkSize)
        {
            SendCmdResponse(message, channel);
        }
        else
        {
            var index = 0;
            do
            {

                SEDiscordBridgePlugin.Log.Debug($"while iteration index {index}");

                /* if remaining part of message is small enough then just output it. */
                if (index + chunkSize >= message.Length)
                {
                    SendCmdResponse(message.Substring(index), channel);
                    break;
                }

                var chunk = message.Substring(index, chunkSize);
                var newLineIndex = chunk.LastIndexOf("\n");
                SEDiscordBridgePlugin.Log.Debug($"while iteration newLineIndex {newLineIndex}");

                SendCmdResponse(chunk.Substring(0, newLineIndex), channel);
                index += newLineIndex + 1;

            } while (index < message.Length);
        }
    }
}

}

} `

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22?email_source=notifications&email_token=AIPE4Q2HEVCMSPAZCDRMPQTQJZ35ZA5CNFSM4HCQAJZKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD6XWDZY#issuecomment-531587559, or mute the thread https://github.com/notifications/unsubscribe-auth/AIPE4Q3CTPVSSFYD7S4RJX3QJZ35ZANCNFSM4HCQAJZA .

FabioZumbi12 commented 5 years ago

@smooreace can you test this version if works like @88tom version? SEDiscordBridge.zip

smooreace commented 5 years ago

Sorry... forgot to delete plugin entries from torch.cfg

No error after fixing that Bot came back online as it should

On Sun, Sep 15, 2019 at 10:50 PM Steve Moore smooreace@gmail.com wrote:

23:49:44.0123 [INFO] Keen: Environment.CurrentDirectory:

C:\Users\Brad\Desktop\Space Engineers via Torch 23:49:44.0983 [ERROR] PluginQuery: Plugin query returned response NotFound 23:49:44.0983 [ERROR] PluginManager: System.NullReferenceException: Object reference not set to an instance of an object. at Torch.Managers.PluginManager.<>cDisplayClass15_1.<b0>d.MoveNext() in C:\jenkins\workspace\Torch_Torch_master\Torch\Plugins\PluginManager.cs:line 146 System.NullReferenceException: Object reference not set to an instance of an object. at Torch.Managers.PluginManager.<>cDisplayClass15_1.<b0>d.MoveNext() in C:\jenkins\workspace\Torch_Torch_master\Torch\Plugins\PluginManager.cs:line 146 23:49:45.0663 [INFO] Keen: CPU Info: AMD FX(tm)-9590 Eight-Core Processor

On Sun, Sep 15, 2019 at 7:58 PM FabioZumbi12 notifications@github.com wrote:

@smooreace https://github.com/smooreace can you test this version if works like @88tom https://github.com/88tom version? SEDiscordBridge.zip https://github.com/FabioZumbi12/SEDiscordBridge/files/3614492/SEDiscordBridge.zip

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22?email_source=notifications&email_token=AIPE4QYDKMOR5BMRHMGRJOLQJ3K2HA5CNFSM4HCQAJZKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD6X47YA#issuecomment-531615712, or mute the thread https://github.com/notifications/unsubscribe-auth/AIPE4QYX7WEBMZWL52MLA23QJ3K2HANCNFSM4HCQAJZA .

FabioZumbi12 commented 5 years ago

What you mean? It worked or not?

smooreace commented 5 years ago

Sorry, that did all come out a little messy!

First attempt failed. I didnt delete the plugin IDs from

After clearing that section it worked perfectly

On Mon, Sep 16, 2019 at 6:28 AM FabioZumbi12 notifications@github.com wrote:

What you mean? It worked or not?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/FabioZumbi12/SEDiscordBridge/issues/22?email_source=notifications&email_token=AIPE4Q7653QYAXRY4XDI3LLQJ5UWFA5CNFSM4HCQAJZKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD6Y244Q#issuecomment-531738226, or mute the thread https://github.com/notifications/unsubscribe-auth/AIPE4Q6C56Z7XHYM42V6NLDQJ5UWFANCNFSM4HCQAJZA .