Exemple #1
0
        public Bot(BotConfig botConfig, DBConfig dBConfig)
        {
            DiscordConfiguration discordConfiguration = new DiscordConfiguration
            {
                Token                 = botConfig.Token,
                TokenType             = TokenType.Bot,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true,
                ShardCount            = 1,
                ShardId               = 0
            };
            ServiceProvider deps = new ServiceCollection()
                                   .AddSingleton(httpClient)
                                   .AddSingleton(utility)
                                   .AddSingleton(new WeebShAPIClient(botConfig.WeebSHToken, httpClient))
                                   .AddDbContext <LanguageManager>(x => x.UseNpgsql(dBConfig.ConnString), ServiceLifetime.Transient)
                                   .AddDbContext <UserManager>(x => x.UseNpgsql(dBConfig.ConnString), ServiceLifetime.Transient)
                                   .BuildServiceProvider();
            CommandsNextConfiguration commandsNextConfiguration = new CommandsNextConfiguration
            {
                StringPrefixes = new [] { botConfig.BetaPrefix },
                Services       = deps
            };
            InteractivityConfiguration interactivityConfiguration = new InteractivityConfiguration
            {
                PaginationBehaviour = PaginationBehaviour.WrapAround,
                PaginationDeletion  = PaginationDeletion.DeleteEmojis,
                PollBehaviour       = PollBehaviour.DeleteEmojis
            };
            VoiceNextConfiguration voiceNextConfiguration = new VoiceNextConfiguration
            {
                AudioFormat = AudioFormat.Default
            };

            this.discordClient                = new DiscordClient(discordConfiguration);
            this.commandsNextExtension        = this.discordClient.UseCommandsNext(commandsNextConfiguration);
            this.interactivityExtension       = this.discordClient.UseInteractivity(interactivityConfiguration);
            this.voiceNextExtension           = this.discordClient.UseVoiceNext(voiceNextConfiguration);
            this.discordClient.ClientErrored += e =>
            {;
             Console.WriteLine("Client Error:");
             Console.WriteLine(e.EventName);
             Console.WriteLine(e.Exception);
             return(Task.CompletedTask); };
            this.discordClient.SocketErrored += e =>
            {
                Console.WriteLine("Socket Error:");
                Console.WriteLine(e.Exception);
                return(Task.CompletedTask);
            };
            this.discordClient.GuildDownloadCompleted += e =>
            {
                this.commandsNextExtension.RegisterCommands <Dev>();
                foreach (var f in Directory.EnumerateFiles(@"Commands\\"))
                {
                    using (ZipFile zip = ZipFile.Read(@$ "{f}"))
                    {
                        var dll           = zip.First(x => x.FileName.EndsWith(".dll"));
                        var splitFileName = dll.FileName.Split('.');
                        var group         = splitFileName[^ 2];
Exemple #2
0
        public void Initialize()
        {
            var config = new DiscordConfiguration()
            {
                Token                 = _appSettings.Keys.Discord,
                TokenType             = TokenType.Bot,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            var vnConfig = new VoiceNextConfiguration()
            {
                VoiceApplication = VoiceApplication.Music,
                EnableIncoming   = false
            };


            Client = new DiscordClient(config);
            Client.UseVoiceNext(vnConfig);

            Client.SetWebSocketClient <WebSocket4NetCoreClient>();
            Client.Ready          += ClientOnReady;
            Client.GuildAvailable += ClientOnGuildAvailable;
            Client.SocketOpened   += ClientOnSocketOpened;
            Client.ClientErrored  += ClientOnClientErrored;
            Client.MessageCreated += ClientOnMessageCreated;
            Client.MessageUpdated += ClientOnMessageUpdated;
            Client.SocketClosed   += ClientOnSocketClosed;
        }
        /// <summary>
        /// Creates a new instance of <see cref="VoiceNextConfiguration"/>, copying the properties of another configuration.
        /// </summary>
        /// <param name="other">Configuration the properties of which are to be copied.</param>
        public VoiceNextConfiguration(VoiceNextConfiguration other)
        {
            this.AudioFormat = new AudioFormat(other.AudioFormat.SampleRate, other.AudioFormat.ChannelCount, other.AudioFormat.VoiceApplication);
#if !NETSTANDARD1_1
            this.EnableIncoming = other.EnableIncoming;
#endif
        }
Exemple #4
0
        static async Task MainAsync(string[] args)
        {
            discord = new DiscordClient(new DiscordConfiguration
            {
                Token     = DiscordoBotToken.myBotToken,
                TokenType = TokenType.Bot
            });

            commands = discord.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefix = "!"
            });

            commands.RegisterCommands <DiscordoCommands>();

            VoiceNextConfiguration vNextConfiguration = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceApplication.Music
            };

            voiceNextClient = discord.UseVoiceNext(vNextConfiguration);

            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
Exemple #5
0
        public JosephineBot(JosephineConfig cfg, int shardid)
        {
            Config = cfg;

            var dcfg = new DiscordConfiguration
            {
                AutoReconnect         = true,
                LargeThreshold        = 250,
                LogLevel              = LogLevel.Debug,
                Token                 = Config.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = false,
                ShardId               = shardid,
                ShardCount            = Config.ShardCount,
                MessageCacheSize      = 2048,
                DateTimeFormat        = "dd-MM-yyyy HH:mm:ss zzz"
            };

            debugMode = Config.debug;
            Discord   = new DiscordClient(dcfg);

            Discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageRecieved;
            Discord.Ready          += this.Client_Ready;
            Discord.ClientErrored  += this.Client_ClientError;
            Discord.GuildUpdated   += this.Discord_GuildUpdated;
            Discord.ChannelDeleted += this.Discord_ChannelDeleted;
            Discord.MessageCreated += this.Client_Chat;
            Discord.MessageUpdated += this.MessageUpdated;
            //Discord.GuildMemberAdded += this.Join_Chat;

            var vcfg = new VoiceNextConfiguration
            {
                AudioFormat    = AudioFormat.Default,
                EnableIncoming = true
            };

            VoiceService = Discord.UseVoiceNext(vcfg);

            var depco = new ServiceCollection();

            // commandsnext config and the commandsnext service itself
            var cncfg = new CommandsNextConfiguration
            {
                StringPrefixes           = Config.CommandPrefixes,
                EnableDms                = false,
                EnableMentionPrefix      = true,
                CaseSensitive            = false,
                Services                 = depco.BuildServiceProvider(true),
                IgnoreExtraArguments     = false,
                UseDefaultCommandHandler = true,
            };

            this.CommandsNextService = Discord.UseCommandsNext(cncfg);
            this.CommandsNextService.CommandErrored  += this.CommandsNextService_CommandErrored;
            this.CommandsNextService.CommandExecuted += this.Commands_CommandExecuted;
            this.CommandsNextService.RegisterCommands(typeof(JosephineBot).GetTypeInfo().Assembly);
            this.CommandsNextService.SetHelpFormatter <HelpFormatter>();
        }
Exemple #6
0
        private void SetupVoice(DiscordClient client)
        {
            var voiceConf = new VoiceNextConfiguration
            {
                EnableIncoming = false,
                AudioFormat    = AudioFormat.Default
            };

            client.UseVoiceNext(voiceConf);
        }
Exemple #7
0
        public async Task RunAsync()
        {
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            var configJson = JsonConvert.DeserializeObject <ConfigJson>(json);


            var config = new DiscordConfiguration
            {
                Token                 = configJson.Token,
                TokenType             = TokenType.Bot,
                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true,
            };

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

            Client.UseInteractivity(new InteractivityConfiguration
            {
                Timeout = TimeSpan.FromMinutes(1)
            });


            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { configJson.Prefix },
                EnableDms           = false,
                EnableMentionPrefix = true,
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <TestCommands>();
            Commands.RegisterCommands <MusicCommands>();

            var voiceConfiguration = new VoiceNextConfiguration
            {
                //configuration of voice
            };


            Voice = Client.UseVoiceNext(voiceConfiguration);

            await Client.ConnectAsync();

            await Task.Delay(-1); //fix for premature disconnect, delays eternally
        }
Exemple #8
0
        public async Task RunAsync()
        {
            var config = new DiscordConfiguration
            {
                Token                 = "",
                TokenType             = TokenType.Bot,
                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

            Client.UseInteractivity(new InteractivityConfiguration
            {
                Timeout = TimeSpan.FromMinutes(2)
            });

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefix        = "!",
                EnableDms           = false,
                EnableMentionPrefix = true,
                EnableDefaultHelp   = false
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <AslCommands>();
            Commands.RegisterCommands <TTS>();
            Commands.RegisterCommands <BslCommands>();
            Commands.RegisterCommands <Hentai>();

            var vcfg = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceApplication.Music
            };

            this.Voice = this.Client.UseVoiceNext(vcfg);

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Exemple #9
0
        private async Task RunAsync()
        {
            var json = string.Empty;

            await using (var fs = File.OpenRead("botconfig.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            var configJson = JsonConvert.DeserializeObject <ConfigJson>(json);

            var config = new DiscordConfiguration
            {
                Token           = configJson.Token,
                TokenType       = TokenType.Bot,
                AutoReconnect   = true,
                MinimumLogLevel = LogLevel.Warning,
            };

            // Client = new DiscordShardedClient(config);
            Client = new DiscordShardedClient(config);

            Client.Ready += OnClientReady;

            var commandsConfig = new CommandsNextConfiguration
            {
                EnableMentionPrefix = true,
                EnableDms           = false,
                EnableDefaultHelp   = true
            };

            await Client.UseCommandsNextAsync(commandsConfig);

            // Commands = Client.UseCommandsNext(commandsConfig);

            var voiceConfig = new VoiceNextConfiguration
            {
                EnableIncoming = false
            };

            await Client.UseVoiceNextAsync(voiceConfig);

            await Client.StartAsync();

            // await Client.ConnectAsync();
            // await Task.Delay(-1);
        }
Exemple #10
0
        private static async Task MainAsync()
        {
            var data = new Global().DefaultDatabase();

            _yone = new DiscordClient(new DiscordConfiguration
            {
                Token                 = data.botToken,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                AutomaticGuildSync    = true,
                AutoReconnect         = true
            });
            _commands = _yone.UseCommandsNext(new CommandsNextConfiguration
            {
                PrefixResolver       = GetPrefixPositionAsync,
                EnableMentionPrefix  = true,
                EnableDms            = false,
                CaseSensitive        = false,
                IgnoreExtraArguments = true
            });
            _yone.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehavior = 0,
                PaginationTimeout  = TimeSpan.FromMinutes(5.0),
                Timeout            = TimeSpan.FromMinutes(2.0)
            });
            var msc = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceApplication.Music
            };


            var dspExtended = _yone.UseDspExtended();

            _commands.SetHelpFormatter <Help.DefaultHelpFormatter>();
            _commands.RegisterCommands(Assembly.GetExecutingAssembly());

            dspExtended.RegisterAssembly(Assembly.GetExecutingAssembly());

            _yone.UseVoiceNext(msc);
            await _yone.ConnectAsync();

            await Task.Delay(-1);
        }
Exemple #11
0
        public static async Task Login()
        {
            Utils.Log("Receiving token...", LogType.Console);
            Program.discord = new DiscordClient(new DiscordConfiguration()
            {
                //Token = DiscordLoginUtils.GetDiscordToken(),
                Token                 = "Mzc5NzUxMDc5MjAzNzAwNzQy.DScCfw.H5BHfhXw-ZwvN4DMgPTdmTRBJ_c",
                TokenType             = DSharpPlus.TokenType.Bot,
                LogLevel              = DSharpPlus.LogLevel.Debug,
                UseInternalLogHandler = true
            });
            await Program.WaitReceiveToken();

            Utils.Log("Received token.", LogType.Console);
            Program.SetupEvents();
            await Onno204Bot.Events.Events.RegisterEvent();

            Utils.Log("Setting up commands...", LogType.Console);
            Program.commands = Program.discord.UseCommandsNext(new CommandsNextConfiguration()
            {
                StringPrefix      = Config.CommandString,
                CaseSensitive     = false,
                EnableDefaultHelp = true
            });
            Program.commands.RegisterCommands <Commands>();
            Program.commands.CommandExecuted += new AsyncEventHandler <CommandExecutionEventArgs>(CommandsEvents.Commands_CommandExecuted);
            Utils.Log("Done Setting up commands.", LogType.Console);
            Utils.Log("Setting up Voice...", LogType.Console);
            VoiceNextConfiguration vcfg = new VoiceNextConfiguration()
            {
                EnableIncoming   = true,
                VoiceApplication = VoiceApplication.Voice
            };

            Program.Voice = Program.discord.UseVoiceNext(vcfg);
            Utils.Log("Done Setting up Voice.", LogType.Console);
            Utils.Log("Loggin in...", LogType.Console);
            await Program.discord.ConnectAsync();

            Utils.Log("Logged in.", LogType.Console);
            await Task.Delay(-1);
        }
Exemple #12
0
 public Bot_Base(string serverName, DiscordConfiguration dsConfig, bool autostart = false)
 {
     try {
         ServerName = serverName;
         Client     = new DiscordClient(dsConfig);
         var ccfg = new CommandsNextConfiguration {
             StringPrefix        = SettingsHelper.GetValue("Prefix"),
             EnableDms           = false,
             EnableMentionPrefix = false
         };
         var vcfg = new VoiceNextConfiguration {
             VoiceApplication = VoiceApplication.Music,
             EnableIncoming   = true
         };
         AppState.CommandsNextModule = Client.UseCommandsNext(ccfg);
         AppState.CommandsNextModule.RegisterCommands <InternalCommands>();
         AssemblyHelper.GetAssemblies().ForEach(o => AppState.CommandsNextModule.RegisterCommands(o));
         AppState.VoiceNextClient = Client.UseVoiceNext(vcfg);
     } catch (Exception ex) {
         AppState.Logger.WriteLog(Enums.Enums.LogLevel.FATAL, "Could not start Service", ex);
     }
 }
Exemple #13
0
        public TestBot(TestBotConfig cfg, int shardid)
        {
            // global bot config
            this.Config = cfg;

            // discord instance config and the instance itself
            var dcfg = new DiscordConfiguration
            {
                AutoReconnect         = true,
                LargeThreshold        = 250,
                LogLevel              = LogLevel.Debug,
                Token                 = this.Config.Token,
                TokenType             = this.Config.UseUserToken ? TokenType.User : TokenType.Bot,
                UseInternalLogHandler = false,
                ShardId               = shardid,
                ShardCount            = this.Config.ShardCount,
                //GatewayCompressionLevel = GatewayCompressionLevel.Stream,
                MessageCacheSize   = 2048,
                AutomaticGuildSync = !this.Config.UseUserToken,
                DateTimeFormat     = "dd-MM-yyyy HH:mm:ss zzz"
            };

            Discord = new DiscordClient(dcfg);

            // events
            Discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageReceived;
            Discord.Ready                  += this.Discord_Ready;
            Discord.GuildAvailable         += this.Discord_GuildAvailable;
            Discord.ClientErrored          += this.Discord_ClientErrored;
            Discord.SocketErrored          += this.Discord_SocketError;
            Discord.GuildCreated           += this.Discord_GuildCreated;
            Discord.VoiceStateUpdated      += this.Discord_VoiceStateUpdated;
            Discord.GuildDownloadCompleted += this.Discord_GuildDownloadCompleted;
            Discord.GuildUpdated           += this.Discord_GuildUpdated;
            Discord.ChannelDeleted         += this.Discord_ChannelDeleted;

            // voice config and the voice service itself
            var vcfg = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceNext.Codec.VoiceApplication.Music,
                EnableIncoming   = false
            };

            this.VoiceService = this.Discord.UseVoiceNext(vcfg);

            // build a dependency collection for commandsnext
            var depco = new ServiceCollection()
                        .AddSingleton(new TestBotService())
                        .AddScoped <TestBotScopedService>();

            // commandsnext config and the commandsnext service itself
            var cncfg = new CommandsNextConfiguration
            {
                StringPrefixes = this.Config.CommandPrefixes,
                //PrefixResolver = msg =>
                //{
                //    if (TestBotCommands.PrefixSettings.ContainsKey(msg.Channel.Id) && TestBotCommands.PrefixSettings.TryGetValue(msg.Channel.Id, out var pfix))
                //        return Task.FromResult(msg.GetStringPrefixLength(pfix));
                //    return Task.FromResult(-1);
                //},
                EnableDms                = true,
                EnableMentionPrefix      = true,
                CaseSensitive            = false,
                Services                 = depco.BuildServiceProvider(true),
                IgnoreExtraArguments     = false,
                UseDefaultCommandHandler = true,
                //DefaultHelpChecks = new List<CheckBaseAttribute>() { new RequireOwnerAttribute() }
            };

            this.CommandsNextService = Discord.UseCommandsNext(cncfg);
            this.CommandsNextService.CommandErrored  += this.CommandsNextService_CommandErrored;
            this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted;
            this.CommandsNextService.RegisterCommands(typeof(TestBot).GetTypeInfo().Assembly);
            this.CommandsNextService.SetHelpFormatter <TestBotHelpFormatter>();

            // hook command handler
            //this.Discord.MessageCreated += this.Discord_MessageCreated;

            // interactivity service
            var icfg = new InteractivityConfiguration()
            {
                PaginationBehavior = TimeoutBehaviour.DeleteMessage,
                PaginationTimeout  = TimeSpan.FromSeconds(30),
                Timeout            = TimeSpan.FromSeconds(30)
            };

            this.InteractivityService = Discord.UseInteractivity(icfg);
            this.LavalinkService      = Discord.UseLavalink();
        }
Exemple #14
0
        public TestBot(TestBotConfig cfg, int shardid)
        {
            // global bot config
            this.Config = cfg;

            // discord instance config and the instance itself
            var dcfg = new DiscordConfiguration
            {
                AutoReconnect         = true,
                LargeThreshold        = 250,
                LogLevel              = LogLevel.Debug,
                Token                 = this.Config.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = false,
                ShardId               = shardid,
                ShardCount            = this.Config.ShardCount,
                MessageCacheSize      = 2048,
                DateTimeFormat        = "dd-MM-yyyy HH:mm:ss zzz"
            };

            Discord = new DiscordClient(dcfg);

            // events
            Discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageReceived;
            Discord.Ready                  += this.Discord_Ready;
            Discord.GuildAvailable         += this.Discord_GuildAvailable;
            Discord.ClientErrored          += this.Discord_ClientErrored;
            Discord.SocketErrored          += this.Discord_SocketError;
            Discord.GuildCreated           += this.Discord_GuildCreated;
            Discord.VoiceStateUpdated      += this.Discord_VoiceStateUpdated;
            Discord.GuildDownloadCompleted += this.Discord_GuildDownloadCompleted;
            Discord.GuildUpdated           += this.Discord_GuildUpdated;
            Discord.ChannelDeleted         += this.Discord_ChannelDeleted;

            // voice config and the voice service itself
            var vcfg = new VoiceNextConfiguration
            {
                AudioFormat    = AudioFormat.Default,
                EnableIncoming = true
            };

            this.VoiceService = this.Discord.UseVoiceNext(vcfg);

            // build a dependency collection for commandsnext
            var depco = new ServiceCollection();

            // commandsnext config and the commandsnext service itself
            var cncfg = new CommandsNextConfiguration
            {
                StringPrefixes           = this.Config.CommandPrefixes,
                EnableDms                = true,
                EnableMentionPrefix      = true,
                CaseSensitive            = false,
                Services                 = depco.BuildServiceProvider(true),
                IgnoreExtraArguments     = false,
                UseDefaultCommandHandler = true,
            };

            this.CommandsNextService = Discord.UseCommandsNext(cncfg);
            this.CommandsNextService.CommandErrored  += this.CommandsNextService_CommandErrored;
            this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted;
            this.CommandsNextService.RegisterCommands(typeof(TestBot).GetTypeInfo().Assembly);
            this.CommandsNextService.SetHelpFormatter <TestBotHelpFormatter>();

            // interactivity service
            var icfg = new InteractivityConfiguration()
            {
                Timeout = TimeSpan.FromSeconds(3)
            };

            this.InteractivityService = Discord.UseInteractivity(icfg);
            this.LavalinkService      = Discord.UseLavalink();
        }
Exemple #15
0
        public static void addcommands(DiscordClient p_discord)
        {
            p_discord.UseCommands(new CommandConfig
            {
                Prefix  = "!",
                SelfBot = false,
            });
            UserRepository    userrepo = new UserRepository(new UserSQLContext());
            MessageRepository msgrepo  = new MessageRepository(new MessageSQLContext());

            p_discord.AddCommand("hello", async e =>
            {
                string[] msg = e.Message.Content.Split(' ');

                //if msg array contains more then 1 arrayobject then..
                if (msg.Length > 1 && msg[1].Length >= 3)

                {
                    bool ChannelContainsUser   = false;
                    List <DiscordUser> members = new List <DiscordUser>();
                    //check if member is in the current 'guild'
                    foreach (DiscordMember dm in e.Guild.Members)
                    {
                        //check if msg[1] containst a part of the user
                        if (dm.User.Username.ToUpper().Contains(msg[1].ToUpper()))
                        {
                            if (dm.User.Username.ToUpper() == msg[1].ToUpper())
                            {
                                ChannelContainsUser = true;
                                await e.Message.Respond($"{e.Message.Author.Username } says hello to <@{dm.User.ID}> ");
                                break;
                            }
                            members.Add(dm.User);
                        }
                        if (members.Count > 1 && !ChannelContainsUser)
                        {
                            await e.Message.Respond($"more then 1 user with those characters in his name");
                            ChannelContainsUser = true;
                            break;
                        }
                    }
                    if (members.Count == 1)
                    {
                        ChannelContainsUser = true;
                        await e.Message.Respond($"{e.Message.Author.Username } says hello to <@{members[0].ID}> ");
                    }
                    else if (!ChannelContainsUser)
                    {
                        await e.Message.Respond("That user is not in the current channel");
                    }
                }
                else
                {
                    await e.Message.Respond($"Hello, {e.Message.Author.Mention}!");
                }
            });
            p_discord.AddCommand("reken", async e =>
            {
                string[] msg = e.Message.Content.Split(' ');
                try
                {
                    double num1 = Convert.ToDouble(msg[1]);
                    double num2 = Convert.ToDouble(msg[3]);
                    double num3 = 1;
                    if (msg.Length > 4)
                    {
                        num3 = Convert.ToDouble(msg[4]);
                    }

                    switch (msg[2])
                    {
                    case "+":
                        await e.Message.Respond(num1.ToString() + msg[2] + num2.ToString() + '=' + (num1 + num2).ToString());
                        break;

                    case "-":
                        await e.Message.Respond(num1.ToString() + msg[2] + num2.ToString() + '=' + (num1 - num2).ToString());
                        break;

                    case "*":
                    case "x":
                        await e.Message.Respond(num1.ToString() + msg[2] + num2.ToString() + '=' + (num1 * num2).ToString());
                        break;

                    case "/":
                        await e.Message.Respond(num1.ToString() + msg[2] + num2.ToString() + '=' + (num1 / num2).ToString());
                        break;

                    case "**":
                    case "^":
                        await e.Message.Respond(num1.ToString() + msg[2] + num2.ToString() + '=' + Math.Pow(num1, num2).ToString());
                        break;

                    case "^^":
                        await e.Message.Respond(num1.ToString() + msg[2] + num2.ToString() + '=' + Math.Pow(Math.Pow(num1, num2), num3).ToString());
                        break;

                    case "%":
                        await e.Message.Respond(num1.ToString() + msg[2] + num2.ToString() + '=' + (num1 % num2).ToString());
                        break;

                    case ">":
                    case "<":
                    case "==":
                    case "!=":
                        await e.Message.Respond(msg[1] + " " + msg[2] + " " + msg[3] + " " + "= " + Operator(msg[2], num1, num2).ToString());
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception exc)
                {
                    await e.Message.Respond(exc.Message);
                }
            });
            p_discord.AddCommand("join", async e =>
            {
                try
                {
                    var vcfg = new VoiceNextConfiguration
                    {
                        VoiceApplication = DSharpPlus.VoiceNext.Codec.VoiceApplication.Music
                    };
                    VoiceService = p_discord.UseVoiceNext(vcfg);

                    await VoiceService.ConnectAsync(await p_discord.GetChannelByID(272324215439491072));
                    Console.WriteLine("Joined voice channel");
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.Message);
                }
            });
            p_discord.AddCommand("dc", async e =>
            {
                try
                {
                    DiscordGuild guild = await p_discord.GetGuild(e.Channel.GuildID);

                    VoiceService.GetConnection(guild).Disconnect();
                    VoiceService.GetConnection(guild).Dispose();
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.Message);
                }
            });
            p_discord.AddCommand("god", async e =>
            {
                if (e.Message.Author.ID == 261216517910167554)
                {
                    await e.Message.Respond("AND THE REAL C#GOD IS....\n" + e.Message.Author.Username);
                }
                else
                {
                    await e.Message.Respond("you're not teh real c#god.");
                }
            });
            p_discord.AddCommand("kkk", async e =>
            {
                await e.Message.Respond($"WHITE POWER, RIGHT { e.Message.Author.Username }?");
            });
            p_discord.AddCommand("help", async e =>
            {
                string prefix = "!";
                await e.Message.Respond($"currently available commands are: \n{prefix}hello <username> \n{prefix}reken 'nummer' 'operator' 'nummer' \n{prefix}god to see if you are a c# god\n{prefix}karma @username to give a user karma!\n" +
                                        $"{prefix}dice 'minimumnumber' 'maximumnumber' (without the quotes) to generate a random number. {prefix}dice will automatically pick a number between 1 and 100.\n" +
                                        $"\n\nThis bot also functions as Robot9000. This means that the bot will mute you if you post duplicate content that already has been posted in this server.\n" +
                                        "The amount of time you get muted depends on the amount of punishments you already had.");
            });
            p_discord.AddCommand("666", async e =>
            {
                await e.Message.Respond("HAIL SATAN " + e.Message.Author.Username);
            });
            p_discord.AddCommand("blm", async e =>
            {
                await e.Message.Respond("BLACK HAS NO POWER, RIGHT " + e.Message.Author.Username + "?");
            });
            p_discord.AddCommand("play", async e =>
            {
                try
                {
                    DiscordGuild guild = await p_discord.GetGuild(e.Channel.GuildID);
                    var rand           = new Random();
                    var bytes          = new byte[32000];
                    rand.NextBytes(bytes);

                    await VoiceService.GetConnection(guild).SendAsync(bytes, 517, 16);
                    Console.Write("i just played something!");
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.Message);
                }
            });
            p_discord.AddCommand("karma", async e =>
            {
                string[] msg             = e.Message.Content.Split(' ');
                List <DiscordUser> users = e.Message.Mentions;
                if (users.Count == 1)
                {
                    if (users[0].ID != e.Message.Author.ID)
                    {
                        int karma = AddKarma(users[0].ID);
                        await e.Message.Respond($"{users[0].Username} gained 1 karma!\n{users[0].Username} now has {karma} karma");
                    }
                    else
                    {
                        await e.Message.Respond($"You just lost 1 karma");
                    }
                }
                else if (users.Count > 1)
                {
                    await e.Message.Respond($"Please only mention 1 user :)");
                }
                else
                {
                    await e.Message.Respond($"You have to at least mention 1 user");
                }
            });
            p_discord.AddCommand("dice", async e =>
            {
                string[] msg = e.Message.Content.Split(' ');
                if (msg.Length > 1)
                {
                    int random = Dice(Convert.ToInt32(msg[1]), Convert.ToInt32(msg[2]));
                    await e.Message.Respond(random.ToString());
                }
                else if (msg.Length == 1)
                {
                    int random = Dice(1, 101);
                    await e.Message.Respond(random.ToString());
                }
                else
                {
                    await e.Message.Respond("Please use 2 parameters divided by a space");
                }
            });
            p_discord.AddCommand("unmute", async e =>
            {
                await Task.Delay(0);
                if (e.Message.Author.ID == 261216517910167554 || e.Message.Author.ID == 239471183475638272)
                {
                    if (e.Message.Mentions.Count > 0)
                    {
                        foreach (DiscordUser user in e.Message.Mentions)
                        {
                            new UserRepository(new UserSQLContext()).Unmute(user.ID);
                            await e.Message.Respond($"{e.Message.Author.Username } unmuted <@{user.ID}> ");
                        }
                    }
                    else
                    {
                        await e.Message.Respond($"Please mention the user(s) you want to unmute!");
                    }
                }
                else
                {
                    await e.Message.Respond($"You ar not permitted to unmute users!");
                }
            });
            p_discord.AddCommand("mutereset", async e =>
            {
                if (e.Message.Author.ID == 261216517910167554 || e.Message.Author.ID == 239471183475638272)
                {
                    if (userrepo.MuteCountreset())
                    {
                        userrepo.MuteReset();
                        await e.Message.Respond("Robot9000 mutes have been reset!");
                    }
                    else
                    {
                        await e.Message.Respond("Oops! looks like something went wrong. Please contact Mivo90");
                    }
                }
                else
                {
                    await e.Message.Respond("I'm sorry, I can not let you do that.");
                }
            });
            p_discord.AddCommand("messagereset", async e =>
            {
                if (e.Message.Author.ID == 261216517910167554 || e.Message.Author.ID == 239471183475638272)
                {
                    if (msgrepo.ResetMessages())
                    {
                        await e.Message.Respond("Robot9000 messages have been reset!");
                    }
                    else
                    {
                        await e.Message.Respond("Oops, couldn't reset the messages. Please contact Mivo90");
                    }
                }
                else
                {
                    await e.Message.Respond("Nice try.");
                }
            });
        }
