Exemplo n.º 1
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);
        }
Exemplo n.º 2
0
        static async Task MainAsync(string[] args)
        {
            //Настройка базовой конфигурации бота
            DiscordConfiguration DiscordConfig = new DiscordConfiguration {
                Token                 = DiscordToken,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                LogLevel              = LogLevel.Debug
            };

            discord = new DiscordClient(DiscordConfig);

            //Настройка списка комманд
            CommandsNextConfiguration commandsConfig = new CommandsNextConfiguration {
                StringPrefix        = "!!",
                EnableMentionPrefix = true
            };

            commands = discord.UseCommandsNext(commandsConfig);
            commands.RegisterCommands <MyCommands> ();
            commands.RegisterCommands <VozhbanCommands> ();
            MyCommands.FillList();
            VozhbanCommands.LoadText();
            Console.WriteLine("Bot staterted 2.0");



            //Restore deleting message
            discord.MessageDeleted += async e => {
                LastDeletedMessage = e.Message.Content;
                await Task.Delay(0);
            };

            //Working when readction added
            discord.MessageReactionAdded += TumbUp;
            discord.MessageReactionAdded += Clock;
            discord.MessageReactionAdded += Permission;
            discord.MessageCreated       += RollDice;
            discord.MessageCreated       += RollXDice;
            discord.MessageCreated       += TolpojDS;

            async Task TumbUp(MessageReactionAddEventArgs context)
            {
                if (context.Emoji.Name == "👍")
                {
                    await context.Message.RespondAsync(context.User.Username + " like it!");
                }
            }

            async Task Clock(MessageReactionAddEventArgs context)
            {
                if (context.Emoji.Name == "⏲")
                {
                    string Respond = context.User.Username + " готов поиграть в ДС!";
                    if (PartyCount > 0)
                    {
                        Respond += "\n Кстати в войсе уже " + PartyCount + " людей!";
                    }
                    await context.Message.RespondAsync(Respond);
                }
            }

            await discord.ConnectAsync();

            async Task Permission(MessageReactionAddEventArgs context)
            {
                if (context.Emoji.Name == "🔫")
                {
                    await context.Message.RespondAsync(context.Message.Author.Username + " расстрелян");
                }
            }

            async Task TolpojDS(MessageCreateEventArgs context)
            {
                string Message = context.Message.Content.ToUpper();

                if (Message.Contains("<@&515543976678391808>"))
                {
                    await context.Message.CreateReactionAsync(DSharpPlus.Entities.DiscordEmoji.FromName(discord, ":g6:"));

                    await context.Message.CreateReactionAsync(DSharpPlus.Entities.DiscordEmoji.FromName(discord, ":r1:"));
                }
            }

            async Task RollXDice(MessageCreateEventArgs context)
            {
                string Message = context.Message.Content.ToLower();

                int d = Message.IndexOf("r");

                if (d != -1)
                {
                    string Respond   = "";
                    int    RollCount = 0;
                    int    s         = Message.IndexOf("+");
                    int    Mod       = 0;
                    int    Sides     = 0;
                    string Sign      = "";
                    string Side      = "";
                    Random Die       = new Random();

                    if (s == -1)
                    {
                        s = Message.IndexOf("-");
                    }

                    if (s != -1)
                    {
                        if (int.TryParse(Message.Remove(0, s), out Mod) == true)
                        {
                            if (Mod > 0)
                            {
                                Sign = "+";
                            }
                        }
                        Side = Message.Remove(s);
                    }
                    else
                    {
                        Mod  = 0;
                        Side = Message;
                    }

                    if (d == 0)
                    {
                        RollCount = 1;
                    }
                    else
                    {
                        if (int.TryParse(Message.Remove(d), out RollCount) == true)
                        {
                            if (RollCount <= 0)
                            {
                                RollCount = 0;
                                Respond   = context.Message.Author.Mention + " роняет кубы, выкидывает **-11** и страдает. За тупость.\n";
                            }
                        }
                    }

                    if (int.TryParse(Side.Remove(0, d + 1), out Sides) == true)
                    {
                        int Dice = Die.Next(1, Sides + 1);
                        if (Sides <= 0)
                        {
                            RollCount = 0;
                            Respond   = context.Message.Author.Mention + " роняет кубы, выкидывает **-11** и страдает. За тупость.\n";
                        }
                    }
                    else
                    {
                        RollCount = 0;
                    }

                    if ((Message.Length == d + 1) || (Message.Length == s + 1) || (s == d + 1))
                    {
                        RollCount = 0;
                    }

                    for (int i = 0; i < RollCount; i++)
                    {
                        if (Mod == 0)
                        {
                            int Dice = Die.Next(1, Sides + 1);
                            Respond += context.Message.Author.Mention + " кидает " + Sides + "-гранник и выкидывает **" + Dice + "**\n";
                        }
                        else
                        {
                            int Dice = Die.Next(1, Sides + 1);
                            Respond += context.Message.Author.Mention + " кидает " + Sides + "-гранник и выкидывает " + Dice + Sign + Mod + " = **" + (Dice + Mod) + "**\n";
                        }
                    }
                    await context.Message.RespondAsync(Respond);

                    await context.Message.DeleteAsync();
                }
            }

            async Task RollDice(MessageCreateEventArgs context)
            {
                string Message = context.Message.Content.ToLower();

                int d = Message.IndexOf("d");

                if (d != -1)
                {
                    string Respond   = "";
                    int    RollCount = 0;

                    if (d == 0)
                    {
                        RollCount = 1;
                    }
                    else
                    {
                        if (int.TryParse(Message.Remove(d), out RollCount) == true)
                        {
                            if (RollCount <= 0)
                            {
                                RollCount = 0;
                                Respond   = context.Message.Author.Mention + " роняет кубы, выкидывает **-11** и страдает. За тупость.\n";
                            }
                        }
                    }

                    for (int i = 0; i < RollCount; i++)
                    {
                        Random GreenDie = new Random();
                        Random RedDie   = new Random();

                        int Green = GreenDie.Next(1, 7);
                        int Red   = RedDie.Next(1, 7);

                        string EmoGreenDie;
                        string EmoRedDie;

                        EmoGreenDie = DSharpPlus.Entities.DiscordEmoji.FromName(discord, ":g" + Green + ":").ToString();
                        EmoRedDie   = DSharpPlus.Entities.DiscordEmoji.FromName(discord, ":r" + Red + ":").ToString();

                        if (Message.Length == d + 1)
                        {
                            Respond += context.Message.Author.Mention + " выкидывает " + EmoGreenDie + EmoRedDie + " | " + Green + " - " + Red + " = **" + (Green - Red) + "**\n";
                        }
                        else
                        {
                            int    Mod  = 0;
                            string Sign = "";
                            if (int.TryParse(Message.Remove(0, d + 1), out Mod) == true)
                            {
                                if (Mod >= 0)
                                {
                                    Sign = "+";
                                }
                                else
                                {
                                    Sign = "";
                                }
                                Respond += context.Message.Author.Mention + " выкидывает " + EmoGreenDie + EmoRedDie + " | " + Green + " - " + Red + " " + Sign + Mod + " = **" + (Green - Red + Mod) + "**\n";
                            }
                        }
                    }
                    await context.Message.RespondAsync(Respond);

                    await context.Message.DeleteAsync();
                }
            }

            /*
             * async Task StatCheck (MessageCreateEventArgs context) {
             *
             *      string Message = context.Message.Content.ToLower();
             *
             *      if (Message[0] == 'd') {
             *
             *              string Respond = "";
             *              //Бросаем 2 d6
             *              Random FirstD6  = new Random ();
             *              Random SecondD6 = new Random ();
             *              int First  = FirstD6 .Next (1,7);
             *              int Second = SecondD6.Next (1,7);
             *
             *              string GreenDie;
             *              string RedDie;
             *
             *              GreenDie = DSharpPlus.Entities.DiscordEmoji.FromName(discord, ":g" + First + ":").ToString();
             *              RedDie   = DSharpPlus.Entities.DiscordEmoji.FromName(discord, ":r" + Second + ":").ToString();
             *
             *              if (Message.Length == 1) {
             *                      Respond = context.Message.Author.Mention + " выкидывает " + GreenDie + RedDie + " | " + First + "-" + Second + "= **" + (First - Second) + "**";
             *              }
             *              else {
             *                      int Side = 0;
             *
             *                      if (Message.Length > 2 && Message[1] == '-') {
             *                              if (int.TryParse (Message.Remove (0,2), out Side) == true) {
             *                                      Random random  = new Random ();
             *                                      int Result = random.Next (1, Side);
             *                                      Respond = context.Message.Author.Mention + " выкидывает " + GreenDie + RedDie + " | " + First + "-" + Second + "-" + Side + "= **" + (First - Second - Side) + "**";
             *                              }
             *                      }
             *                      else {
             *
             *                              if (int.TryParse (Message.Remove (0,1), out Side) == true) {
             *                                      Random random  = new Random ();
             *                                      int Result = 0;
             *                                      if (Side > 1) {
             *                                              Result = random.Next (1, Side);
             *                                      }
             *                                      Respond = context.Message.Author.Mention + " выкидывает " + GreenDie + RedDie + " | " + First + "-" + Second + "+" + Side + "= **" + (First - Second + Side) + "**";
             *                              }
             *                      }
             *              }
             *              await context.Message.RespondAsync (Respond);
             *              await context.Message.DeleteAsync ();
             *      }
             * }
             */

            //Позволяет печатать прямо из консоли в любой канал, при отправке в azure лучше закоментить этот код
            //while(true) {
            //	string Message = Console.ReadLine ();
            //	DSharpPlus.Entities.DiscordChannel channel = await discord.GetChannelAsync (292562693993529349);//NSFW Science 439527469897351178 //Bot log 530096997726945317
            //	await discord.SendMessageAsync (channel, Message);
            //}

            await Task.Delay(-1);
        }
