Пример #1
0
        public Bot(Settings settings)
        {
            this.Settings = settings;
            ProgramStart  = DateTimeOffset.Now;
            Client        = new DiscordClient(new DiscordConfiguration
            {
                AutoReconnect         = true,
                EnableCompression     = true,
                LogLevel              = LogLevel.Debug,
                Token                 = settings.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true
            });

            Interactivity = Client.UseInteractivity();

            var deps = new DependencyCollectionBuilder().AddInstance(this).Build();

            Commands = Client.UseCommandsNext(new CommandsNextConfiguration
            {
                CaseSensitive       = false,
                EnableDefaultHelp   = true,
                EnableDms           = false,
                EnableMentionPrefix = true,
                StringPrefix        = settings.Prefix,
                Dependencies        = deps
            });

            Commands.RegisterCommands <Main>();
            Commands.RegisterCommands <Owner>();

            CTS = new CancellationTokenSource();

            Client.SocketOpened += async() =>
            {
                await Task.Yield();

                SocketStart = DateTimeOffset.Now;
            };

            Commands.CommandErrored += async e =>
            {
                e.Context.Client.DebugLogger.LogMessage(LogLevel.Critical, "Commands", e.Exception.ToString(), DateTime.Now);
            };

            AsyncListenerHandler.InstallListeners(Client, this);
        }
Пример #2
0
        internal void Initialize()
        {
            // Store the Start Times to use in DI
            // SocketStartTime will be updated in the SocketOpened event,
            // For now we just need to make sure its not null.
            StartTimes = new StartTimes(SharedData.ProcessStartTime, SharedData.ProcessStartTime);

            // Initialize the DiscordClient
            var cfg = new DiscordConfiguration
            {
                AutoReconnect           = true,
                GatewayCompressionLevel = GatewayCompressionLevel.Stream,
                LargeThreshold          = 250,
                LogLevel              = LogLevel.Debug,
                Token                 = Settings.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                ShardCount            = this.Settings.ShardCount,
                ShardId               = this.ShardId
            };

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Environment.OSVersion.Version <= new Version(6, 1, 7601, 65536))
            {
                // NT 6.1 (Win7 SP1)
                cfg.WebSocketClientFactory = WebSocket4NetCoreClient.CreateNew;
            }
            this.Client = new DiscordClient(cfg);

            Client.ClientErrored += async args =>
            {
                await Task.Yield();

                Console.WriteLine(args.Exception);
            };

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

            // Add the instances we need to dependencies
            var deps = new ServiceCollection()
                       .AddSingleton(this.SharedData)
                       //.AddInstance(this.Settings)
                       .AddSingleton(this.Interactivity)
                       .AddSingleton(this.StartTimes)
                       .AddSingleton(this.Database)
                       .BuildServiceProvider();

            // enable commandsnext
            this.Commands = Client.UseCommandsNext(new CommandsNextConfiguration
            {
                CaseSensitive       = false,
                EnableDefaultHelp   = true,
                EnableDms           = false,
                EnableMentionPrefix = true,
                PrefixResolver      = this.GetPrefixPositionAsync,
                Services            = deps,
            });

            // set the converters
            this.Commands.RegisterConverter(new AugmentedBoolConverter());
            this.Commands.RegisterConverter(new CustomDiscordMessageConverter());

            // register commands
            this.Commands.RegisterCommands(Assembly.GetExecutingAssembly());

            foreach (var c in this.Commands.RegisteredCommands)
            {
                var reqperm = c.Value.ExecutionChecks.Where(x => x.GetType() == typeof(RequirePermissionsAttribute));
                foreach (RequirePermissionsAttribute att in reqperm)
                {
                    if (!SharedData.AllPerms.Contains(att.Permissions))
                    {
                        SharedData.AllPerms.Add(att.Permissions);
                    }
                }
                var requsrperm = c.Value.ExecutionChecks.Where(x => x.GetType() == typeof(RequireBotPermissionsAttribute));
                foreach (RequireBotPermissionsAttribute att in requsrperm)
                {
                    if (!SharedData.AllPerms.Contains(att.Permissions))
                    {
                        SharedData.AllPerms.Add(att.Permissions);
                    }
                }
            }

            // Update the SocketStartTime
            this.Client.SocketOpened += async() =>
            {
                await Task.Yield();

                StartTimes.SocketStartTime = DateTime.Now;
            };

            // register event handlers
            this.Client.Ready += Client_Ready;

            AsyncListenerHandler.InstallListeners(Client, this);
        }
Пример #3
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);
        }