Exemple #16
0
        public TestBot(TestBotConfig cfg, int shardid)
        {
            // global bot config
            this.Config = cfg;

            // discord instance config and the instance itself
            var dcfg = new DiscordConfiguration
            {
                AutoReconnect      = true,
                LargeThreshold     = 250,
                MinimumLogLevel    = LogLevel.Debug,
                Token              = this.Config.Token,
                TokenType          = TokenType.Bot,
                ShardId            = shardid,
                ShardCount         = this.Config.ShardCount,
                MessageCacheSize   = 2048,
                LogTimestampFormat = "dd-MM-yyyy HH:mm:ss zzz",
                Intents            = DiscordIntents.All // if 4013 is received, change to DiscordIntents.AllUnprivileged
            };

            Discord = new DiscordClient(dcfg);

            // events
            Discord.Ready           += this.Discord_Ready;
            Discord.GuildAvailable  += this.Discord_GuildAvailable;
            Discord.PresenceUpdated += this.Discord_PresenceUpdated;
            //Discord.ClientErrored += this.Discord_ClientErrored;
            Discord.SocketErrored          += this.Discord_SocketError;
            Discord.GuildCreated           += this.Discord_GuildCreated;
            Discord.VoiceStateUpdated      += this.Discord_VoiceStateUpdated;
            Discord.GuildDownloadCompleted += this.Discord_GuildDownloadCompleted;
            Discord.GuildUpdated           += this.Discord_GuildUpdated;
            Discord.ChannelDeleted         += this.Discord_ChannelDeleted;

            // For event timeout testing
            //Discord.GuildDownloadCompleted += async (s, e) =>
            //{
            //    await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
            //    throw new Exception("Flippin' tables");
            //};

            // voice config and the voice service itself
            var vcfg = new VoiceNextConfiguration
            {
                AudioFormat    = AudioFormat.Default,
                EnableIncoming = true
            };

            this.VoiceService = this.Discord.UseVoiceNext(vcfg);

            // build a dependency collection for commandsnext
            var depco = new ServiceCollection();

            // commandsnext config and the commandsnext service itself
            var cncfg = new CommandsNextConfiguration
            {
                StringPrefixes           = this.Config.CommandPrefixes,
                EnableDms                = true,
                EnableMentionPrefix      = true,
                CaseSensitive            = false,
                Services                 = depco.BuildServiceProvider(true),
                IgnoreExtraArguments     = false,
                UseDefaultCommandHandler = true,
            };

            this.CommandsNextService = Discord.UseCommandsNext(cncfg);
            this.CommandsNextService.CommandErrored  += this.CommandsNextService_CommandErrored;
            this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted;
            this.CommandsNextService.RegisterCommands(typeof(TestBot).GetTypeInfo().Assembly);
            this.CommandsNextService.SetHelpFormatter <TestBotHelpFormatter>();

            // interactivity service
            var icfg = new InteractivityConfiguration()
            {
                Timeout = TimeSpan.FromSeconds(3)
            };

            this.InteractivityService = Discord.UseInteractivity(icfg);
            this.LavalinkService      = Discord.UseLavalink();

            //this.Discord.MessageCreated += async e =>
            //{
            //    if (e.Message.Author.IsBot)
            //        return;

            //    _ = Task.Run(async () => await e.Message.RespondAsync(e.Message.Content)).ConfigureAwait(false);
            //};
        }