Exemplo n.º 3
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
            };

            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.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.Discord.MessageCreated += async e =>
            //{
            //    if (e.Message.Author.IsBot)
            //        return;

            //    _ = Task.Run(async () => await e.Message.RespondAsync(e.Message.Content)).ConfigureAwait(false);
            //};
        }
Exemplo n.º 4
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);
            var cfg     = new DiscordConfiguration
            {
                Token     = cfgjson.Token,
                TokenType = TokenType.Bot,

                AutoReconnect   = true,
                MinimumLogLevel = LogLevel.Debug
            };

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

            // 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;

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

                // 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
                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
            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;

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

            // finally, let's connect and log in
            await this.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);
        }
Exemplo n.º 5
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);
            var cfg     = new DiscordConfiguration
            {
                Token     = cfgjson.Token,
                TokenType = TokenType.Bot,

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

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

            // 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
                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
            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;

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

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

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

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

            // finally, let's connect and log in
            await this.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);
        }
Exemplo n.º 6
0
        public async Task RunBotAsync()
        {
            ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;
            // 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
            cfgjson = JsonConvert.DeserializeObject <ConfigJson>(json);
            var cfg = new DiscordConfiguration
            {
                Token     = cfgjson.Token,
                TokenType = TokenType.Bot,

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



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

            // 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;

            // let's enable interactivity, and set default options
            this.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,

                EnableDefaultHelp = false
            };

            // 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;

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


            //await this.Client.UpdateStatusAsync(dg);

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

            //test();
            while (true)
            {
                checkForReminders();
                //Check every minute for assigned tasks
                Thread.Sleep(60000);
            }

            // 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);
        }
Exemplo n.º 7
0
        public RPBot(Config 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.Info,
                Token                 = this.Config.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = false,
                ShardId               = shardid,
                ShardCount            = this.Config.ShardCount,
            };

            Discord = new DiscordClient(dcfg);
            //Discord.SetWebSocketClient<WebSocketSharpClient>();
            // events
            Discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageReceived;
            Discord.Ready          += this.Discord_Ready;
            Discord.GuildAvailable += this.Discord_GuildAvailable;
            Discord.MessageCreated += this.Discord_MessageCreated;
            Discord.MessageDeleted += this.Discord_MessageDeleted;
            Discord.MessageUpdated += this.Discord_MessageUpdated;

            Discord.MessageReactionAdded    += this.Discord_MessageReactionAdd;
            Discord.MessageReactionsCleared += this.Discord_MessageReactionRemoveAll;
            Discord.PresenceUpdated         += this.Discord_PresenceUpdate;
            Discord.SocketClosed            += this.Discord_SocketClose;
            Discord.GuildMemberAdded        += this.Discord_GuildMemberAdded;
            Discord.GuildMemberRemoved      += this.Discord_GuildMemberRemoved;
            Discord.SocketErrored           += this.Discord_SocketError;
            Discord.VoiceStateUpdated       += this.Discord_VoiceStateUpdated;
            Discord.ClientErrored           += this.Discord_ClientErrored;

            // commandsnext config and the commandsnext service itself
            var cncfg = new CommandsNextConfiguration
            {
                StringPrefixes = new List <string>()
                {
                    Config.CommandPrefix, ""
                },
                EnableDms           = true,
                EnableMentionPrefix = true,
                CaseSensitive       = false
            };

            this.CommandsNextService = Discord.UseCommandsNext(cncfg);
            this.CommandsNextService.CommandErrored  += this.CommandsNextService_CommandErrored;
            this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted;

            CommandsNextService.RegisterCommands(typeof(XPClass));
            //    this.CommandsNextService.RegisterCommands<InstanceClass>();
            CommandsNextService.RegisterCommands(typeof(MoneyClass));
            CommandsNextService.RegisterCommands(typeof(CommandsClass));
            CommandsNextService.RegisterCommands(typeof(GuildClass));
            CommandsNextService.RegisterCommands(typeof(BloodClass));
            CommandsNextService.RegisterCommands(typeof(MeritClass));
            CommandsNextService.RegisterCommands(typeof(LogClass));
            CommandsNextService.RegisterCommands(typeof(TriviaClass));
            CommandsNextService.RegisterCommands(typeof(ModClass));
            CommandsNextService.RegisterCommands(typeof(TagClass));
            CommandsNextService.RegisterCommands(typeof(SVClass));
            CommandsNextService.RegisterCommands(typeof(WikiClass));
            CommandsNextService.RegisterCommands(typeof(StatsClass));
            CommandsNextService.RegisterCommands(typeof(SignupClass));
            CommandsNextService.RegisterCommands(typeof(FameClass));
            CommandsNextService.RegisterCommands(typeof(InfamyClass));
            CommandsNextService.RegisterCommands(typeof(CardClass));


            // WikiClass.InitWiki();

            InteractivityConfiguration icfg = new InteractivityConfiguration();

            this.InteractivityService = Discord.UseInteractivity(icfg);
        }
