void IModule.Install(ModuleManager manager)
        {
            _client = manager.Client;
            _client.MessageReceived +=
                (s, e) =>
            {
                StringBuilder builder = new StringBuilder($"Msg: ");

                if (e.Server != null)
                {
                    builder.Append($"{e.Server.Name} ");
                }

                builder.Append(e.Channel.Name);

                Logger.FormattedWrite(builder.ToString(), e.Message.ToString(),
                                      ConsoleColor.White);
            };

            _io = _client.GetService <DataIoService>();

            manager.CreateCommands("", group =>
            {
                group.MinPermissions((int)PermissionLevel.BotOwner);

                group.CreateCommand("io save")
                .Description("Saves data used by the bot.")
                .Do(e => _io.Save());

                group.CreateCommand("io load")
                .Description("Loads data that the bot loads at runtime.")
                .Do(e => _io.Load());

                group.CreateCommand("set name")
                .Description("Changes the name of the bot")
                .Parameter("name", ParameterType.Unparsed)
                .Do(async e => await _client.CurrentUser.Edit(Config.Pass, e.GetArg("name")));

                group.CreateCommand("set avatar")
                .Description("Changes the avatar of the bot")
                .Parameter("name")
                .Do(async e =>
                {
                    string avDir = Constants.DataFolderDir + e.GetArg("name");

                    using (FileStream stream = new FileStream(avDir, FileMode.Open))
                    {
                        ImageType type;
                        switch (Path.GetExtension(avDir))
                        {
                        case ".jpg":
                        case ".jpeg":
                            type = ImageType.Jpeg;
                            break;

                        case ".png":
                            type = ImageType.Png;
                            break;

                        default:
                            return;
                        }

                        await _client.CurrentUser.Edit(Config.Pass, avatar: stream, avatarType: type);
                    }
                });

                group.CreateCommand("set game")
                .Description("Sets the current played game for the bot.")
                .Parameter("game", ParameterType.Unparsed)
                .Do(e => _client.SetGame(e.GetArg("game")));

                group.CreateCommand("killbot")
                .Description("Kills the bot.")
                .Do(x =>
                {
                    _io.Save();
                    Environment.Exit(0);
                });

                group.CreateCommand("gc")
                .Description("Lists used memory, then collects it.")
                .Do(async e =>
                {
                    await PrintMemUsage(e);
                    await Collect(e);
                });

                group.CreateCommand("gc collect")
                .Description("Calls GC.Collect()")
                .Do(async e => await Collect(e));

                group.CreateCommand("gencmdmd")
                .AddCheck((cmd, usr, chnl) => !chnl.IsPrivate)
                .Do(async e => await DiscordUtils.GenerateCommandMarkdown(_client));
            });

            manager.CreateDynCommands("", PermissionLevel.User, group =>
            {
                group.CreateCommand("join")
                .Description("Joins a server by invite.")
                .Parameter("invite")
                .Do(async e => await DiscordUtils.JoinInvite(e.GetArg("invite"), e.Channel));

                group.CreateCommand("leave")
                .Description("Instructs the bot to leave this server.")
                .MinDynPermissions((int)PermissionLevel.ServerModerator)
                .Do(async e => await e.Server.Leave());

                group.CreateCommand("cleanmsg")
                .Description("Removes the last 100 messages sent by the bot in this channel.")
                .MinPermissions((int)PermissionLevel.ChannelModerator)
                .Do(async e =>
                {
                    foreach (Message msg in (await e.Channel.DownloadMessages()).Where(m => m.IsAuthor))
                    {
                        await msg.Delete();
                    }
                });

                group.CreateCommand("gc list")
                .Description("Calls GC.GetTotalMemory()")
                .Do(async e => await PrintMemUsage(e));
            });

            manager.MessageReceived += async(s, e) =>
            {
                if (!e.Channel.IsPrivate)
                {
                    return;
                }

                if (e.Message.Text.StartsWith("https://discord"))
                {
                    string invite = string.Empty;
                    try
                    {
                        invite = e.Message.Text.Split(' ').FirstOrDefault();
                    }
                    catch
                    {
                    } // ignored

                    if (!string.IsNullOrEmpty(invite))
                    {
                        await DiscordUtils.JoinInvite(invite, e.Channel);
                    }
                }
            };
        }
        void IModule.Install(ModuleManager manager)
        {
            _client = manager.Client;
            _client.MessageReceived +=
                (s, e) =>
                {
                    StringBuilder builder = new StringBuilder($"Msg: ");

                    if (e.Server != null)
                        builder.Append($"{e.Server.Name} ");

                    builder.Append(e.Channel.Name);

                    Logger.FormattedWrite(builder.ToString(), e.Message.ToString(),
                        ConsoleColor.White);
                };

            _io = _client.GetService<DataIoService>();

            manager.CreateCommands("", group =>
            {
                group.MinPermissions((int) PermissionLevel.BotOwner);

                group.CreateCommand("io save")
                    .Description("Saves data used by the bot.")
                    .Do(e => _io.Save());

                group.CreateCommand("io load")
                    .Description("Loads data that the bot loads at runtime.")
                    .Do(e => _io.Load());

                group.CreateCommand("set name")
                    .Description("Changes the name of the bot")
                    .Parameter("name", ParameterType.Unparsed)
                    .Do(async e => await _client.CurrentUser.Edit(Config.Pass, e.GetArg("name")));

                group.CreateCommand("set avatar")
                    .Description("Changes the avatar of the bot")
                    .Parameter("name")
                    .Do(async e =>
                    {
                        string avDir = Constants.DataFolderDir + e.GetArg("name");

                        using (FileStream stream = new FileStream(avDir, FileMode.Open))
                        {
                            ImageType type;
                            switch (Path.GetExtension(avDir))
                            {
                                case ".jpg":
                                case ".jpeg":
                                    type = ImageType.Jpeg;
                                    break;
                                case ".png":
                                    type = ImageType.Png;
                                    break;
                                default:
                                    return;
                            }

                            await _client.CurrentUser.Edit(Config.Pass, avatar: stream, avatarType: type);
                        }
                    });

                group.CreateCommand("set game")
                    .Description("Sets the current played game for the bot.")
                    .Parameter("game", ParameterType.Unparsed)
                    .Do(e => _client.SetGame(e.GetArg("game")));

                group.CreateCommand("killbot")
                    .Description("Kills the bot.")
                    .Do(x =>
                    {
                        _io.Save();
                        Environment.Exit(0);
                    });

                group.CreateCommand("gc")
                    .Description("Lists used memory, then collects it.")
                    .Do(async e =>
                    {
                        await PrintMemUsage(e);
                        await Collect(e);
                    });

                group.CreateCommand("gc collect")
                    .Description("Calls GC.Collect()")
                    .Do(async e => await Collect(e));

                group.CreateCommand("gencmdmd")
                    .AddCheck((cmd, usr, chnl) => !chnl.IsPrivate)
                    .Do(async e => await DiscordUtils.GenerateCommandMarkdown(_client));
            });

            manager.CreateDynCommands("", PermissionLevel.User, group =>
            {
                group.CreateCommand("join")
                    .Description("Joins a server by invite.")
                    .Parameter("invite")
                    .Do(async e => await DiscordUtils.JoinInvite(e.GetArg("invite"), e.Channel));

                group.CreateCommand("leave")
                    .Description("Instructs the bot to leave this server.")
                    .MinDynPermissions((int) PermissionLevel.ServerModerator)
                    .Do(async e => await e.Server.Leave());

                group.CreateCommand("cleanmsg")
                    .Description("Removes the last 100 messages sent by the bot in this channel.")
                    .MinPermissions((int) PermissionLevel.ChannelModerator)
                    .Do(async e =>
                    {
                        foreach (Message msg in (await e.Channel.DownloadMessages()).Where(m => m.IsAuthor))
                            await msg.Delete();
                    });

                group.CreateCommand("gc list")
                    .Description("Calls GC.GetTotalMemory()")
                    .Do(async e => await PrintMemUsage(e));
            });

            manager.MessageReceived += async (s, e) =>
            {
                if (!e.Channel.IsPrivate) return;

                if (e.Message.Text.StartsWith("https://discord"))
                {
                    string invite = string.Empty;
                    try
                    {
                        invite = e.Message.Text.Split(' ').FirstOrDefault();
                    }
                    catch
                    {
                    } // ignored

                    if (!string.IsNullOrEmpty(invite))
                        await DiscordUtils.JoinInvite(invite, e.Channel);
                }
            };
        }