Exemple #17
0
        public async Task RunBotAsync()
        {
            var cfg = new DiscordConfiguration
            {
                Token     = "NTI4OTQ3OTA1ODYwNDY4NzU1.DxEuvw.B9u9nu-pNC5G3xrqgcXfbPIeg9E",
                TokenType = TokenType.Bot,

                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            // then we want to instantiate our client
            this.Client = new DiscordClient(cfg);
            // If you are on Windows 7 and using .NETFX, install
            // DSharpPlus.WebSocket.WebSocket4Net from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            //this.Client.SetWebSocketClient<WebSocket4NetClient>();

            // If you are on Windows 7 and using .NET Core, install
            // DSharpPlus.WebSocket.WebSocket4NetCore from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            //this.Client.SetWebSocketClient<WebSocket4NetCoreClient>();

            // If you are using Mono, install
            // DSharpPlus.WebSocket.WebSocketSharp from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            //this.Client.SetWebSocketClient<WebSocketSharpClient>();

            // if using any alternate socket client implementations,
            // remember to add the following to the top of this file:
            //using DSharpPlus.Net.WebSocket;

            // next, let's hook some events, so we know
            // what's going on
            this.Client.Ready          += this.Client_Ready;
            this.Client.GuildAvailable += this.Client_GuildAvailable;
            this.Client.ClientErrored  += this.Client_ClientError;

            // up next, let's set up our commands
            var ccfg = new CommandsNextConfiguration
            {
                // let's use the string prefix defined in config.json
                StringPrefix = "!",

                // enable responding in direct messages
                EnableDms = true,

                // enable mentioning the bot as a command prefix
                EnableMentionPrefix = true
            };

            // and hook them up
            this.Commands = this.Client.UseCommandsNext(ccfg);

            // let's hook some command events, so we know what's
            // going on
            this.Commands.CommandExecuted += this.Commands_CommandExecuted;
            this.Commands.CommandErrored  += this.Commands_CommandErrored;
            this.Client.MessageCreated    += this.Handle_Message;
            // up next, let's register our commands
            // but with Reflection \^^/
            //i added a comment
            foreach (var item in Assembly.GetExecutingAssembly().GetTypes().Where(x => x.GetInterfaces().Contains(typeof(IWillCommand))))
            {
                var methodtoInvoke = typeof(CommandsNextModule).GetMethod("RegisterCommands", Type.EmptyTypes);
                var method         = methodtoInvoke.MakeGenericMethod(item);
                method.Invoke(this.Commands, null);
            }

            // let's set up voice
            var vcfg = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceApplication.Music
            };

            // and let's enable it
            this.Voice = this.Client.UseVoiceNext(vcfg);

            // finally, let's connect and log in
            await this.Client.ConnectAsync();

            // for this example you will need to read the
            // VoiceNext setup guide, and include ffmpeg.

            // and this is to prevent premature quitting
            await Task.Delay(-1);
        }