Exemplo n.º 8
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);
            var cfg     = new DiscordConfiguration
            {
                Token     = cfgjson.Token,
                TokenType = TokenType.Bot,

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

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

            // 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 = cfgjson.CommandPrefix,

                // 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;

            // up next, let's register our commands
            this.Commands.RegisterCommands <BasicUnGroupedCommands>();
            this.Commands.RegisterCommands <DKPGroupedCommands>();
            this.Commands.RegisterCommands <AttendanceCommands>();

            //Trigger the singleton for our DKP service
            DKPService vService = DKPService.Instance;

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

            // and this is to prevent premature quitting
            await Task.Delay(-1);
        }
Exemplo n.º 9
0
        private async Task Login()
        {
            _logger.Information("Initializing the client setup...");
            var activity = new DiscordActivity("ur mom is pretty gae", ActivityType.Custom);

            _client = new DiscordShardedClient(new DiscordConfiguration
            {
                Token                   = _token,
                TokenType               = TokenType.Bot,
                DateTimeFormat          = "dd-MM-yyyy HH:mm",
                AutoReconnect           = true,
                MessageCacheSize        = 4096,
                ReconnectIndefinitely   = true,
                HttpTimeout             = Timeout.InfiniteTimeSpan,
                GatewayCompressionLevel = GatewayCompressionLevel.Payload
            });

            _logger.Information("Successfully setup the client.");
            _logger.Information("Setting up all configurations...");

            var ccfg = new CommandsNextConfiguration
            {
                Services            = _serviceProvider,
                PrefixResolver      = PrefixResolverAsync,
                EnableMentionPrefix = false,
                EnableDms           = true,
                DmHelp            = true,
                EnableDefaultHelp = true
            };

            _logger.Information("Commands configuration setup done.");

            var icfg = new InteractivityConfiguration
            {
                PollBehaviour = PollBehaviour.KeepEmojis,
                Timeout       = TimeSpan.FromMinutes(2)
            };

            _logger.Information("Interactivity configuration setup done.");
            _logger.Information("Connecting all shards...");
            await _client.StartAsync().ConfigureAwait(true);

            await _client.UpdateStatusAsync(activity, UserStatus.Online).ConfigureAwait(true);

            _logger.Information("Setting up client event handler...");
            _clientEventHandler = new ClientEventHandler(_client, _logger, _redis, _reactionListener);

            foreach (var shard in _client.ShardClients.Values)
            {
                _logger.Information($"Applying configs to shard {shard.ShardId}...");
                _cnext = shard.UseCommandsNext(ccfg);
                _cnext.RegisterCommands(Assembly.GetEntryAssembly());
                _cnext.SetHelpFormatter <HelpFormatter>();
                shard.UseInteractivity(icfg);
                _logger.Information($"Settings up command event handler for the shard {shard.ShardId}...");
                _commandEventHandler = new CommandEventHandler(_cnext, _logger);
                _logger.Information($"Setup for shard {shard.ShardId} done.");
                await shard.InitializeAsync();
            }

            foreach (var cNextRegisteredCommand in _cnext.RegisteredCommands)
            {
                _logger.Information($"{cNextRegisteredCommand.Value} is registered!");
            }
        }
Exemplo n.º 10
0
        public BotService(
            IOptions <BotOptions> options,
            ILoggerFactory factory,
            IServiceProvider provider,
            IMediator mediator,
            IDateTimeZoneProvider timeZoneProvider)
        {
            this.Started          = false;
            this.config           = options.Value;
            this.Logger           = factory.CreateLogger <BotService>();
            this.Mediator         = mediator;
            this.TimeZoneProvider = timeZoneProvider;
            MemoryCacheOptions memCacheOpts = new()
            {
                SizeLimit            = 1000,
                CompactionPercentage = .25,
            };

            this.PrefixCache = new MemoryCache(memCacheOpts, factory);

            #region Client Config
            this.clientConfig = new DiscordConfiguration
            {
                Token           = this.config.BotToken,
                TokenType       = TokenType.Bot,
                Intents         = DiscordIntents.All,
                LoggerFactory   = factory,
                MinimumLogLevel = LogLevel.Trace,
            };
            #endregion

            #region Commands Module Config
            this.commandsConfig = new CommandsNextConfiguration
            {
                Services            = provider,
                EnableDms           = this.config.EnableDms,
                EnableMentionPrefix = this.config.EnableMentionPrefix
            };

            if (this.config.EnablePrefixResolver)
            {
                this.commandsConfig.PrefixResolver = this.CheckForPrefix;
            }
            else
            {
                this.commandsConfig.StringPrefixes = this.config.Prefixes;
            }
            #endregion

            #region Interactivity Module Config
            this.interactivityConfig = new InteractivityConfiguration
            {
                PaginationBehaviour = PaginationBehaviour.Ignore,
                PaginationDeletion  = PaginationDeletion.KeepEmojis,
                PollBehaviour       = PollBehaviour.DeleteEmojis,
                Timeout             = TimeSpan.FromMinutes(5),
            };
            #endregion

            this.ShardedClient = new DiscordShardedClient(this.clientConfig);
        }
Exemplo n.º 11
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);
            var cfg     = new DiscordConfiguration
            {
                Token     = cfgjson.Token,
                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 = cfgjson.CommandPrefix,

                // 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;

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

            // 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);
        }
Exemplo n.º 12
0
        public override async void Initialize()
        {
            #region Hooks
            ServerApi.Hooks.ServerCommand.Register(this, Logs.OnServerCommand);
            ServerApi.Hooks.GamePostInitialize.Register(this, Utils.OnPostInitialize);
            ServerApi.Hooks.ServerBroadcast.Register(this, Bridge.OnBC);
            ServerApi.Hooks.NetGreetPlayer.Register(this, OnGreet);
            ServerApi.Hooks.WorldSave.Register(this, OnSave);

            GeneralHooks.ReloadEvent += OnReload;
            //GetDataHandlers.KillMe += Bridge.OnKill;
            PlayerHooks.PlayerCommand += Logs.OnPlayerCommand;
            PlayerHooks.PlayerLogout  += OnLogout;
            PlayerHooks.PlayerChat    += OnChat;
            #endregion

            LoadConfig();

            Color = new Color(Config.Messagecolor[0], Config.Messagecolor[1], Config.Messagecolor[2]);

            if (Config.DiscordBotToken != "Token here")
            {
                DiscordBot = new DiscordClient(new DiscordConfiguration
                {
                    Token     = Config.DiscordBotToken,
                    TokenType = TokenType.Bot,

                    UseInternalLogHandler = true,
                    LogLevel = LogLevel.Warning
                });
                await DiscordBot.ConnectAsync();

                if (Config.Commands)
                {
                    var ccfg = new CommandsNextConfiguration
                    {
                        StringPrefix = Config.Prefix,

                        EnableDms = false,

                        EnableMentionPrefix = false
                    };

                    this.DiscordCommands = DiscordBot.UseCommandsNext(ccfg);

                    DiscordCommands.RegisterCommands <BotCommands>();

                    this.DiscordCommands.SetHelpFormatter <HelpFormatter>();

                    this.DiscordCommands.CommandExecuted += this.CommandExecuted;
                    this.DiscordCommands.CommandErrored  += this.CommandErrored;
                }

                DiscordBot.ClientErrored  += this.ClientErrored;
                DiscordBot.MessageCreated += OnMessageCreated;
            }
            else
            {
                Environment.Exit(0);
            }
        }