Exemple #3
0
        private async Task Init()
        {
            Logger.Writeline("Initializing Stormbot v2");
            Logger.Writeline("Installing services... ");

            Client.AddService(new HttpService());
            Client.AddService(new ModuleService());

            DataIoService io = Client.AddService(new DataIoService());

            Client.AddService(new PastebinService());

            Client.UsingCommands(cmd =>
            {
                cmd.AllowMentionPrefix = true;
                cmd.ErrorHandler      += async(s, e) =>
                {
                    switch (e.ErrorType)
                    {
                    case CommandErrorType.Exception:
                        await
                        e.Channel.SendMessage(
                            $"{e.User.Mention} Something went wrong while processing your command! Make sure your input is in the valid format. `({e.Exception.GetType().Name})`");

                        Logger.FormattedWrite("CommandService", $"Exception on command: {e.Exception}",
                                              ConsoleColor.Yellow);
                        break;

                    case CommandErrorType.UnknownCommand:
                        await e.Channel.SendMessage($"{e.User.Mention} that command does not exist.");
                        break;

                    case CommandErrorType.BadPermissions:
                        StringBuilder builder =
                            new StringBuilder(
                                $"{e.User.Mention} you do not have sufficient permissions for that command. ");
                        if (!string.IsNullOrEmpty(e.Exception?.Message))
                        {
                            builder.AppendLine($"Error message: ```{e.Exception.Message}```");
                        }
                        await e.Channel.SendMessage(builder.ToString());
                        break;

                    case CommandErrorType.BadArgCount:
                        await
                        e.Channel.SendMessage(
                            $"{e.User.Mention} bad argument count.");
                        break;

                    case CommandErrorType.InvalidInput:
                        await e.Channel.SendMessage($"{e.User.Mention} invalid command input.");
                        break;

                    default:
                        Logger.FormattedWrite("CommandService", $"e.ErrorType ({e.ErrorType}) is not handled.",
                                              ConsoleColor.Yellow);
                        break;
                    }
                };
                cmd.PrefixChar = '}';
                cmd.HelpMode   = HelpMode.Public;
            });

            Client.UsingAudio(audio =>
            {
                audio.EnableMultiserver = true;
                audio.Mode             = AudioMode.Outgoing;
                audio.Channels         = 2;
                audio.EnableEncryption = true;
            });

            Client.UsingPermissionLevels((u, c) =>
            {
                if (u.Id == Constants.UserOwner)
                {
                    return((int)PermissionLevel.BotOwner);
                }

                if (u.Server != null)
                {
                    if (Equals(u, c.Server.Owner))
                    {
                        return((int)PermissionLevel.ServerOwner);
                    }

                    ServerPermissions serverPerms = u.ServerPermissions;
                    if (serverPerms.ManageRoles)
                    {
                        return((int)PermissionLevel.ServerAdmin);
                    }
                    if (serverPerms.ManageMessages && serverPerms.KickMembers && serverPerms.BanMembers)
                    {
                        return((int)PermissionLevel.ServerModerator);
                    }

                    ChannelPermissions channelPerms = u.GetPermissions(c);
                    if (channelPerms.ManagePermissions)
                    {
                        return((int)PermissionLevel.ChannelAdmin);
                    }
                    if (channelPerms.ManageMessages)
                    {
                        return((int)PermissionLevel.ChannelModerator);
                    }
                }

                return((int)PermissionLevel.User);
            });

            Client.UsingDynamicPerms();

            Logger.Writeline("Connecting to Discord... ");
            await Client.Connect(_email, _password);

            Logger.Writeline("Installing modules... ");

            Client.AddModule <BotManagementModule>("Bot", ModuleFilter.ServerWhitelist | ModuleFilter.ChannelWhitelist | ModuleFilter.AlwaysAllowPrivate);
            Client.AddModule <ServerManagementModule>("Server Management", ModuleFilter.ServerWhitelist | ModuleFilter.ChannelWhitelist);
            Client.AddModule <AudioStreamModule>("Audio", ModuleFilter.ServerWhitelist | ModuleFilter.ChannelWhitelist);
            Client.AddModule <QualityOfLifeModule>("QoL", ModuleFilter.ServerWhitelist | ModuleFilter.ChannelWhitelist);
            Client.AddModule <TestModule>("Test", ModuleFilter.ServerWhitelist | ModuleFilter.ChannelWhitelist);
            Client.AddModule <InfoModule>("Information", ModuleFilter.ServerWhitelist | ModuleFilter.ChannelWhitelist | ModuleFilter.AlwaysAllowPrivate);
            Client.AddModule <ModulesModule>("Modules");
            Client.AddModule <ExecuteModule>("Execute", ModuleFilter.AlwaysAllowPrivate);
            Client.AddModule <TerrariaRelayModule>("Terraria Relay", ModuleFilter.ChannelWhitelist | ModuleFilter.ServerWhitelist);
            Client.AddModule <TwitchRelayModule>("Twitch Relay", ModuleFilter.ChannelWhitelist | ModuleFilter.ServerWhitelist);
            Client.AddModule <TwitchEmoteModule>("Twitch Emotes", ModuleFilter.ServerWhitelist | ModuleFilter.ChannelWhitelist);
            Client.AddModule <AnnouncementModule>("Announcements", ModuleFilter.ServerWhitelist);
            Client.AddModule <VermintideModule>("Vermintide", ModuleFilter.ServerWhitelist | ModuleFilter.ChannelWhitelist | ModuleFilter.AlwaysAllowPrivate);
            Client.AddModule <PersonalModule>("Personal", ModuleFilter.ServerWhitelist);
#if RELEASE
            await DiscordUtils.GenerateCommandMarkdown(Client);
#endif
            Client.Log.Message += (sender, args) =>
            {
                if (_ignoredLogs.Contains(args.Severity))
                {
                    return;
                }

                Logger.FormattedWrite($"{args.Severity} {args.Source}", $"{args.Message}", _colorMap[args.Severity]);

                if (args.Exception != null)
                {
                    Logger.Write($"Exception: {args.Exception}");
                }
            };

            Logger.Writeline("Loading data... ");
            io.Load();

            Client.SetGame("}help for commands");
            Config.Owner = Client.GetUser(Constants.UserOwner);

            Logger.Writeline($" -WE ARE LIVE-{Environment.NewLine}");
        }