Exemple #18
0
        private async Task MainAsync()
        {
            // getting versions and assembly info
            SetBotVersionInfo();

            // init log channels
            _logChannels    = new List <DiscordChannel>();
            _lastLogChWrite = File.GetLastWriteTime("logchannels.txt");

            string json = await FileHandler.ReadJsonConfig();

            if (json.Length == 0)
            {
                return;
            }
            if (json == "default")
            {
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("Created default config file.\n" +
                                  "Now you need to get your discord bot token " +
                                  "and put it in config.json file.\n" +
                                  "Also make sure you set other parameters.");
                Console.ResetColor();
                return;
            }

            // setting up client
            var cfgjson = JsonSerializer.Deserialize <ConfigJson>(json);

            if (cfgjson == null)
            {
                return;
            }
            var cfg = new DiscordConfiguration
            {
                Token              = cfgjson.Token,
                TokenType          = TokenType.Bot,
                AutoReconnect      = true,
                MinimumLogLevel    = RuntimeInfo == "Debug" ? LogLevel.Debug : LogLevel.Information,
                MessageCacheSize   = 2048,
                LogTimestampFormat = "dd-MM-yyyy HH:mm:ss zzz"
            };

            // client init and event hooks
            _discord                         = new DiscordClient(cfg);
            _discord.Ready                  += Discord_Ready;
            _discord.GuildAvailable         += Discord_GuildAvailable;
            _discord.GuildUnavailable       += Discord_GuildUnavailable;
            _discord.GuildCreated           += Discord_GuildCreated;
            _discord.GuildDeleted           += Discord_GuildDeleted;
            _discord.ChannelDeleted         += Discord_ChannelDeleted;
            _discord.DmChannelDeleted       += Discord_DmChannelDeleted;
            _discord.GuildDownloadCompleted += Discord_GuildDownloadCompleted;
            _discord.ClientErrored          += Discord_ClientErrored;
            _discord.SocketClosed           += Discord_SocketClosed;
            _discord.Resumed                += Discord_Resumed;
            _discord.Heartbeated            += Discord_Heartbeated;

            // setting up interactivity
            var intcfg = new InteractivityConfiguration
            {
                Timeout            = TimeSpan.FromMinutes(cfgjson.ActTimeout),
                PaginationDeletion = PaginationDeletion.DeleteMessage,
                PollBehaviour      = PollBehaviour.KeepEmojis
            };

            _discord.UseInteractivity(intcfg);

            // setting up commands
            var cmdcfg = new CommandsNextConfiguration
            {
                StringPrefixes = new List <string> {
                    cfgjson.CommandPrefix
                },
                EnableDms           = cfgjson.DmsEnabled,
                EnableMentionPrefix = cfgjson.MentionEnabled,
                CaseSensitive       = cfgjson.CaseSensitive,
                EnableDefaultHelp   = true
            };

            // commands hooks and register
            _commands = _discord.UseCommandsNext(cmdcfg);
            _commands.CommandExecuted += Commands_CommandExecuted;
            _commands.CommandErrored  += Commands_CommandErrored;
            _commands.RegisterCommands <Commands.Commands>();
            _commands.RegisterCommands <LeetCommands>();
            _commands.RegisterCommands <Interactivities.Interactivities>();
            _commands.RegisterCommands <Administrative>();
            _commands.RegisterCommands <Cats>();
            _commands.RegisterCommands <DiceRolling>();
            _commands.RegisterCommands <CryptoAes>();
            _commands.RegisterCommands <CryptoRsa>();
            _commands.RegisterCommands <MathCommands>();
            _commands.RegisterCommands <StatusCommands>();
            _commands.RegisterCommands <VoiceCommands>();
            // adding math converter for custom type and name
            var mathopscvrt = new MathOperationConverter();

            _commands.RegisterConverter(mathopscvrt);
            _commands.RegisterUserFriendlyTypeName <MathOperation>("operator");

            // setting up and enabling voice
            var vcfg = new VoiceNextConfiguration
            {
                AudioFormat    = AudioFormat.Default,
                EnableIncoming = false
            };

            _discord.UseVoiceNext(vcfg);

            // setting custom help formatter
            _commands.SetHelpFormatter <HelpFormatter>();

            // init twitch live and youtube video monitors
            _ttvApIclid   = cfgjson.TwitchApiClid;
            _ttvApIsecret = cfgjson.TwitchApiSecret;
            _ytApIkey     = cfgjson.YoutubeApiKey;
            _tlm          = new TwitchLiveMonitor();
            _yvm          = new YoutubeVideoMonitor();

            // getting aes and rsa keys from config
            AesKey        = cfgjson.AesKey;
            AesIv         = cfgjson.AesIv;
            RsaPublicKey  = cfgjson.RsaPublicKey;
            RsaPrivateKey = cfgjson.RsaPrivateKey;

            // connecting discord
            try
            {
                await _discord.ConnectAsync();
            }
            catch (Exception e)
            {
                _discord.Logger.LogCritical($"{e.Message}");
                return;
            }

            await Task.Delay(-1);
        }