Exemplo n.º 13
0
        private async Task Login()
        {
            this.logger.Information("Initializing the client setup...");

            client = new DiscordShardedClient(new DiscordConfiguration
            {
                Token                   = config.Token,
                TokenType               = TokenType.Bot,
                LogTimestampFormat      = "dd-MM-yyyy HH:mm",
                AutoReconnect           = true,
                MessageCacheSize        = 4096,
                HttpTimeout             = Timeout.InfiniteTimeSpan,
                GatewayCompressionLevel = GatewayCompressionLevel.Stream
            });

            this.logger.Information("Successfully setup the client.");
            this.logger.Information("Setting up all configurations...");

            var ccfg = new CommandsNextConfiguration
            {
                Services            = serviceProvider,
                PrefixResolver      = PrefixResolverAsync,
                EnableMentionPrefix = true,
                EnableDms           = true,
                DmHelp                   = false,
                EnableDefaultHelp        = true,
                UseDefaultCommandHandler = true
            };

            this.logger.Information("Commands configuration setup done.");

            var icfg = new InteractivityConfiguration {
                PollBehaviour = PollBehaviour.KeepEmojis, Timeout = TimeSpan.FromMinutes(2)
            };

            this.logger.Information("Interactivity configuration setup done.");
            this.logger.Information("Connecting all shards...");
            await client.StartAsync()
            .ConfigureAwait(true);

            this.logger.Information("Setting up client event handler...");
            clientEventHandler = new ClientEventHandler(client, logger, redis, reactionService, logService);

            foreach (var shard in client.ShardClients.Values)
            {
                logger.Information($"Applying configs to shard {shard.ShardId}...");
                commandsNext = shard.UseCommandsNext(ccfg);
                commandsNext.RegisterCommands(typeof(Modules.Dummy).Assembly);
                commandsNext.SetHelpFormatter <HelpFormatter>();
                shard.UseInteractivity(icfg);
                this.logger.Information($"Settings up command event handler for the shard {shard.ShardId}...");
                commandEventHandler = new CommandEventHandler(commandsNext, logger);
                this.logger.Information($"Setup for shard {shard.ShardId} done.");
                await shard.InitializeAsync().ConfigureAwait(true);
            }

            foreach (var cNextRegisteredCommand in commandsNext.RegisteredCommands)
            {
                this.logger.Information($"{cNextRegisteredCommand.Value} is registered!");
            }
        }
Exemplo n.º 14
0
        public async Task RunBotAsync()
        {
            var cfg = new DiscordConfig
            {
                Token                 = ApplicationInformation.DiscordToken,
                TokenType             = TokenType.Bot,
                AutoReconnect         = true,
                LogLevel              = LogLevel.Info,
                UseInternalLogHandler = true
            };

            // Init client
            Client = new DiscordClient(cfg);

            // Issue event hooks to client
            Client.Ready          += Client_Ready;
            Client.GuildAvailable += Client_GuildAvailable;
            Client.ClientError    += 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 = Resources.CommandPrefix,

                // enable responding in direct messages
                EnableDms = false,

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

                EnableDefaultHelp = false
            };

            // 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 <UngroupedCommands>();
            Commands.RegisterCommands <GroupedCommands>();
            Commands.RegisterCommands <ExecCommands>();
            Commands.RegisterCommands <TextOutputsCommands>();
            Commands.RegisterCommands <BotOwnerCommands>();

            // finnaly, 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);
        }
Exemplo n.º 15
0
        public async Task RunAsync()
        {
            var    json         = string.Empty;
            string loadBotFiles = Globals.loadBotFiles;

            string jsonConfig   = @"config.json";
            bool   configExists = File.Exists(jsonConfig);

            if (configExists)
            {
                Globals.CWLMethod("Config File Found", "Yellow");

                using (var fs = File.OpenRead(jsonConfig))
                    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 = Microsoft.Extensions.Logging.LogLevel.Debug
                };

                Client        = new DiscordClient(config);
                Client.Ready += (OnClientReady);

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

                Commands = Client.UseCommandsNext(commandsConfig);

                Commands.RegisterCommands <AchievementSearch>();
                Commands.RegisterCommands <EQPatch>();
                Commands.RegisterCommands <EQEvent>();
                Commands.RegisterCommands <FactionSearch>();
                Commands.RegisterCommands <Help>();
                Commands.RegisterCommands <ItemSearch>();
                //Commands.RegisterCommands<OverseerSearch>();
                Commands.RegisterCommands <Raffle>();
                Commands.RegisterCommands <Reload>();
                Commands.RegisterCommands <SpellSearch>();

                var gamePlaying = new DiscordActivity
                {
                    Name = "EverQuest",
                };

                await Client.ConnectAsync(gamePlaying);

                await Task.Delay(-1);
            }
            else
            {
                Globals.CWLMethod("Config File was not found, Bot can't run...", "Red");
                await Task.Delay(-1);
            }
        }
Exemplo n.º 16
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);
            var cfg     = new DiscordConfiguration
            {
                Token     = cfgjson.Token,
                TokenType = TokenType.Bot,

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

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

            // 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
                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
            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;

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

            // let's enable voice
            this.Voice = this.Client.UseVoiceNext();

            // 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);
        }
Exemplo n.º 17
0
        public static async Task Main(String[] args)
        {
            //run command line parser
            Parser.Default.ParseArguments <CommandLineOptions>(args)
            .WithParsed <CommandLineOptions>(o =>
            {
                CommandLineOptions = o;
            });

            // initialize datafixers
#if DEBUG
            DatafixerLogger.MinimalLevel = Helium.Commons.Logging.LogLevel.Debug;
#else
            DatafixerLogger.MinimalLevel = Helium.Commons.Logging.LogLevel.Warning;
#endif

            DataFixerLower.Initialize(0); //this can be switched out for 1 if you need to, insanitybot default is 0
            RegisterDatafixers();

            //load main config
            ConfigManager   = new MainConfigurationManager();
            LanguageManager = new LanguageConfigurationManager();

            //read config from file
            Config = ConfigManager.Deserialize("./config/main.json");

            if (String.IsNullOrWhiteSpace(Config.Token))
            {
                Console.WriteLine("Invalid Token. Please provide a valid token in .\\config\\main.json" +
                                  "\nPress any key to continue...");
                Console.ReadKey();
                return;
            }

            LanguageConfig = LanguageManager.Deserialize("./config/lang.json");


            //create discord config; increase the cache size if you want though itll take more RAM
            ClientConfiguration = new DiscordConfiguration
            {
                AutoReconnect    = true,
                Token            = Config.Token,
                TokenType        = TokenType.Bot,
                MessageCacheSize = 4096,
#if DEBUG
                MinimumLogLevel = LogLevel.Debug
#else
                MinimumLogLevel = LogLevel.Information
#endif
            };

            //create and connect client
            Client = new DiscordClient(ClientConfiguration);
            await Client.ConnectAsync();

            //load perms :b
            Client.InitializePermissionFramework();

            try
            {
                //create home guild so commands can use it
                HomeGuild = await Client.GetGuildAsync(Convert.ToUInt64(Config.GuildId));
            }
#pragma warning disable CS0168
            catch (UnauthorizedException e)
#pragma warning restore CS0168
            {
                Client.Logger.LogCritical(new EventId(0000, "Main"),
                                          "Your GuildId is either invalid or InsanityBot has not been invited to the server yet.");
            }
            catch
            {
                throw;
            }

            //load command configuration
            CommandConfiguration = new CommandsNextConfiguration
            {
                CaseSensitive        = false,
                StringPrefixes       = Config.Prefixes,
                DmHelp               = (Boolean)Config["insanitybot.commands.help.send_dms"],
                IgnoreExtraArguments = true
            };

            //create and register command client
            Client.UseCommandsNext(CommandConfiguration);
            CommandsExtension = Client.GetCommandsNext();

            //start timer framework
            TimeHandler.Start();

            //register commands and events
            RegisterAllCommands();
            RegisterAllEvents();

            //initialize various parts of InsanityBots framework
            InitializeAll();

            Client.Logger.LogInformation(new EventId(1000, "Main"), "Startup successful!");

            //start offthread TCP connection
            _ = HandleTCPConnections((Int64)Config["insanitybot.tcp_port"]);

            //start offthread XP management
            if ((Boolean)Config["insanitybot.modules.experience"])
            {
                ; // not implemented yet
            }
            //start offthread console management
            if ((Boolean)Config["insanitybot.modules.console"])
            {
                ; // not implemented yet
            }
            //abort main thread, who needs it anyway
            Thread.Sleep(-1);
        }
Exemplo n.º 18
0
 public Comandos(DiscordClient cliente, CommandsNextConfiguration configuracao, IServiceProvider serviceProvider)
 {
     configuracao.Services = serviceProvider;
     _serviceProvider      = serviceProvider;
     _comandos             = cliente.UseCommandsNext(configuracao);
 }
Exemplo n.º 19
0
        public async Task RunBotAsync()
        {
            var json = "";

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

            CfgJson = JsonConvert.DeserializeObject <JazzBotConfig>(json);

            Console.WriteLine("Конфиг загружен");

            var cfg = new DiscordConfiguration
            {
                Token     = CfgJson.Discord.Token,
                TokenType = TokenType.Bot,

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

            this.Client = new DiscordClient(cfg);

            this.Client.Ready                += this.Client_Ready;
            this.Client.GuildAvailable       += this.Client_GuildAvailable;
            this.Client.ClientErrored        += this.Client_ClientError;
            this.Client.VoiceServerUpdated   += this.Voice_VoiceServerUpdate;
            this.Client.MessageReactionAdded += this.Client_ReactionAdded;
            this.Bot = new Bot(CfgJson, this.Client);

            this.Services = new ServiceCollection()
                            .AddSingleton(this.Client)
                            .AddSingleton(this.Bot)
                            .AddSingleton <MusicService>()
                            .AddSingleton(new YoutubeService(CfgJson.Youtube))
                            .AddSingleton(new LavalinkService(CfgJson, this.Client))
                            .AddScoped <DatabaseContext>()
                            .AddSingleton(this)
                            .BuildServiceProvider(true);


            var ccfg = new CommandsNextConfiguration
            {
                StringPrefixes = CfgJson.Discord.Prefixes,

                EnableDefaultHelp = true,

                CaseSensitive = false,

                EnableDms = false,

                EnableMentionPrefix = true,

                Services = this.Services
            };

            this.Commands = this.Client.UseCommandsNext(ccfg);


            this.Commands.CommandExecuted += this.Commands_CommandExecuted;
            this.Commands.CommandErrored  += this.Commands_CommandErrored;


            this.Commands.RegisterCommands <UngruppedCommands>();
            this.Commands.RegisterCommands <MusicCommands>();
            this.Commands.RegisterCommands <OwnerCommands>();
            this.Commands.RegisterCommands <TagCommands>();
            this.Commands.RegisterCommands <InfoCommands>();
            this.Commands.RegisterCommands <EmojiCommands>();
            this.Commands.SetHelpFormatter <JazzBotHelpFormatter>();

            this.Commands.RegisterConverter(new CustomEmojiConverter());
            this.Commands.RegisterUserFriendlyTypeName <DiscordEmojiWrapper>("эмодзи");

            var icfg = new InteractivityConfiguration
            {
                Timeout = TimeSpan.FromSeconds(45)
            };

            this.Interactivity = this.Client.UseInteractivity(icfg);

            this.Lavalink = this.Client.UseLavalink();


            await this.Client.ConnectAsync();

            await Task.Delay(-1);
        }
Exemplo n.º 20
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"
            };

            Discord = new DiscordClient(dcfg);

            // events
            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;

            // For event timeout testing
            //Discord.GuildDownloadCompleted += async (s, e) =>
            //{
            //    await Task.Delay(TimeSpan.FromSeconds(2));
            //    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));
            //};
        }
Exemplo n.º 21
0
        public async Task RunBotAsync()
        {
            var cfg = new DiscordConfiguration
            {
                Token           = BotSettings.Token,
                AutoReconnect   = true,
                TokenType       = TokenType.Bot,
                MinimumLogLevel = BotSettings.Debug ? LogLevel.Debug : LogLevel.Information
            };

            Client = new DiscordClient(cfg);

            var ccfg = new CommandsNextConfiguration
            {
                StringPrefixes      = new[] { BotSettings.Prefix },
                EnableDms           = true,
                CaseSensitive       = false,
                EnableMentionPrefix = true
            };

            Commands = Client.UseCommandsNext(ccfg);

            var icfg = new InteractivityConfiguration
            {
                PaginationBehaviour = PaginationBehaviour.WrapAround,
                PaginationDeletion  = PaginationDeletion.DeleteEmojis,
                Timeout             = TimeSpan.FromMinutes(2)
            };

            Interactivity = Client.UseInteractivity(icfg);

            //Команды
            Commands.RegisterCommands(Assembly.GetExecutingAssembly());

            //Кастомная справка команд
            Commands.SetHelpFormatter <HelpFormatter>();

            //Ивенты
            AsyncListenerHandler.InstallListeners(Client, this);

            ConnectionString =
                $"Server={Bot.BotSettings.DatabaseHost}; Port=3306; Database={Bot.BotSettings.DatabaseName}; Uid={Bot.BotSettings.DatabaseUser}; Pwd={Bot.BotSettings.DatabasePassword}; CharSet=utf8mb4;";

            await Client.ConnectAsync();

            if (!Directory.Exists("generated"))
            {
                Directory.CreateDirectory("generated");
            }
            if (!File.Exists("generated/attachments_messages.csv"))
            {
                File.Create("generated/attachments_messages.csv");
            }
            if (!File.Exists("generated/find_channel_invites.csv"))
            {
                File.Create("generated/find_channel_invites.csv");
            }
            if (!File.Exists("generated/top_inviters.xml"))
            {
                File.Create("generated/top_inviters.xml");
            }
            if (!Directory.Exists("generated/stats"))
            {
                Directory.CreateDirectory("generated/stats");
            }
            if (!File.Exists("generated/stats/ship_names.csv"))
            {
                File.Create("generated/stats/ship_names.csv");
            }

            await Task.Delay(-1);
        }