Exemple #19
0
        static async Task MainAsync(string[] args)
        {
            /*
             * var http = (HttpWebRequest)WebRequest.Create(new Uri("https://discordapp.com/api/v6/auth/login"));
             * http.Accept = "application/json";
             * http.ContentType = "application/json";
             * http.Method = "POST";
             * string parsedContent = Newtonsoft.Json.JsonSerializer.
             * ASCIIEncoding encoding = new ASCIIEncoding();
             * Byte[] bytes = encoding.GetBytes(parsedContent);
             * Stream newStream = http.GetRequestStream();
             * newStream.Write(bytes, 0, bytes.Length);
             * newStream.Close();
             * var response = http.GetResponse();
             *
             * var stream = response.GetResponseStream();
             * var srr = new StreamReader(stream);
             * var content = srr.ReadToEnd();
             *
             * using (var wb = new WebClient())
             * {
             *  var data = new NameValueCollection();
             *  data["email"] = "email";
             *  data["password"] = "******";
             *  wb.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
             *  var res = wb.UploadValues("https://discordapp.com/api/v6/auth/login", data);
             *  response = Encoding.Default.GetString(res);
             * }
             */
            var json = "";

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync();
            var cfgjson = Newtonsoft.Json.JsonConvert.DeserializeObject <ConfigJson>(json);
            var conf    = new DiscordConfiguration
            {
                //Token = cfgjson.Token,
                //TokenType = TokenType.Bot,
                Token                 = cfgjson.Token,
                TokenType             = TokenType.User,
                UseInternalLogHandler = true,
                LogLevel              = LogLevel.Debug,
                AutoReconnect         = true,
            };

            try
            {
                discord = new DiscordClient(conf);
            }
            catch (Exception e)
            {
                Console.Write(e);
            }

            var commands = discord.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefix        = cfgjson.CommandPrefix,
                EnableDms           = false,
                EnableMentionPrefix = true
            });

            var vcfg = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceApplication.Music
            };

            var voice = discord.UseVoiceNext(vcfg);


            discord.MessageCreated += async ev =>
            {
                if (checkUser(ev))
                {
                    try
                    {
                        await analyzeMessage(ev);
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex);
                    }
                }
            };


            commands.RegisterCommands <MartinCommands>();
            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
Exemple #20
0
        public async Task RunBotAsync()
        {
            // first, let's load our configuration file
            string json;

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync();

            // next, let's load the values from that file
            // to our client's configuration
            var cfgjson = JsonConvert.DeserializeObject <ConfigJson>(json);
            var cfg     = new DiscordConfiguration
            {
                Token     = cfgjson.Token,
                TokenType = TokenType.Bot,

                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            // then we want to instantiate our client
            Client = new DiscordClient(cfg);

            // If you are on Windows 7 and using .NETFX, install
            // DSharpPlus.WebSocket.WebSocket4Net from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            //this.Client.SetWebSocketClient<WebSocket4NetClient>();

            // If you are on Windows 7 and using .NET Core, install
            // DSharpPlus.WebSocket.WebSocket4NetCore from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            //this.Client.SetWebSocketClient<WebSocket4NetCoreClient>();

            // If you are using Mono, install
            // DSharpPlus.WebSocket.WebSocketSharp from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            //this.Client.SetWebSocketClient<WebSocketSharpClient>();

            // if using any alternate socket client implementations,
            // remember to add the following to the top of this file:
            //using DSharpPlus.Net.WebSocket;

            // next, let's hook some events, so we know
            // what's going on
            Client.Ready          += Client_Ready;
            Client.GuildAvailable += Client_GuildAvailable;
            Client.ClientErrored  += Client_ClientError;

            // up next, let's set up our commands
            var ccfg = new CommandsNextConfiguration
            {
                // let's use the string prefix defined in config.json
                StringPrefixes = new[] { cfgjson.CommandPrefix },

                // enable responding in direct messages
                EnableDms = true,

                // enable mentioning the bot as a command prefix
                EnableMentionPrefix = true
            };

            // and hook them up
            Commands = Client.UseCommandsNext(ccfg);

            // let's hook some command events, so we know what's
            // going on
            Commands.CommandExecuted += Commands_CommandExecuted;
            Commands.CommandErrored  += Commands_CommandErrored;

            // up next, let's register our commands
            Commands.RegisterCommands <ExampleInteractiveCommands>();

            // let's set up voice
            var vcfg = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceApplication.Music
            };

            // and let's enable it
            Voice = Client.UseVoiceNext(vcfg);

            // finally, let's connect and log in
            await Client.ConnectAsync();

            // when the bot is running, try doing <prefix>help
            // to see the list of registered commands, and
            // <prefix>help <command> to see help about specific
            // command.

            // and this is to prevent premature quitting
            await Task.Delay(-1);
        }
Exemple #21
0
        static async Task MainAsync(string[] args)
        {
            // Create service collection and configure our services
            var serviceProvider = new ServiceCollection()
                                  .AddSingleton <IKarvisConfigurationService>(new KarvisConfigurationService())
                                  .AddSingleton <IProvideAudioState>(new AudioStateProvider())
                                  .BuildServiceProvider();

            karvisConfiguration = serviceProvider.GetService <IKarvisConfigurationService>().Configuration;

            discord = new DiscordClient(new DSharpPlus.DiscordConfiguration()
            {
                Token                 = karvisConfiguration.DiscordConfiguration.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                LogLevel              = LogLevel.Debug,
                AutoReconnect         = true
            });

            var audioConfig = new VoiceNextConfiguration();

            audioConfig.AudioFormat    = new AudioFormat(48000, 2, VoiceApplication.Music);
            audioConfig.EnableIncoming = true;
            voice = discord.UseVoiceNext(audioConfig);

            discord.MessageCreated += async e =>
            {
                if (e.Message.Content.ToLower().StartsWith("ping"))
                {
                    await e.Message.RespondAsync("pong!");
                }
            };

            commands = discord.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefixes = new List <string>()
                {
                    ";;", "->"
                },
                EnableDms = false, // required for UseVoiceNext?
                Services  = serviceProvider
            });

            commands.RegisterCommands <CommandsModule>();
            commands.RegisterCommands <LavalinkCommandsModule>();
            commands.RegisterCommands <AzureCommandsModule>();
            commands.RegisterCommands <GoogleCommandsModule>();

            interactivity = discord.UseInteractivity(new InteractivityConfiguration
            {
            });

            lavalink = discord.UseLavalink();

            discord.Ready          += Client_Ready;
            discord.GuildAvailable += Client_GuildAvailable;
            discord.ClientErrored  += Client_ClientError;

            await discord.ConnectAsync();

            await Task.Delay(-1); // infinite wait to prevent exit
        }
Exemple #22
0
        public static async Task MainAsync(string[] args)
        {
            var   filePath = "./Data/Token.json";
            var   jsonData = System.IO.File.ReadAllText(filePath);
            Token _Token   = JsonConvert.DeserializeObject <Token>(jsonData);

            discord = new DiscordClient(new DiscordConfiguration
            {
                Token                 = _Token.token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                LogLevel              = LogLevel.Info
            });

            discord.MessageCreated += async e =>
            {
                if (e.Message.Content.ToLower().Equals("lemme smash"))
                {
                    await e.Message.RespondAsync("no ron");
                }
            };

            discord.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehaviour = DSharpPlus.Interactivity.Enums.PaginationBehaviour.Default,
                Timeout             = TimeSpan.FromMinutes(2)
            });

            List <string> prefixes = new List <string>()
            {
                "|"
            };

            commands = discord.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefixes      = prefixes,
                EnableDms           = true,
                EnableMentionPrefix = true
            });

            var vcfg = new VoiceNextConfiguration
            {
                AudioFormat = AudioFormat.Default,
            };

            var game = new DiscordActivity()
            {
                Name         = "Type |help for help!",
                ActivityType = ActivityType.Playing,
            };

            commands.RegisterCommands <Commands>();
            commands.RegisterCommands <ServerCommands>();
            commands.RegisterCommands <GBFCommands>();
            commands.RegisterCommands <LeagueCommands>();

            await discord.ConnectAsync();

            discord.Ready += async e =>
            {
                await discord.UpdateStatusAsync(game);

                DisplayGuildCount();
                ReadyChecker = true;
            };

#pragma warning disable CS1998
            discord.Heartbeated += async e =>
            {
                if (ReadyChecker == true)
                {
                    DisplayGuildCount();
                }
            };
#pragma warning restore CS1998

            await Task.Delay(-1);
        }