Exemplo n.º 22
0
        public async Task RunBotAsync()
        {
            // next, let's load the values from that file
            // to our client's configuration
            var cfg = new DiscordConfiguration
            {
                Token     = Environment.GetEnvironmentVariable(BotName + "Token"),
                TokenType = TokenType.Bot,

                AutoReconnect   = true,
                MinimumLogLevel = LogLevel.Debug,
                Intents         = DiscordIntents.AllUnprivileged,
            };

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

            // next, let's hook some events, so we know
            // what's going on

            this.Client.UseInteractivity(new InteractivityConfiguration()
            {
                PollBehaviour = PollBehaviour.KeepEmojis,
                Timeout       = TimeSpan.FromSeconds(15)
            });

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

                // enable responding in direct messages
                EnableDms = true,

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

                UseDefaultCommandHandler = false
            };

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

            // Hook all possible Event Handlers in the system.
            this.Client.ChannelCreated           += this.Event_ChannelCreated;
            this.Client.ChannelDeleted           += this.Event_ChannelDeleted;
            this.Client.ChannelPinsUpdated       += this.Event_ChannelPinsUpdated;
            this.Client.ChannelUpdated           += this.Event_ChannelUpdated;
            this.Client.ClientErrored            += this.Event_ClientErrored;
            this.Client.DmChannelDeleted         += this.Event_DmChannelDeleted;
            this.Client.GuildAvailable           += this.Event_GuildAvailable;
            this.Client.GuildBanAdded            += this.Event_GuildBanAdded;
            this.Client.GuildBanRemoved          += this.Event_GuildBanRemoved;
            this.Client.GuildCreated             += this.Event_GuildCreated;
            this.Client.GuildDeleted             += this.Event_GuildDeleted;
            this.Client.GuildDownloadCompleted   += this.Event_GuildDownloadCompleted;
            this.Client.GuildEmojisUpdated       += this.Event_GuildEmojisUpdated;
            this.Client.GuildIntegrationsUpdated += this.Event_GuildIntegrationsUpdated;
            this.Client.GuildMemberAdded         += this.Event_GuildMemberAdded;
            this.Client.GuildMemberRemoved       += this.Event_GuildMemberRemoved;
            this.Client.GuildMembersChunked      += this.Event_GuildMembersChunked;
            this.Client.GuildMemberUpdated       += this.Event_GuildMemberUpdated;
            this.Client.GuildRoleCreated         += this.Event_GuildRoleCreated;
            this.Client.GuildRoleDeleted         += this.Event_GuildRoleDeleted;
            this.Client.GuildRoleUpdated         += this.Event_GuildRoleUpdated;
            this.Client.GuildUnavailable         += this.Event_GuildUnavailable;
            this.Client.GuildUpdated             += this.Event_GuildUpdated;
            this.Client.Heartbeated                 += this.Event_Heartbeated;
            this.Client.InviteCreated               += this.Event_InviteCreated;
            this.Client.InviteDeleted               += this.Event_InviteDeleted;
            this.Client.MessageAcknowledged         += this.Event_MessageAcknowledged;
            this.Client.MessageCreated              += this.Event_MessageCreated;
            this.Client.MessageDeleted              += this.Event_MessageDeleted;
            this.Client.MessageReactionAdded        += this.Event_MessageReactionAdded;
            this.Client.MessageReactionRemoved      += this.Event_MessageReactionRemoved;
            this.Client.MessageReactionRemovedEmoji += this.Event_MessageReactionRemovedEmoji;
            this.Client.MessageReactionsCleared     += this.Event_MessageReactionsCleared;
            this.Client.MessagesBulkDeleted         += this.Event_MessagesBulkDeleted;
            this.Client.MessageUpdated              += this.Event_MessageUpdated;
            this.Client.PresenceUpdated             += this.Event_PresenceUpdated;
            this.Client.Ready               += this.Event_Ready;
            this.Client.Resumed             += this.Event_Resumed;
            this.Client.SocketClosed        += this.Event_SocketClosed;
            this.Client.SocketErrored       += this.Event_SocketErrored;
            this.Client.SocketOpened        += this.Event_SocketOpened;
            this.Client.TypingStarted       += this.Event_TypingStarted;
            this.Client.UnknownEvent        += this.Event_UnknownEvent;
            this.Client.UserSettingsUpdated += this.Event_UserSettingsUpdated;
            this.Client.UserUpdated         += this.Event_UserUpdated;
            this.Client.VoiceServerUpdated  += this.Event_VoiceServerUpdated;
            this.Client.VoiceStateUpdated   += this.Event_VoiceStateUpdated;
            this.Client.WebhooksUpdated     += this.Event_WebhooksUpdated;

            this.Client.ApplicationCommandCreated += this.Event_ApplicationCommandCreated;
            this.Client.ApplicationCommandDeleted += this.Event_ApplicationCommandDeleted;
            this.Client.ApplicationCommandUpdated += this.Event_ApplicationCommandUpdated;

            this.Client.InteractionCreated += this.Event_InteractionCreated;

            this.Commands.CommandExecuted += this.Event_CommandExecuted;
            this.Commands.CommandErrored  += this.Event_CommandErrored;

            // up next, let's register our commands
            this.Commands.RegisterCommands <Commands>();
            // this.Commands.RegisterCommands<SnappleFacts>();
            this.Commands.RegisterCommands <BotSettings>(); // Main Folder. Test Items.

            // All these commands are in the STARSIEGE folder.
            //if (BotName.Contains("ssp"))
            //{
            this.Commands.RegisterCommands <Quickchat>();
            this.Commands.RegisterCommands <Functions>();
            this.Commands.RegisterCommands <DeathMessages>();
            //}
            Task thisTimer = StartTimer(new CancellationToken());

            // let's enable voice
            this.Voice = this.Client.UseVoiceNext();

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

            // and this is to prevent premature quitting
            await Task.Delay(-1);
        }
Exemplo n.º 23
0
        public async Task Run()
        {
            Log("Server", "Critical", "Savage bot is starting.");

            #region Misc Variables
            Log("Server", "Critical", "Initializing misc. variables.");
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.Title           = "Companion Cube";
            Log("Server", "Critical", "Variables initialized.");
            #endregion Misc Variables

            #region Client Config setup
            Log("Server", "Critical", "Setting up client config.");
            DiscordConfig companion_config = new DiscordConfig
            {
                AutoReconnect         = true,
                DiscordBranch         = Branch.Stable,
                LargeThreshold        = 250,
                LogLevel              = LogLevel.Debug,
                Token                 = "",
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = false
            };
            Log("Server", "Critical", "Loading configs.");
            this.Client = new DiscordClient(companion_config);
            Log("Server", "Critical", "Configs loaded.");
            #endregion Client Config setup

            #region Command Configs and Prefix
            Log("Server", "Critical", "Setting up Commands config and prefix.");
            var CommandConfig = new CommandsNextConfiguration
            {
                StringPrefix = "$",

                EnableMentionPrefix = true,

                EnableDms = false
            };
            this.Commands = this.Client.UseCommandsNext(CommandConfig);
            Log("Server", "Critical", "Commands config loaded.");
            #endregion Command Configs and Prefix

            #region Command Loader
            Log("Server", "Critical", "Loading command classes.");
            //this.Commands.RegisterCommands<>();
            Log("Server", "Critical", "Command classes loaded.");
            #endregion Command Loader

            #region Bot Connection and Task Looping
            Log("Server", "Critical", "Starting bot connection.");
            var discord_conn = new DiscordConnection();
            if (Is_Win_7 == true)
            {
                this.Client.SetWebSocketClient <WebSocket4NetClient>();
            }
            await this.Client.ConnectAsync();

            Log("Server", "Critical", "Bot connected.");
            Log("Server", "Info", "Enjoy your stay.");
            await Task.Delay(-1);

            #endregion Bot Connection and Task Looping
        }
Exemplo n.º 24
0
        public static async Task Start()
        {
            Storage = new GlobalStorage(System.IO.File.ReadAllText("./storage.json"));

            var cfg = new DiscordConfiguration
            {
                Token     = "<REDACTED>",
                TokenType = TokenType.Bot,

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

            Client = new DiscordClient(cfg);

            Client.Ready += async(e) =>
            {
                e.Client.DebugLogger.LogMessage(LogLevel.Info, "Gateway", "Ready Signal Received", DateTime.Now);
                await Task.Delay(0);
            };

            Client.GuildAvailable += async(e) =>
            {
                await Storage.Add(e.Guild);
            };

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

            Commands = Client.UseCommandsNext(ccfg);

            Commands.CommandErrored += async(e) =>
            {
                await e.Context.Message.CreateReactionAsync(DiscordEmoji.FromName(e.Context.Client, ":no_entry:"));

                if (e.Exception.Message != "Specified command was not found.")
                {
                    await e.Context.Channel.SendMessageAsync(null, false, new DiscordEmbedBuilder()
                                                             .WithDescription($"**{e.Exception.Message}**")
                                                             .WithColor(new DiscordColor(0xFF0000))
                                                             .Build());

                    e.Context.Client.DebugLogger.LogMessage(LogLevel.Warning, "Commands", $"Error occured while running command {e.Command.QualifiedName} in guild {e.Context.Guild.Name} ({e.Context.Guild.Id.ToString()}) in channel #{e.Context.Channel.Name} with exception {e.Exception.Message} and stacktrace {e.Exception.StackTrace}", DateTime.Now);
                }
            };

            Commands.RegisterCommands <Commands>();

            //Commands.SetHelpFormatter<HelpFormatter>();

            var icfg = new InteractivityConfiguration();

            Interactivity = Client.UseInteractivity(icfg);

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Exemplo n.º 25
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
            {
                AudioFormat    = AudioFormat.Default,
                EnableIncoming = true
            };

            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();
        }
Exemplo n.º 26
0
        public async Task RunAsync()
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .MinimumLevel.Debug()
                         .CreateLogger();

            var logFactory = new LoggerFactory().AddSerilog();
            var config     = new DiscordConfiguration
            {
                Token         = Configuration.Token,
                TokenType     = TokenType.Bot,
                AutoReconnect = true,
                LoggerFactory = logFactory,
                Intents       = DiscordIntents.All
            };

            Client = new DiscordClient(config);

            Client.Ready          += OnClientReady;
            Client.MessageCreated += OnMessage;

            Client.UseInteractivity(new InteractivityConfiguration
            {
                Timeout            = TimeSpan.FromMinutes(5),
                PollBehaviour      = PollBehaviour.KeepEmojis,
                PaginationDeletion = PaginationDeletion.DeleteMessage
            });

            Services = new ServiceCollection()
                       .AddDbContext <MUNContext>()
                       .AddSingleton(this)
                       .AddSingleton(Configuration)
                       .AddSingleton <Guilds>()
                       .AddSingleton <ProfanityFilterService>()
                       .AddSingleton <PollService>()
                       .BuildServiceProvider();

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

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.SetHelpFormatter <MUNHelp>();

            Commands.RegisterConverter(new ChitConverter());

            Commands.RegisterCommands <ConfigurationModule>();
            Commands.RegisterCommands <GeneralModule>();
            Commands.RegisterCommands <TimerModule>();
            Commands.RegisterCommands <ModerationModule>();
            Commands.RegisterCommands <CountryModule>();
            Commands.RegisterCommands <MotionModule>();
            Commands.RegisterCommands <PointsModule>();

            Commands.CommandErrored += OnError;

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Exemplo n.º 27
0
        public static async Task Run()
        {
            Console.WriteLine("Loading...");
            //instantiate discord object and set config
            var discord = new DiscordClient(new DiscordConfiguration
            {
                AutoReconnect         = true,
                LargeThreshold        = 250,
                Token                 = _keys.Find(a => a.ApiName == "Discord").ApiKey,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = false
            });

            //update console with discord server response
            discord.DebugLogger.LogMessageReceived += (o, e) =>
            {
                Console.WriteLine($"[{e.Timestamp}] [{e.Application}] [{e.Level}] {e.Message}");
            };

            //waits until bot connection is established
            await discord.ConnectAsync();

            PrintConsole("Connected!");

            //updates console with information about current discord guild
            discord.GuildAvailable += e =>
            {
                discord.DebugLogger.LogMessage(LogLevel.Info, "discord bot", $"Guild available: {e.Guild.Name}", DateTime.Now);
                return(Task.Delay(0));
            };

            //responds to discord message "ping" with discord message "pong"
            //used to check that bot has connected to the discord server, logged in, and responsive
            discord.MessageCreated += async e =>
            {
                if (e.Message.Content.ToLower() == "ping")
                {
                    await Respond(e, "pong");
                }
            };


            //set command config
            var ccfg = new CommandsNextConfiguration
            {
                StringPrefix        = "!",
                SelfBot             = false,
                CaseSensitive       = false,
                EnableMentionPrefix = true,
                EnableDefaultHelp   = true
            };

            Commands = discord.UseCommandsNext(ccfg);

            //report command events to console
            Commands.CommandExecuted += Commands_CommandExecuted;
            Commands.CommandErrored  += Commands_CommandErrored;

            //commands

            Commands.RegisterCommands <CommandLoader>();

            //keeps the project running
            await Task.Delay(-1);
        }
Exemplo n.º 28
0
        public Bot(ConfigJson cfg, int shardid)
        {
            // then we want to instantiate our client
            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"
            };

            this.Client = new DiscordClient(dcfg);


            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
                StringPrefixes = this.Config.CommandPrefix,

                // enable responding in direct messages
                EnableDms = true,

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

            // and hook them up
            this.CommandsNextService = this.Client.UseCommandsNext(ccfg);
            this.CommandsNextService.CommandExecuted += this.Commands_CommandExecuted;
            this.CommandsNextService.CommandErrored  += this.Commands_CommandErrored;
            this.Client.GuildBanAdded    += this.Ban;
            this.Client.GuildBanRemoved  += this.Unban;
            this.Client.GuildMemberAdded += this.NewMember;
            System.Threading.Thread liveChecker = new System.Threading.Thread(async e => await CheckLive(this.Client));
            liveChecker.Start();
            // let's add a converter for a custom type and a name

            //general (ping)
            this.CommandsNextService.RegisterCommands <ExampleUngrouppedCommands>();
            //MyAnimeList Commands
            //this.CommandsNextService.RegisterCommands<MyAnimeListCommands>();
            //Programmation
            //this.CommandsNextService.RegisterCommands<Programmation>();

            //Check member
            //this.Commands.RegisterCommands<MemberCheck>();

            /*  //Check nouveaux mambres
             *          var memberTimer = new System.Threading.Timer(
             *              async e => await CheckMember(this.Client), null, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(10));
             */
        }
Exemplo n.º 29
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);
        }