Exemple #23
0
        public TestBot(TestBotConfig cfg, int shardid)
        {
            // global bot config
            this.Config = cfg;

            // discord instance config and the instance itself
            var dcfg = new DiscordConfiguration
            {
                AutoReconnect         = true,
                LargeThreshold        = 250,
                LogLevel              = LogLevel.Debug,
                Token                 = this.Config.Token,
                TokenType             = this.Config.UseUserToken ? TokenType.User : TokenType.Bot,
                UseInternalLogHandler = false,
                ShardId               = shardid,
                ShardCount            = this.Config.ShardCount,
                EnableCompression     = true,
                MessageCacheSize      = 50,
                AutomaticGuildSync    = !this.Config.UseUserToken,
                DateTimeFormat        = "dd-MM-yyyy HH:mm:ss zzz"
            };

            Discord = new DiscordClient(dcfg);

            // events
            Discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageReceived;
            Discord.Ready                   += this.Discord_Ready;
            Discord.GuildAvailable          += this.Discord_GuildAvailable;
            Discord.GuildBanAdded           += this.Discord_GuildBanAdd;
            Discord.MessageCreated          += this.Discord_MessageCreated;
            Discord.MessageReactionAdded    += this.Discord_MessageReactionAdd;
            Discord.MessageReactionsCleared += this.Discord_MessageReactionRemoveAll;
            Discord.PresenceUpdated         += this.Discord_PresenceUpdate;
            Discord.ClientErrored           += this.Discord_ClientErrored;
            Discord.SocketErrored           += this.Discord_SocketError;
            Discord.GuildCreated            += this.Discord_GuildCreated;

            // voice config and the voice service itself
            var vcfg = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceNext.Codec.VoiceApplication.Music,
                EnableIncoming   = false
            };

            this.VoiceService = this.Discord.UseVoiceNext(vcfg);

            // build a dependency collection for commandsnext
            var depco = new DependencyCollectionBuilder();

            depco.AddInstance("This is a dependency string.");
            depco.Add <TestDependency>();

            // commandsnext config and the commandsnext service itself
            var cncfg = new CommandsNextConfiguration
            {
                StringPrefix          = this.Config.CommandPrefix,
                CustomPrefixPredicate = msg =>
                {
                    if (TestBotNextCommands.Prefixes.ContainsKey(msg.Channel.Id) && TestBotNextCommands.Prefixes.TryGetValue(msg.Channel.Id, out var pfix))
                    {
                        return(Task.FromResult(msg.GetStringPrefixLength(pfix)));
                    }
                    return(Task.FromResult(-1));
                },
                EnableDms            = true,
                EnableMentionPrefix  = true,
                CaseSensitive        = true,
                Dependencies         = depco.Build(),
                SelfBot              = this.Config.UseUserToken,
                IgnoreExtraArguments = false
                                       //DefaultHelpChecks = new List<CheckBaseAttribute>() { new RequireOwnerAttribute() }
            };

            this.CommandsNextService = Discord.UseCommandsNext(cncfg);
            this.CommandsNextService.CommandErrored  += this.CommandsNextService_CommandErrored;
            this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted;
            //this.CommandsNextService.RegisterCommands<TestBotCommands>();
            //this.CommandsNextService.RegisterCommands<TestBotNextCommands>();
            //this.CommandsNextService.RegisterCommands<TestBotEvalCommands>();
            //this.CommandsNextService.RegisterCommands<TestBotDependentCommands>();
            //this.CommandsNextService.RegisterCommands<TestBotGroupInheritedChecksCommands>();
            this.CommandsNextService.RegisterCommands(typeof(TestBot).GetTypeInfo().Assembly);
            this.CommandsNextService.SetHelpFormatter <TestBotHelpFormatter>();

            // interactivity service
            var icfg = new InteractivityConfiguration()
            {
                PaginationBehaviour = TimeoutBehaviour.Delete,
                PaginationTimeout   = TimeSpan.FromSeconds(30),
                Timeout             = TimeSpan.FromSeconds(30)
            };

            this.InteractivityService = Discord.UseInteractivity(icfg);
        }
Exemple #24
0
        public TestBot(TestBotConfig cfg)
        {
            // global bot config
            this.Config = cfg;

            // discord instance config and the instance itself
            var dcfg = new DiscordConfig
            {
                AutoReconnect  = true,
                DiscordBranch  = Branch.Stable,
                LargeThreshold = 250,
                // Use unnecessary instead of debug for more verbosity
                //LogLevel = LogLevel.Unnecessary,
                LogLevel              = LogLevel.Debug,
                Token                 = this.Config.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = false,
            };

            this.Discord = new DiscordClient(dcfg);

            // events
            this.Discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageReceived;
            this.Discord.Ready                    += this.Discord_Ready;
            this.Discord.GuildAvailable           += this.Discord_GuildAvailable;
            this.Discord.GuildBanAdd              += this.Discord_GuildBanAdd;
            this.Discord.MessageCreated           += this.Discord_MessageCreated;
            this.Discord.MessageReactionAdd       += this.Discord_MessageReactionAdd;
            this.Discord.MessageReactionRemoveAll += this.Discord_MessageReactionRemoveAll;
            this.Discord.PresenceUpdate           += this.Discord_PresenceUpdate;

            // command config and the command service itself
            this.Commands = new TestBotCommands();
            var ccfg = new CommandConfig
            {
                Prefix  = this.Config.CommandPrefix,
                SelfBot = false
            };

            this.CommandService = this.Discord.UseCommands(ccfg);
            this.CommandService.CommandError += this.CommandService_CommandError;

            // register all commands dynamically
            var t  = new[] { typeof(TestBotCommands), typeof(Task), typeof(CommandEventArgs) };
            var cm = t[0].GetMethods(BindingFlags.Public | BindingFlags.Instance)
                     .Where(xm => this.IsCommandMethod(xm, t[1], t[2]));

            var expr_inst = Expression.Constant(this.Commands);
            var expr_arg0 = Expression.Parameter(t[2]);

            foreach (var xm in cm)
            {
                var expr_call = Expression.Call(expr_inst, xm, expr_arg0);
                var expr_anon = Expression.Lambda <Func <CommandEventArgs, Task> >(expr_call, expr_arg0);
                var cmcall    = expr_anon.Compile();

                this.Discord.AddCommand(xm.Name.ToLower(), cmcall);
                this.Discord.DebugLogger.LogMessage(LogLevel.Info, "DSPlus Test", $"Command {xm.Name.ToLower()} registered", DateTime.Now);
            }

            // voice config and the voice service itself
            var vcfg = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceNext.Codec.VoiceApplication.Music
            };

            this.VoiceService = this.Discord.UseVoiceNext(vcfg);
        }