Exemplo n.º 30
0
        public static async Task Main(String[] args)
        {
            //run command line parser
            Parser.Default.ParseArguments <CommandLineOptions>(args)
            .WithParsed(o =>
            {
                CommandLineOptions = o;
            });


            // initialize datafixers
#if DEBUG
            DatafixerLogger.MinimalLevel = Helium.Commons.Logging.LogLevel.Debug;
#else
            DatafixerLogger.MinimalLevel = Helium.Commons.Logging.LogLevel.Warning;
#endif

            DataFixerLower.Initialize(0); //this can be switched out for 1 if you need to, insanitybot default is 0
            RegisterDatafixers();

            //load main config
            ConfigManager   = new MainConfigurationManager();
            LanguageManager = new LanguageConfigurationManager();
            LoggerManager   = new LoggerConfigurationManager();

            //read config from file
            Config = ConfigManager.Deserialize("./config/main.json");

            //validate token and guild id
            #region token
            if (String.IsNullOrWhiteSpace(Config.Token))
            {
                if (!CommandLineOptions.Interactive)
                {
                    System.Console.WriteLine("Invalid Token. Please provide a valid token in .\\config\\main.json" +
                                             "\nPress any key to continue...");
                    System.Console.ReadKey();
                    return;
                }

                System.Console.Write("Your config does not contain a token. To set a token now, paste your token here. " +
                                     "To abort and exit InsanityBot, type \"cancel\"\nToken: ");
                String token = System.Console.ReadLine();

                if (token.ToLower().Trim() == "cancel")
                {
                    System.Console.WriteLine("Operation aborted, exiting InsanityBot.\nPress any key to continue...");
                    System.Console.ReadKey();
                    return;
                }

                Config.Token = token;
                ConfigManager.Serialize(Config, "./config/main.json");
            }

            if (Config.GuildId == 0)
            {
                if (!CommandLineOptions.Interactive)
                {
                    System.Console.WriteLine("Invalid GuildId. Please provide a valid guild ID in .\\config\\main.json" +
                                             "\nPress any key to continue...");
                    System.Console.ReadKey();
                    return;
                }

                System.Console.Write("Your config does not contain a valid guild ID. To set a guild ID now, paste your guild ID here. " +
                                     "To abort and exit InsanityBot, type \"cancel\"\nGuild ID: ");
                String guildId = System.Console.ReadLine();

                if (guildId.ToLower().Trim() == "cancel")
                {
                    System.Console.WriteLine("Operation aborted, exiting InsanityBot.\nPress any key to continue...");
                    System.Console.ReadKey();
                    return;
                }

                if (UInt64.TryParse(guildId, out UInt64 id))
                {
                    Config.GuildId = id;
                    ConfigManager.Serialize(Config, "./config/main.json");
                }
                else
                {
                    System.Console.WriteLine("The provided guild ID could not be parsed. Aborting and exiting InsanityBot.\n" +
                                             "Press any key to continue...");
                    System.Console.ReadKey();
                    return;
                }
            }
            #endregion

            LanguageConfig = LanguageManager.Deserialize("./config/lang.json");
            LoggerConfig   = LoggerManager.Deserialize("./config/logger.json");

            LoggerFactory loggerFactory = new();
            EmbedFactory = new();


            //create discord config; increase the cache size if you want though itll take more RAM
            ClientConfiguration = new DiscordConfiguration
            {
                AutoReconnect    = true,
                Token            = Config.Token,
                TokenType        = TokenType.Bot,
                MessageCacheSize = 4096,
                LoggerFactory    = loggerFactory,
                HttpTimeout      = new(00, 00, 30)
            };

            //create and connect client
            Client = new DiscordClient(ClientConfiguration);
            await Client.ConnectAsync();

            Client.Logger.LogInformation(new EventId(1000, "Main"), $"InsanityBot Version {Version}");

            //load perms
            PermissionEngine = Client.InitializeEngine(new PermissionConfiguration
            {
                PrecompiledScripts    = true,
                UpdateRolePermissions = true,
                UpdateUserPermissions = true
            });

            try
            {
                //create home guild so commands can use it
                HomeGuild = await Client.GetGuildAsync(Convert.ToUInt64(Config.GuildId));
            }
            catch (UnauthorizedException)
            {
                Client.Logger.LogCritical(new EventId(0000, "Main"),
                                          "Your GuildId is either invalid or InsanityBot has not been invited to the server yet.");
            }
            catch
            {
                throw;
            }

            //load command configuration
            CommandConfiguration = new CommandsNextConfiguration
            {
                CaseSensitive        = false,
                StringPrefixes       = Config.Prefixes,
                DmHelp               = (Boolean)Config["insanitybot.commands.help.send_dms"],
                IgnoreExtraArguments = true
            };

            //create and register command client
            Client.UseCommandsNext(CommandConfiguration);
            CommandsExtension = Client.GetCommandsNext();

            PaginationEmojis InteractivityPaginationEmotes = new();
            if (ToUInt64(Config["insanitybot.identifiers.interactivity.scroll_right_emote_id"]) != 0)
            {
                InteractivityPaginationEmotes.Right = HomeGuild.Emojis[ToUInt64(Config["insanitybot.identifiers.interactivity.scroll_right_emote_id"])];
            }

            if (ToUInt64(Config["insanitybot.identifiers.interactivity.scroll_left_emote_id"]) != 0)
            {
                InteractivityPaginationEmotes.Left = HomeGuild.Emojis[ToUInt64(Config["insanitybot.identifiers.interactivity.scroll_left_emote_id"])];
            }

            if (ToUInt64(Config["insanitybot.identifiers.interactivity.skip_right_emote_id"]) != 0)
            {
                InteractivityPaginationEmotes.SkipRight = HomeGuild.Emojis[ToUInt64(Config["insanitybot.identifiers.interactivity.skip_right_emote_id"])];
            }

            if (ToUInt64(Config["insanitybot.identifiers.interactivity.skip_left_emote_id"]) != 0)
            {
                InteractivityPaginationEmotes.SkipLeft = HomeGuild.Emojis[ToUInt64(Config["insanitybot.identifiers.interactivity.skip_left_emote_id"])];
            }

            if (ToUInt64(Config["insanitybot.identifiers.interactivity.stop_emote_id"]) != 0)
            {
                InteractivityPaginationEmotes.Stop = HomeGuild.Emojis[ToUInt64(Config["insanitybot.identifiers.interactivity.stop_emote_id"])];
            }

            Interactivity = Client.UseInteractivity(new()
            {
                PaginationBehaviour = PaginationBehaviour.Ignore,
                PaginationDeletion  = PaginationDeletion.DeleteEmojis,
                PaginationEmojis    = InteractivityPaginationEmotes
            });

            CommandsExtension.CommandErrored += CommandsExtension_CommandErrored;

            //start timer framework
            TimeHandler.Start();

            //register commands and events
            RegisterAllCommands();
            RegisterAllEvents();

            //initialize various parts of InsanityBots framework
            InitializeAll();

            Client.Logger.LogInformation(new EventId(1000, "Main"), $"Startup successful!");

            //start offthread TCP connection
            _ = HandleTCPConnections((Int64)Config["insanitybot.tcp_port"]);

            //start offthread XP management
            // if ((Boolean)Config["insanitybot.modules.experience"])
            ; // not implemented yet

            //start integrated offthread console management - cannot disable
            _ = Task.Run(() => { IntegratedCommandHandler.Initialize(); });

            //start offthread console management
            // if ((Boolean)Config["insanitybot.modules.console"])
            ; // not implemented yet

            //abort main thread, who needs it anyway
            Thread.Sleep(-1);
        }