Exemple #25
0
        //main async task
        public async Task startBotAsync()
        {
            //loading configuration from json
            var json = "";

            using (var file = File.OpenRead("config.json"))
                using (var sr = new StreamReader(file, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync();

            //load values from config
            var configjson = JsonConvert.DeserializeObject <ConfigJson>(json);
            var config     = new DiscordConfiguration
            {
                Token     = configjson.Token,
                TokenType = TokenType.Bot,

                AutoReconnect         = true,
                LogLevel              = LogLevel.Info,
                UseInternalLogHandler = true
            };

            //instantiate the bot
            this.bot = new DiscordClient(config);

            //hook events to the bot
            this.bot.Ready          += this.botReady;
            this.bot.Ready          += this.botStatusAsync;
            this.bot.GuildAvailable += this.botGuildAvailable;
            this.bot.ClientErrored  += this.botErrorHandler;



            //command setup
            var commandConfig = new CommandsNextConfiguration
            {
                //use prefix from config
                StringPrefixes = new[] { configjson.CommandPrefix },

                //enable mentioning the bot as a prefix
                EnableMentionPrefix = true
            };

            //hook to bot
            this.Commands = this.bot.UseCommandsNext(commandConfig);

            //hook command events for debugging
            this.Commands.CommandExecuted += this.commandsExecuted;
            this.Commands.CommandErrored  += this.commandsError;

            //register commands
            this.Commands.RegisterCommands <zeroTwoCommandsUngroupped>();
            //this.Commands.RegisterCommands<zeroTwoCommandsInteractive>();
            this.Commands.RegisterCommands <zeroTwoCommandsVoice>();


            var voiceConfig = new VoiceNextConfiguration
            {
                AudioFormat = AudioFormat.Default
            };

            this.Voice = this.bot.UseVoiceNext(voiceConfig);

            //connect and log in
            await this.bot.ConnectAsync();

            //when bot is running, <prefix>help will show command list, <prefix>help <command> will show help abbout the command

            //this is to prevent premature quitting
            await Task.Delay(-1);
        }
Exemple #26
0
        public async Task RunBotAsync()
        {
            //Reads the config file
            var json = "";

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync();

            //reads value from the config
            //to our client config
            var cfgjson = JsonConvert.DeserializeObject <ConfigJson>(json);
            var cfg     = new DiscordConfiguration
            {
                Token     = cfgjson.Token,
                TokenType = TokenType.Bot,

                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            discord = new DiscordClient(cfg);
            discord.SetWebSocketClient <WebSocket4NetClient>();

            //hooks some events, so we know
            //whats going on
            discord.Ready          += Client_Ready;
            discord.GuildAvailable += Client_GuildAvailable;
            discord.ClientErrored  += Client_ClientError;

            var ccfg = new CommandsNextConfiguration
            {
                StringPrefix        = "fulp",
                CaseSensitive       = false,
                EnableDms           = true,
                EnableMentionPrefix = true
            };

            commands = discord.UseCommandsNext(ccfg);


            discord.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehaviour = TimeoutBehaviour.Ignore,
                PaginationTimeout   = TimeSpan.FromMinutes(5),
                Timeout             = TimeSpan.FromMinutes(2)
            });

            discord.MessageCreated += async e =>
            {
                if (e.Message.Content.ToLower().StartsWith("are we talking about tom fulp"))
                {
                    await e.Message.RespondAsync("I **LOVE** talking about Tom Fulp");
                }

                if ((e.Message.Content.ToLower().StartsWith("hi") ||
                     e.Message.Content.ToLower().StartsWith("hey") ||
                     e.Message.Content.ToLower().StartsWith("heya") ||
                     e.Message.Content.ToLower().StartsWith("sup") ||
                     e.Message.Content.ToLower().StartsWith("yo") ||
                     e.Message.Content.ToLower().StartsWith("hello")) && (
                        e.Message.Content.ToLower().EndsWith("tom") ||
                        e.Message.Content.ToLower().EndsWith("fulp") ||
                        e.Message.Content.ToLower().EndsWith("tom fulp") ||
                        e.Message.Content.ToLower().EndsWith("fulperino") ||
                        e.Message.Content.ToLower().EndsWith("fulpster") ||
                        e.Message.Content.ToLower().EndsWith("fulpo")))
                {
                    await e.Message.RespondAsync("Hi friend!");
                }

                if (e.Message.Content.ToLower().StartsWith("good bot"))
                {
                    await e.Message.RespondAsync("Yeah, I know");
                }

                if (e.Message.Content.ToLower().StartsWith("shame on you") || e.Message.Content.ToLower().StartsWith(".r34"))
                {
                    if (e.Message.Content.Length > 13 && !e.Message.Content.ToLower().StartsWith(".r34"))
                    {
                        await e.Message.RespondAsync("**SHAAAAAME on " + new string(e.Message.Content.Skip(13).ToArray()) + "!!!**");
                    }
                    else
                    {
                        await e.Message.RespondAsync("**SHAAAAAME!!!**");
                    }
                }

                if (e.Message.Content.ToLower().StartsWith("lies lies lies"))
                {
                    await e.Message.RespondAsync("yeah!\n\nhttps://www.youtube.com/watch?v=v6cn0mLJVZY");
                }


                if (e.Message.Content.ToLower().EndsWith("loves lolis") ||
                    e.Message.Content.ToLower().StartsWith("i love lolis") ||
                    e.Message.Content.ToLower().EndsWith("love lolis") ||
                    e.Message.Content.ToLower().EndsWith("like lolis"))
                {
                    await e.Message.RespondAsync("me too!");

                    await e.Message.RespondWithFileAsync("images/tomloveslolis.jpg");
                }

                if (e.Message.Content.ToLower().StartsWith("i hate lolis"))
                {
                    await e.Message.RespondAsync(";(");
                }

                if (e.Message.Content.ToLower().StartsWith("what's monster mashing?"))
                {
                    await e.Message.RespondAsync("A good game fool, play it!\n\nhttps://www.newgrounds.com/portal/view/707498");
                }

                if (e.Message.Content.ToLower().StartsWith("i like trains"))
                {
                    await e.Message.RespondAsync("vroom\n\nhttps://www.newgrounds.com/portal/view/581989");
                }
            };

            commands.CommandExecuted += Commands_CommandExecuted;
            commands.CommandErrored  += Commands_CommandErrored;


            commands.RegisterCommands <MyCommands>();

            var voicecfg = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceApplication.Music
            };

            voice = discord.UseVoiceNext(voicecfg);

            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
Exemple #27
0
        public async Task RunBotAsync()
        {
            // first, let's load our configuration file
            var json = "";

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync();

            // next, let's load the values from that file
            // to our client's configuration
            var cfgjson = JsonConvert.DeserializeObject <ConfigJson>(json);

            _botID    = cfgjson.Bot_ID;
            _serverID = cfgjson.Server_ID;

            var cfg = new DiscordConfiguration
            {
                Token     = cfgjson.Token,
                TokenType = TokenType.Bot,

                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            // then we want to instantiate our client
            Client = new DiscordClient(cfg);

            // If you are on Windows 7 and using .NETFX, install
            // DSharpPlus.WebSocket.WebSocket4Net from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            Client.SetWebSocketClient <WebSocket4NetClient>();

            // If you are on Windows 7 and using .NET Core, install
            // DSharpPlus.WebSocket.WebSocket4NetCore from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            //this.Client.SetWebSocketClient<WebSocket4NetCoreClient>();

            // If you are using Mono, install
            // DSharpPlus.WebSocket.WebSocketSharp from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            //this.Client.SetWebSocketClient<WebSocketSharpClient>();

            // if using any alternate socket client implementations,
            // remember to add the following to the top of this file:
            //using DSharpPlus.Net.WebSocket;

            // next, let's hook some events, so we know
            // what's going on
            Client.Ready          += Client_Ready;
            Client.GuildAvailable += Client_GuildAvailable;
            Client.ClientErrored  += Client_ClientError;
            Client.MessageCreated += Client_MessageCreated;
            //Client.GuildMemberUpdated += Client_GuildMemberUpdated;
            Client.GuildMemberAdded += Client_GuildMemberAdded;

            // let's enable interactivity, and set default options
            Client.UseInteractivity(new InteractivityConfiguration
            {
                // default pagination behaviour to just ignore the reactions
                PaginationBehaviour = TimeoutBehaviour.Ignore,

                // default pagination timeout to 5 minutes
                PaginationTimeout = TimeSpan.FromMinutes(5),

                // default timeout for other actions to 2 minutes
                Timeout = TimeSpan.FromMinutes(2)
            });

            // up next, let's set up our commands
            var ccfg = new CommandsNextConfiguration
            {
                // let's use the string prefix defined in config.json
                StringPrefix = cfgjson.CommandPrefix,

                // enable responding in direct messages
                EnableDms = true,

                // enable mentioning the bot as a command prefix
                EnableMentionPrefix = true
            };

            // let's set up voice
            var vcfg = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceApplication.Music
            };

            // and hook them up
            Commands = Client.UseCommandsNext(ccfg);

            // let's hook some command events, so we know what's
            // going on
            Commands.CommandExecuted += Commands_CommandExecuted;
            Commands.CommandErrored  += Commands_CommandErrored;

            // let's add a converter for a custom type and a name
            var mathopcvt = new MathOperationConverter();

            CommandsNextUtilities.RegisterConverter(mathopcvt);
            CommandsNextUtilities.RegisterUserFriendlyTypeName <MathOperation>("operation");

            // up next, let's register our commands
            Commands.RegisterCommands <ExampleUngrouppedCommands>();
            Commands.RegisterCommands <ExampleGrouppedCommands>();
            Commands.RegisterCommands <ExampleExecutableGroup>();
            Commands.RegisterCommands <ExampleInteractiveCommands>();
            Commands.RegisterCommands <ExampleVoiceCommands>();

            // set up our custom help formatter
            Commands.SetHelpFormatter <SimpleHelpFormatter>();

            // and let's enable Voice
            Voice = Client.UseVoiceNext(vcfg);

            // finally, let's connect and log in
            await Client.ConnectAsync();

            // when the bot is running, try doing <prefix>help
            // to see the list of registered commands, and
            // <prefix>help <command> to see help about specific
            // command.

            // and this is to prevent premature quitting
            await Task.Delay(-1);
        }
Exemple #28
0
        public async Task RunBotAsync()
        {
            try
            {
                // load settings then we want to instantiate our client
                DiscordConfiguration discordConfiguration = GetConfigFromJsonSettings();
                Client = new DiscordClient(discordConfiguration);
            }
            catch (InvalidConfigException ice)
            {
                Console.WriteLine(string.Format("{0}:\tCRITICAL ERROR: Problem with the Json Settings: {1}\n\nPress enter to close", DateTime.Now, ice.Message));
                Console.ReadLine();
                return;
            }

            // If you are on Windows 7 and using .NETFX, install
            // DSharpPlus.WebSocket.WebSocket4Net from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            // this.Client.SetWebSocketClient<WebSocket4NetClient>();

            // If you are on Windows 7 and using .NET Core, install
            // DSharpPlus.WebSocket.WebSocket4NetCore from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            // this.Client.SetWebSocketClient<WebSocket4NetCoreClient>();

            // If you are using Mono, install
            // DSharpPlus.WebSocket.WebSocketSharp from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            // this.Client.SetWebSocketClient<WebSocketSharpClient>();

            // if using any alternate socket client implementations,
            // remember to add the following to the top of this file:
            // using DSharpPlus.Net.WebSocket;

            // next, let's hook some events, so we know
            // what's going on
            Client.Ready           += this.Client_Ready;
            Client.GuildAvailable  += this.Client_GuildAvailable;
            Client.ClientErrored   += this.Client_ClientError;
            Client.PresenceUpdated += Client_PresenceUpdated;
            Client.DebugLogger.LogMessageReceived += DebugLogger_LogMessageReceived;


            // up next, let's set up our commands
            var ccfg = new CommandsNextConfiguration
            {
                // let's use the string prefix defined in config.json
                StringPrefixes = new[] { configFile.CommandPrefix },

                // enable responding in direct messages
                EnableDms = true,

                // enable mentioning the bot as a command prefix
                EnableMentionPrefix = true
            };

            // and hook them up
            this.Commands = Client.UseCommandsNext(ccfg);

            // let's hook some command events, so we know what's
            // going on
            this.Commands.CommandExecuted += this.Commands_CommandExecuted;
            this.Commands.CommandErrored  += this.Commands_CommandErrored;

            // up next, let's register our commands
            this.Commands.RegisterCommands <VoiceCommand>();
            this.Commands.RegisterCommands <PlayAudioCommand>();
            this.Commands.RegisterCommands <WormsCommand>();
            this.Commands.RegisterCommands <VoiceRecognition>();
            this.Commands.RegisterCommands <FuckYouCommand>();
            this.Commands.RegisterCommands <CustomAudioCommand>();
            this.Commands.RegisterCommands <MadWorldCommand>();
            this.Commands.RegisterCommands <CustomIntroCommand>();
            this.Commands.RegisterCommands <EmoteCommands>();
            this.Commands.RegisterCommands <RedditCommands>();
            this.Commands.SetHelpFormatter <HelpFormatter>();
            //this.Client.TypingStarted += Client_TypingStarted;

            // let's set up voice
            var vcfg = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceApplication.Music,
                EnableIncoming   = false
            };

            // and let's enable it
            this.Voice = Client.UseVoiceNext(vcfg);

            // finally, let's connect and log in
            await Client.ConnectAsync();

            // for this example you will need to read the
            // VoiceNext setup guide, and include ffmpeg.

            RedditController.StartSubscriptionThreadsThread();

            // and this is to prevent premature quitting
            await Task.Delay(-1);
        }
Exemple #29
0
        public TestBot(TestBotConfig cfg, int shardid)
        {
            // global bot config
            this.Config = cfg;

            // discord instance config and the instance itself
            var dcfg = new DiscordConfiguration
            {
                AutoReconnect      = true,
                LargeThreshold     = 250,
                MinimumLogLevel    = LogLevel.Trace,
                Token              = this.Config.Token,
                TokenType          = TokenType.Bot,
                ShardId            = shardid,
                ShardCount         = this.Config.ShardCount,
                MessageCacheSize   = 2048,
                LogTimestampFormat = "dd-MM-yyyy HH:mm:ss zzz",
                Intents            = DiscordIntents.All // if 4013 is received, change to DiscordIntents.AllUnprivileged
            };

            this.Discord = new DiscordClient(dcfg);

            // events
            this.Discord.Ready += this.Discord_Ready;
            this.Discord.GuildStickersUpdated += this.Discord_StickersUpdated;
            this.Discord.GuildAvailable       += this.Discord_GuildAvailable;
            //Discord.PresenceUpdated += this.Discord_PresenceUpdated;
            //Discord.ClientErrored += this.Discord_ClientErrored;
            this.Discord.SocketErrored          += this.Discord_SocketError;
            this.Discord.GuildCreated           += this.Discord_GuildCreated;
            this.Discord.VoiceStateUpdated      += this.Discord_VoiceStateUpdated;
            this.Discord.GuildDownloadCompleted += this.Discord_GuildDownloadCompleted;
            this.Discord.GuildUpdated           += this.Discord_GuildUpdated;
            this.Discord.ChannelDeleted         += this.Discord_ChannelDeleted;

            this.Discord.InteractionCreated          += this.Discord_InteractionCreated;
            this.Discord.ComponentInteractionCreated += this.Discord_ModalCheck;
            this.Discord.ModalSubmitted += this.Discord_ModalSubmitted;
            //this.Discord.ComponentInteractionCreated += this.RoleMenu;
            //this.Discord.ComponentInteractionCreated += this.DiscordComponentInteractionCreated;
            //this.Discord.InteractionCreated += this.SendButton;
            // For event timeout testing
            //Discord.GuildDownloadCompleted += async (s, e) =>
            //{
            //    await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
            //    throw new Exception("Flippin' tables");
            //};

            this.Discord.ThreadCreated        += this.Discord_ThreadCreated;
            this.Discord.ThreadUpdated        += this.Discord_ThreadUpdated;
            this.Discord.ThreadDeleted        += this.Discord_ThreadDeleted;
            this.Discord.ThreadListSynced     += this.Discord_ThreadListSynced;
            this.Discord.ThreadMemberUpdated  += this.Discord_ThreadMemberUpdated;
            this.Discord.ThreadMembersUpdated += this.Discord_ThreadMembersUpdated;

            // voice config and the voice service itself
            var vcfg = new VoiceNextConfiguration
            {
                AudioFormat    = AudioFormat.Default,
                EnableIncoming = true
            };

            this.VoiceService = this.Discord.UseVoiceNext(vcfg);

            // build a dependency collection for commandsnext
            var depco = new ServiceCollection();

            // commandsnext config and the commandsnext service itself
            var cncfg = new CommandsNextConfiguration
            {
                StringPrefixes           = this.Config.CommandPrefixes,
                EnableDms                = true,
                EnableMentionPrefix      = true,
                CaseSensitive            = false,
                Services                 = depco.BuildServiceProvider(true),
                IgnoreExtraArguments     = false,
                UseDefaultCommandHandler = true,
                DefaultParserCulture     = CultureInfo.InvariantCulture,
                //CommandExecutor = new ParallelQueuedCommandExecutor(2),
            };

            this.CommandsNextService = this.Discord.UseCommandsNext(cncfg);
            this.CommandsNextService.CommandErrored  += this.CommandsNextService_CommandErrored;
            this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted;
            this.CommandsNextService.RegisterCommands(typeof(TestBot).GetTypeInfo().Assembly);
            this.CommandsNextService.SetHelpFormatter <TestBotHelpFormatter>();

            // interactivity service
            var icfg = new InteractivityConfiguration()
            {
                Timeout = TimeSpan.FromSeconds(10),
                AckPaginationButtons = true,
                ResponseBehavior     = InteractionResponseBehavior.Respond,
                PaginationBehaviour  = PaginationBehaviour.Ignore,
                ResponseMessage      = "Sorry, but this wasn't a valid option, or does not belong to you!",
                PaginationButtons    = new PaginationButtons()
                {
                    Stop      = new DiscordButtonComponent(ButtonStyle.Danger, "stop", null, false, new DiscordComponentEmoji(862259725785497620)),
                    Left      = new DiscordButtonComponent(ButtonStyle.Secondary, "left", null, false, new DiscordComponentEmoji(862259522478800916)),
                    Right     = new DiscordButtonComponent(ButtonStyle.Secondary, "right", null, false, new DiscordComponentEmoji(862259691212242974)),
                    SkipLeft  = new DiscordButtonComponent(ButtonStyle.Primary, "skipl", null, false, new DiscordComponentEmoji(862259605464023060)),
                    SkipRight = new DiscordButtonComponent(ButtonStyle.Primary, "skipr", null, false, new DiscordComponentEmoji(862259654403031050))
                }
            };

            this.InteractivityService = this.Discord.UseInteractivity(icfg);
            this.LavalinkService      = this.Discord.UseLavalink();

            this.SlashCommandService = this.Discord.UseSlashCommands();
            this.SlashCommandService.SlashCommandErrored  += this.SlashCommandService_CommandErrored;
            this.SlashCommandService.SlashCommandInvoked  += this.SlashCommandService_CommandReceived;
            this.SlashCommandService.SlashCommandExecuted += this.SlashCommandService_CommandExecuted;

            if (this.Config.SlashCommandGuild != 0)
            {
                this.SlashCommandService.RegisterCommands(typeof(TestBot).GetTypeInfo().Assembly, this.Config.SlashCommandGuild);
            }

            //this.Discord.MessageCreated += async e =>
            //{
            //    if (e.Message.Author.IsBot)
            //        return;

            //    _ = Task.Run(async () => await e.Message.RespondAsync(e.Message.Content)).ConfigureAwait(false);
            //};
        }
Exemple #30
0
        public Core(int ParentId, int shardId)
        {
            //check if shardId assigned is < 0
            if (shardId < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(shardId));
            }

            //set up credentials
            LogSetup.LoggerSetup(shardId);
            _config     = new BotConfig();
            _log        = LogManager.GetCurrentClassLogger();
            Credentials = new CoreCredentials();
            _db         = new DbService(Credentials);
            var coreConfig = new DiscordConfiguration
            {
                AutoReconnect           = true,
                LargeThreshold          = 250,
                LogLevel                = DSharpPlus.LogLevel.Debug,
                Token                   = Credentials.Token,
                TokenType               = Credentials.UseUserToken ? TokenType.Bot : TokenType.Bot,
                UseInternalLogHandler   = false,
                ShardId                 = shardId,
                ShardCount              = Credentials.TotalShards,
                GatewayCompressionLevel = GatewayCompressionLevel.Stream,
                MessageCacheSize        = 50,
                AutomaticGuildSync      = true,
                DateTimeFormat          = "dd-MM-yyyy HH:mm:ss zzz"
            };

            _discord = new DiscordClient(coreConfig);

            //attach Discord events
            _discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageReceived;
            _discord.Ready             += this.Discord_Ready;
            _discord.GuildAvailable    += this.Discord_GuildAvailable;
            _discord.MessageCreated    += this.Discord_MessageCreated;
            _discord.ClientErrored     += this.Discord_ClientErrored;
            _discord.SocketErrored     += this.Discord_SocketError;
            _discord.GuildCreated      += this.Discord_GuildAvailable;
            _discord.VoiceStateUpdated += this.Discord_VoiceStateUpdated;

            var voiceConfig = new VoiceNextConfiguration
            {
                VoiceApplication = DSharpPlus.VoiceNext.Codec.VoiceApplication.Music,
                EnableIncoming   = false
            };

            _discord.UseVoiceNext(voiceConfig);
            var googleService = new GoogleApiService(Credentials);
            //enable voice service

            IGoogleApiService googleApiService = new GoogleApiService(Credentials);
            CoreMusicService  cms = new CoreMusicService(_discord, _db, Credentials, this, googleApiService);
            var depoBuild         = new ServiceCollection();

            //taken from NadeoBot's Service loading
            depoBuild.AddSingleton <DiscordClient>(_discord);
            depoBuild.AddSingleton <CoreCredentials>(Credentials);
            depoBuild.AddSingleton <IGoogleApiService>(googleApiService);
            depoBuild.AddSingleton(_db);
            depoBuild.AddSingleton(cms);

            //add dependency here

            using (var uow = _db.UnitOfWork)
            {
                _config = uow.BotConfig.GetOrCreate();
            }

            //build command configuration
            //see Dsharpplus configuration
            _log.Info($"{_config.DefaultPrefix}");

            var commandConfig = new CommandsNextConfiguration
            {
                StringPrefix         = _config.DefaultPrefix,
                EnableDms            = true,
                EnableMentionPrefix  = true,
                CaseSensitive        = true,
                Services             = depoBuild.BuildServiceProvider(),
                Selfbot              = Credentials.UseUserToken,
                IgnoreExtraArguments = false
            };

            //attach command events
            this.CommandsNextService = _discord.UseCommandsNext(commandConfig);

            this.CommandsNextService.CommandErrored += this.CommandsNextService_CommandErrored;

            this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted;

            this.CommandsNextService.RegisterCommands(typeof(CoreCommands).GetTypeInfo().Assembly);

            this.CommandsNextService.SetHelpFormatter <CoreBotHelpFormatter>();

            //interactive service

            var interConfig = new InteractivityConfiguration()
            {
                PaginationBehaviour = TimeoutBehaviour.DeleteMessage,
                //default paginationtimeout (30 seconds)
                PaginationTimeout = TimeSpan.FromSeconds(30),
                //timeout for current action
                Timeout = TimeSpan.FromMinutes(2)
            };

            //attach interactive component
            this.InteractivityService = _discord.UseInteractivity(interConfig);
            //this.CommandsNextService.RegisterCommands<CoreInteractivityModuleCommands>();
            //register commands from coreinteractivitymodulecommands
            //this.CommandsNextService.RegisterCommands(typeof(CoreInteractivityModuleCommands).GetTypeInfo().Assembly);
        }