示例#1
0
        public BotClient()
        {
            LoadConfig();

            discord = new DiscordClient(new DiscordConfiguration
            {
                Token     = Config.Token,
                TokenType = TokenType.Bot,

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

            // Set up commands
            var dependencyBuilder = new DependencyCollectionBuilder();

            dependencyBuilder.AddInstance(this);

            commands = discord.UseCommandsNext(new CommandsNextConfiguration()
            {
                StringPrefix = Config.CommandPrefix,
                Dependencies = dependencyBuilder.Build()
            });

            commands.RegisterCommands <BasicCommands>();
            commands.RegisterCommands <AdminCommands>();

            // Set up error handlers
            discord.Ready += (e) =>
            {
                e.Client.DebugLogger.LogMessage(LogLevel.Info, "AwfulBot", "Client started successfully.", DateTime.Now);
                return(Task.CompletedTask);
            };
            discord.ClientErrored += (e) =>
            {
                e.Client.DebugLogger.LogMessage(LogLevel.Error, "AwfulBot",
                                                $"Exception occured: {e.Exception.GetType()}: {e.Exception.Message}", DateTime.Now);
                return(Task.CompletedTask);
            };
            commands.CommandExecuted += (e) =>
            {
                e.Context.Client.DebugLogger.LogMessage(LogLevel.Info, "AwfulBot",
                                                        $"{e.Context.User.Username} executed '{e.Command.QualifiedName}'", DateTime.Now);
                return(Task.CompletedTask);
            };
            commands.CommandErrored += (e) =>
            {
                e.Context.Client.DebugLogger.LogMessage(LogLevel.Error, "AwfulBot",
                                                        $"{e.Context.User.Username} tried executing '{e.Command?.QualifiedName ?? "<unknown command>"}' but it failed: {e.Exception.GetType()}: {e.Exception.Message ?? "<no message>"}",
                                                        DateTime.Now);
                return(Task.CompletedTask);
            };

            // Disconnect on exit
            AppDomain.CurrentDomain.ProcessExit += async(sender, e) =>
            {
                await this.Stop();
            };
        }
示例#2
0
        private DependencyCollection BuildDeps()
        {
            using var deps = new DependencyCollectionBuilder();

            deps.AddInstance(_provider).AddInstance(_service);

            return(deps.Build());
        }
示例#3
0
 private DependencyCollection BuildDependancies()
 {
     using var dc = new DependencyCollectionBuilder();
     dc.AddInstance(subHandler)
     .AddInstance(pageChecker)
     .AddInstance(config);
     return(dc.Build());
 }
示例#4
0
文件: Bot.cs 项目: soleng-exp/DBot
        public Bot()
        {
            if (!File.Exists("config.json"))
            {
                configNotFound();
            }
            _config = Config.LoadFromFile("config.json");

            _discord = new DiscordClient(new DiscordConfiguration()
            {
                AutoReconnect         = true,
                EnableCompression     = true,
                LogLevel              = LogLevel.Debug,
                Token                 = _config.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true
            });

            _cts           = new CancellationTokenSource();
            _interactivity = _discord.UseInteractivity(new InteractivityConfiguration());

            ////
            DependencyCollection dep = null;

            using (var d = new DependencyCollectionBuilder())
            {
                d.AddInstance(new Dependencies()
                {
                    Interactivity = _interactivity,
//                    StartTimes = _starttimes,
                    Cts = _cts
                });
                dep = d.Build();
            }
            ///

            _commands = _discord.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefix         = _config.Prefix,
                EnableDms            = false,
                Dependencies         = dep,
                IgnoreExtraArguments = true,
                EnableDefaultHelp    = true,
                CaseSensitive        = false,
                EnableMentionPrefix  = true,
            });
            _commands.RegisterCommands <Generals>();
            _commands.RegisterCommands <Owner>();

            ///
            _discord.MessageCreated += async e =>
            {
                if (e.Message.Content.ToLower().StartsWith("ping"))
                {
                    await e.Message.RespondAsync("pong!");
                }
            };
        }
示例#5
0
        /*
         * DSharpPlus has dependancy injection for commands, this builds a list of dependancies.
         * We can then access these in our command modules.
         */
        private DependencyCollection BuildDeps()
        {
            using var deps = new DependencyCollectionBuilder();

            deps.AddInstance(_interactivity) // Add interactivity
            .AddInstance(_cts)               // Add the cancellation token
            .AddInstance(_config)            // Add our config
            .AddInstance(_discord);          // Add the discord client

            return(deps.Build());
        }
示例#6
0
        private DependencyCollection BuildDependencies()
        {
            using var deps = new DependencyCollectionBuilder();

            deps.AddInstance(_interactivity)
            .AddInstance(Cts)
            .AddInstance(_config)
            .AddInstance(_discord);

            return(deps.Build());
        }
示例#7
0
        private DependencyCollection BuildDeps()
        {
            using var deps = new DependencyCollectionBuilder();

            deps.AddInstance(_interactivity)
            .AddInstance(_cancellationToken)
            .AddInstance(_configuration)
            .AddInstance(_discordClient)
            .AddInstance(_wargamingApi);

            return(deps.Build());
        }
示例#8
0
        public CommandsNextConfiguration GetCommandsNextConfiguration()
        {
            var deps = new DependencyCollectionBuilder()
                       .AddInstance(_config)
                       .Build();

            return(new CommandsNextConfiguration
            {
                StringPrefix = _config.Get().Bot.CommandPrefix,
                Dependencies = deps,
            });
        }
示例#9
0
        private CommandsNextConfiguration GetCommandsNextConfiguration()
        {
            using var builder = new DependencyCollectionBuilder();
            builder.AddInstance(_serviceProvider.GetService <IHttpClientFactory>());

            return(new CommandsNextConfiguration
            {
                StringPrefix = "v!",
                EnableMentionPrefix = true,
                EnableDms = true,
                CaseSensitive = false,
                EnableDefaultHelp = true,
                IgnoreExtraArguments = false,
                Dependencies = builder.Build()
            });
        }
示例#10
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);
        }
示例#11
0
        private async Task InitAsync()
        {
            DiscordClient = new DiscordClient(new DiscordConfiguration
            {
                Token     = _configuration[Constants.DiscordBotTokenKey],
                TokenType = TokenType.Bot
            });

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

            DiscordClient.MessageCreated += DiscordClient_MessageCreated;

            var commands = DiscordClient.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefix  = ";;",
                Dependencies  = d,
                CaseSensitive = false
            });

            commands.RegisterCommands <DiscordBotCommands>();

            var discordTask = DiscordClient.ConnectAsync();

            using (var context = _dbContextFactory.Create <ApplicationDbContext>())
            {
                foreach (var ds in context.DiscordServers)
                {
                    discordToServer[ds.DiscordChannelId] = ds.ServerId;
                    serverdToDiscord[ds.ServerId]        = ds.DiscordChannelId;
                }
            }

            messageQueue = new SingleConsumerQueue <DiscordMessage>(async m =>
            {
                try
                {
                    await DiscordClient.SendMessageAsync(m.Channel, m.Content, false, m.Embed);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "messageQueue consumer");
                }
            });

            await discordTask;
        }
示例#12
0
        private void SetCommands()
        {
            DependencyCollection dep = null;

            using (var d = new DependencyCollectionBuilder())
            {
                d.AddInstance(new Dependencies()
                {
                    SankakuBot  = this._sankakuBot,
                    WaifuJoiBot = this._waifujoiBot
                });
                dep = d.Build();
            }

            var ccfg = new CommandsNextConfiguration()
            {
                CaseSensitive        = false,
                EnableDefaultHelp    = true,
                EnableDms            = false,
                EnableMentionPrefix  = true,
                IgnoreExtraArguments = true,
                StringPrefix         = Prefix,
                Dependencies         = dep
            };

            this._context = new DiscordContext();
            this.Commands = this._client.UseCommandsNext(ccfg);

            foreach (Type type in Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsClass && t.Namespace == "Sabrina.Commands" && t.DeclaringType == null))
            {
                if (type == null || type.Name == "BlackJackGame" || type.IsAbstract || type.FullName == "Sabrina.Commands.Edges+<AssignEdgesAsync>d__2") //Really shitty solution, but im lazy
                {
                    continue;
                }
                var info = type.GetTypeInfo();
                this.Commands.RegisterCommands(type);
            }
        }
示例#13
0
        private void Startup()
        {
            try
            {
                using var deps = new DependencyCollectionBuilder()
                                 .AddInstance(_interactivity)
                                 .AddInstance(_client);

                var commands = _client.UseCommandsNext(new CommandsNextConfiguration
                {
                    StringPrefix = _settings.CommandPrefix,
                    Dependencies = deps.Build()
                });

                _logger.LogInformation("[info] Loading command modules..");

                var type  = typeof(ICommand);
                var types = AppDomain.CurrentDomain.GetAssemblies()
                            .SelectMany(s => s.GetTypes())
                            .Where(p => type.IsAssignableFrom(p) && !p.IsInterface);

                var typeList = types as Type[] ?? types.ToArray(); // Convert to an array
                foreach (var t in typeList)
                {
                    commands.RegisterCommands(t); // Loop through the list and register each command module with CommandsNext
                }
                _logger.LogInformation($"[info] Loaded {typeList.Count()} modules.");
            }
            catch (Exception ex)
            {
                // This will catch any exceptions that occur during the operation/setup of your bot.

                // Feel free to replace this with what ever logging solution you'd like to use.
                // I may do a guide later on the basic logger I implemented in my most recent bot.
                Console.Error.WriteLine(ex.ToString());
            }
        }
示例#14
0
文件: Bot.cs 项目: kbtbc/Brock-WhMgr
        public Bot(WhConfig whConfig, string alarmsFilePath)
        {
            _logger.Trace($"WhConfig={whConfig.Discord.GuildId}, OwnerId={whConfig.Discord.OwnerId}, GuildId={whConfig.Discord.GuildId}, WebhookPort={whConfig.WebhookPort}");
            _lang     = new Translator();
            _whConfig = whConfig;
            DataAccessLayer.ConnectionString        = _whConfig.ConnectionStrings.Main;
            DataAccessLayer.ScannerConnectionString = _whConfig.ConnectionStrings.Scanner;

            AppDomain.CurrentDomain.UnhandledException += async(sender, e) =>
            {
                _logger.Debug("Unhandled exception caught.");
                _logger.Error((Exception)e.ExceptionObject);

                if (e.IsTerminating)
                {
                    if (_client != null)
                    {
                        var owner = await _client.GetUserAsync(_whConfig.Discord.OwnerId);

                        if (owner == null)
                        {
                            _logger.Warn($"Failed to get owner from id {_whConfig.Discord.OwnerId}.");
                            return;
                        }

                        await _client.SendDirectMessage(owner, Strings.CrashMessage, null);
                    }
                }
            };

            _gyms = new Dictionary <string, GymDetailsData>();

            _whm = new WebhookManager(_whConfig, alarmsFilePath);
            _whm.PokemonAlarmTriggered    += OnPokemonAlarmTriggered;
            _whm.RaidAlarmTriggered       += OnRaidAlarmTriggered;
            _whm.QuestAlarmTriggered      += OnQuestAlarmTriggered;
            _whm.PokestopAlarmTriggered   += OnPokestopAlarmTriggered;
            _whm.GymAlarmTriggered        += OnGymAlarmTriggered;
            _whm.GymDetailsAlarmTriggered += OnGymDetailsAlarmTriggered;
            _whm.WeatherAlarmTriggered    += OnWeatherAlarmTriggered;
            if (_whConfig.Discord.EnableSubscriptions)
            {
                _whm.PokemonSubscriptionTriggered  += OnPokemonSubscriptionTriggered;
                _whm.RaidSubscriptionTriggered     += OnRaidSubscriptionTriggered;
                _whm.QuestSubscriptionTriggered    += OnQuestSubscriptionTriggered;
                _whm.InvasionSubscriptionTriggered += OnInvasionSubscriptionTriggered;
            }

            _logger.Info("WebhookManager is running...");

            var midnight = new DandTSoftware.Timers.MidnightTimer();

            midnight.TimeReached += async(e) => await ResetQuests();

            midnight.Start();

            _client = new DiscordClient(new DiscordConfiguration
            {
                AutomaticGuildSync = true,
                AutoReconnect      = true,
                EnableCompression  = true,
                Token                 = _whConfig.Discord.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true
            });
            _client.Ready += Client_Ready;
            //_client.MessageCreated += Client_MessageCreated;
            _client.ClientErrored += Client_ClientErrored;
            _client.DebugLogger.LogMessageReceived += DebugLogger_LogMessageReceived;

            _interactivity = _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),     //TODO: Set prod

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

            if (_whConfig.Discord.EnableSubscriptions)
            {
                _subProcessor = new SubscriptionProcessor(_client, _whConfig, _whm);
            }

            DependencyCollection dep;

            using (var d = new DependencyCollectionBuilder())
            {
                d.AddInstance(_dep = new Dependencies(_interactivity, _whm, _subProcessor, _whConfig, _lang, new StripeService(_whConfig.StripeApiKey)));
                dep = d.Build();
            }

            _commands = _client.UseCommandsNext
                        (
                new CommandsNextConfiguration
            {
                StringPrefix         = _whConfig.Discord.CommandPrefix?.ToString(),
                EnableDms            = true,
                EnableMentionPrefix  = string.IsNullOrEmpty(_whConfig.Discord.CommandPrefix),
                EnableDefaultHelp    = false,
                CaseSensitive        = false,
                IgnoreExtraArguments = true,
                Dependencies         = dep
            }
                        );
            _commands.CommandExecuted += Commands_CommandExecuted;
            _commands.CommandErrored  += Commands_CommandErrored;
            _commands.RegisterCommands <Owner>();
            _commands.RegisterCommands <CommunityDay>();
            _commands.RegisterCommands <Nests>();
            _commands.RegisterCommands <ShinyStats>();
            _commands.RegisterCommands <Gyms>();
            _commands.RegisterCommands <Quests>();
            if (_whConfig.Discord.EnableSubscriptions)
            {
                _commands.RegisterCommands <Notifications>();
            }
            if (_whConfig.Discord.EnableCities)
            {
                _commands.RegisterCommands <Feeds>();
            }
        }
示例#15
0
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            Log.Information("Provisioning Services");
            _httpClient = new HttpClient();

            Log.Information("Configuring Discord client");
            var _dService = new Services(_config);


            var _dBuilder = new DependencyCollectionBuilder();

            _dBuilder.AddInstance <Services>(_dService);
            _dBuilder.AddInstance <IConfiguration>(_config);

            (_discord, _commands) = _dService.CreateDiscordClient(_dBuilder.Build());

            _commands.RegisterCommands <MessageCommands>();
            _commands.RegisterCommands <AttachmentCommands>();

            #region processors

            var _processors = new Processors(_config, _dService, _supportChannel);

            _discord.MessageCreated += async e =>
            {
                if (e.Message.Attachments != null && e.Message.Attachments.Any())
                {
                    await _processors.ProcessWithOCR(_discord, e);
                }
            };
            #endregion

            #region reactions

            var _reactionsWorker = new ReactionCommands(_config, _dService);

            _discord.MessageReactionAdded += async e =>
            {
                await _reactionsWorker.RunCommand_Reaction(_discord, e, _supportChannel);
            };

            #endregion

            _discord.ConnectAsync();

            var _assemblyVersion = typeof(Worker).Assembly.GetCustomAttribute <AssemblyFileVersionAttribute>().Version;

            // setup support channels
            try
            {
                var _supportUserId = _config["Discord:SupportUser"];
                var _supportUser   = _discord.GetUserAsync(ulong.Parse(_supportUserId)).Result;

                _supportChannel = _discord.CreateDmAsync(_supportUser).Result;
                _supportChannel.SendMessageAsync($"I'm alive! Now running version {_assemblyVersion}");
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error setting up support channels");
            }

            return(base.StartAsync(cancellationToken));
        }
示例#16
0
        static async Task MainAsync(string[] args)
        {
            Console.WriteLine(Directory.GetCurrentDirectory());
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("settings.json", optional: true, reloadOnChange: true).Build();

            var discordToken   = builder["Discord:Token"].ToString();
            var challongeToken = builder["Challonge:Token"].ToString();
            var restUrl        = builder["REST:Url"].ToString();
            var restUser       = builder["REST:User"].ToString();
            var restPassword   = builder["REST:Password"].ToString();

            Console.WriteLine($"LaDOSE.Net Discord Bot");


            discord = new DiscordClient(new DiscordConfiguration
            {
                Token     = discordToken,
                TokenType = TokenType.Bot
            });

            discord.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)
            });
            var webService = new WebService(new Uri(restUrl), restUser, restPassword);
            //var challongeService = new ChallongeService(challongeToken);

            var cts = new CancellationTokenSource();
            DependencyCollection dep = null;

            using (var d = new DependencyCollectionBuilder())
            {
                d.AddInstance(new Dependencies()
                {
                    Cts = cts,
                    //ChallongeService = challongeService,
                    WebService = webService
                });
                dep = d.Build();
            }

            var _cnext = discord.UseCommandsNext(new CommandsNextConfiguration()
            {
                CaseSensitive        = false,
                EnableDefaultHelp    = true,
                EnableDms            = false,
                EnableMentionPrefix  = true,
                StringPrefix         = "!",
                IgnoreExtraArguments = true,
                Dependencies         = dep
            });

            _cnext.RegisterCommands <Result>();
            _cnext.RegisterCommands <Twitch>();
            _cnext.RegisterCommands <Shutdown>();
            _cnext.RegisterCommands <Todo>();
            _cnext.RegisterCommands <Hokuto>();


            //discord.MessageCreated += async e =>
            //{
            //    if (e.Message.Content.ToLower().Equals("!result"))
            //        await e.Message.RespondAsync("Les Résultats du dernier Ranking : XXXX");
            //    if (e.Message.Content.ToLower().Equals("!twitch"))
            //        await e.Message.RespondAsync("https://www.twitch.tv/LaDOSETV");
            //};

            discord.GuildMemberAdded += async e =>
            {
                Console.WriteLine($"{e.Member.DisplayName} Joined");
                await Task.Delay(0);

                //await e.Guild.GetDefaultChannel().SendMessageAsync($"Bonjour!");
            };
            await discord.ConnectAsync();

            while (!cts.IsCancellationRequested)
            {
                await Task.Delay(200);
            }
        }
示例#17
0
        private static async Task Order66()
        {
            KeyManager = new KeyManager("keystore.json");
            if (!KeyManager.HasKey("pgmain"))
            {
                KeyManager.AddKey("pgmain", 256);
            }

            var l = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            GuildEmoji = new DeviGuildEmojiMap(new Dictionary <string, string>());

            var stx = Path.Combine(l, "devi.json");
            var emx = Path.Combine(l, "emoji.json");
            var dgx = Path.Combine(l, "donger.json");

            if (File.Exists(stx) && File.Exists(emx) && File.Exists(dgx))
            {
                stx      = File.ReadAllText(stx, new UTF8Encoding(false));
                Settings = JsonConvert.DeserializeObject <DeviSettingStore>(stx);
            }
            else
            {
                throw new FileNotFoundException("Unable to load configuration file (devi.json)!");
            }

            DatabaseClient = new DeviDatabaseClient(Settings.DatabaseSettings, KeyManager);
            await DatabaseClient.PreconfigureAsync();

            if (File.Exists(emx))
            {
                emx = File.ReadAllText(emx, new UTF8Encoding(false));
                var edict = JsonConvert.DeserializeObject <Dictionary <string, string> >(emx);
                EmojiMap = new DeviEmojiMap(edict);
            }
            else
            {
                EmojiMap = new DeviEmojiMap(new Dictionary <string, string>());
            }

            if (File.Exists(dgx))
            {
                dgx     = File.ReadAllText(dgx, new UTF8Encoding(false));
                Dongers = JsonConvert.DeserializeObject <DeviDongerMap>(dgx);
                Dongers.HookAliases();
            }
            else
            {
                Dongers = new DeviDongerMap()
                {
                    Dongers = new Dictionary <string, string>(),
                    Aliases = new Dictionary <string, List <string> >()
                };
            }

            Utilities = new DeviUtilities();
            Http      = new HttpClient();

            var discord = new DiscordClient(new DiscordConfig()
            {
                LogLevel           = LogLevel.Debug,
                Token              = Settings.Token,
                TokenType          = TokenType.User,
                MessageCacheSize   = Settings.CacheSize,
                AutomaticGuildSync = false
            });

            DeviClient = discord;

            var depb = new DependencyCollectionBuilder();
            var deps = depb.AddInstance(Settings)
                       .AddInstance(EmojiMap)
                       .AddInstance(Dongers)
                       .AddInstance(GuildEmoji)
                       .AddInstance(DatabaseClient)
                       .AddInstance(Utilities)
                       .AddInstance(Http)
                       .AddInstance(Settings.CryptoSettings)
                       .AddInstance(KeyManager)
                       .Add <CryptonatorApiClient>()
                       .Add <NanopoolApiClient>()
                       .Build();

            CommandsNextUtilities.RegisterConverter(new CryptoCurrencyCodeConverter());

            var commands = discord.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefix        = Settings.Prefix,
                SelfBot             = true,
                EnableDefaultHelp   = false,
                EnableMentionPrefix = false,
                Dependencies        = deps
            });

            DeviCommands = commands;
            DeviCommands.CommandErrored += DeviCommands_CommandErrored;
            DeviCommands.RegisterCommands <DeviCommandModule>();
            DeviCommands.RegisterCommands <DeviLogManagementModule>();
            DeviCommands.RegisterCommands <DeviCryptomarketCommands>();

            DeviMessageTracker = new List <DiscordMessage>();

            discord.GuildAvailable      += Discord_GuildAvailable;
            discord.MessageCreated      += Discord_MessageReceived;
            discord.MessageUpdated      += Discord_MessageUpdate;
            discord.MessageDeleted      += Discord_MessageDelete;
            discord.MessagesBulkDeleted += Discord_MessageBulkDelete;
            discord.Ready += Discord_Ready;
            discord.DebugLogger.LogMessageReceived += Discord_Log;
            discord.MessageReactionAdded           += Discord_ReactionAdded;
            discord.MessageReactionRemoved         += Discord_ReactionRemoved;
            discord.ClientErrored += Discord_ClientError;

            await discord.ConnectAsync();

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

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

            Discord = new DiscordClient(dcfg);

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

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

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

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

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

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

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

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

            this.InteractivityService = Discord.UseInteractivity(icfg);
        }
示例#19
0
文件: Bot.cs 项目: CloudHolic/Namazuo
        public Bot()
        {
            if (!File.Exists("config.json"))
            {
                new Config().SaveToFile("config.json");
                #region !! Report to user that config has not been set yet !! (aesthetics)
                Console.BackgroundColor = ConsoleColor.Red;
                Console.ForegroundColor = ConsoleColor.Black;
                WriteCenter("▒▒▒▒▒▒▒▒▒▄▄▄▄▒▒▒▒▒▒▒", 2);
                WriteCenter("▒▒▒▒▒▒▄▀▀▓▓▓▀█▒▒▒▒▒▒");
                WriteCenter("▒▒▒▒▄▀▓▓▄██████▄▒▒▒▒");
                WriteCenter("▒▒▒▄█▄█▀░░▄░▄░█▀▒▒▒▒");
                WriteCenter("▒▒▄▀░██▄░░▀░▀░▀▄▒▒▒▒");
                WriteCenter("▒▒▀▄░░▀░▄█▄▄░░▄█▄▒▒▒");
                WriteCenter("▒▒▒▒▀█▄▄░░▀▀▀█▀▒▒▒▒▒");
                WriteCenter("▒▒▒▄▀▓▓▓▀██▀▀█▄▀▀▄▒▒");
                WriteCenter("▒▒█▓▓▄▀▀▀▄█▄▓▓▀█░█▒▒");
                WriteCenter("▒▒▀▄█░░░░░█▀▀▄▄▀█▒▒▒");
                WriteCenter("▒▒▒▄▀▀▄▄▄██▄▄█▀▓▓█▒▒");
                WriteCenter("▒▒█▀▓█████████▓▓▓█▒▒");
                WriteCenter("▒▒█▓▓██▀▀▀▒▒▒▀▄▄█▀▒▒");
                WriteCenter("▒▒▒▀▀▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒");
                Console.BackgroundColor = ConsoleColor.Yellow;
                WriteCenter("WARNING", 3);
                Console.ResetColor();
                WriteCenter("Thank you Mario!", 1);
                WriteCenter("But our config.json is in another castle!");
                WriteCenter("(Please fill in the config.json that was generated.)", 2);
                WriteCenter("Press any key to exit..", 1);
                Console.SetCursorPosition(0, 0);
                Console.ReadKey();
                #endregion
                Environment.Exit(0);
            }

            _config = Config.LoadFromFile("config.json");
            _client = new DiscordClient(new DiscordConfiguration
            {
                AutoReconnect     = true,
                EnableCompression = true,
                Token             = _config.Token,
                TokenType         = TokenType.Bot,
            });

            _interactivity = _client.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehaviour = TimeoutBehaviour.Delete,
                PaginationTimeout   = TimeSpan.FromSeconds(30),
                Timeout             = TimeSpan.FromSeconds(30)
            });

            _startTimes = new StartTimes
            {
                BotStart    = DateTime.Now,
                SocketStart = DateTime.MinValue
            };

            _cts = new CancellationTokenSource();

            DependencyCollection dep;
            using (var d = new DependencyCollectionBuilder())
            {
                d.AddInstance(new Dependencies
                {
                    Interactivity = _interactivity,
                    StartTimes    = _startTimes,
                    Cts           = _cts
                });
                dep = d.Build();
            }

            _cnext = _client.UseCommandsNext(new CommandsNextConfiguration
            {
                CaseSensitive       = false,
                EnableDefaultHelp   = true,
                EnableDms           = true,
                EnableMentionPrefix = true,
                StringPrefix        = _config.Prefix,
                Dependencies        = dep
            });

            _cnext.RegisterCommands <Commands.Etime>();

            // Hook some events for logging.
            _client.Ready          += OnReadyAsync;
            _client.ClientErrored  += ClientError;
            _cnext.CommandExecuted += CommandExecuted;
            _cnext.CommandErrored  += CommandErrored;
        }
示例#20
0
        public Bot()
        {
            try
            {
                _config = Program.Config;
                _client = new DiscordClient(new DiscordConfiguration
                {
                    AutoReconnect         = true,
                    EnableCompression     = true,
                    Token                 = _config.Token,
                    TokenType             = TokenType.Bot,
                    LogLevel              = LogLevel.Debug,
                    UseInternalLogHandler = true
                });

                _interactivity = _client.UseInteractivity(new InteractivityConfiguration()
                {
                    PaginationBehaviour = TimeoutBehaviour.Delete,
                    PaginationTimeout   = TimeSpan.FromSeconds(30),
                    Timeout             = TimeSpan.FromSeconds(30)
                });

                _startTimes = new StartTimes
                {
                    BotStart    = DateTime.Now,
                    SocketStart = DateTime.MinValue
                };

                _cts = new CancellationTokenSource();

                DependencyCollection dep;
                using (var d = new DependencyCollectionBuilder())
                {
                    d.AddInstance(new Dependencies
                    {
                        Interactivty = _interactivity,
                        StartTimes   = _startTimes,
                        Cts          = _cts
                    });
                    dep = d.Build();
                }

                var cnext = _client.UseCommandsNext(new CommandsNextConfiguration
                {
                    CaseSensitive        = false,
                    EnableMentionPrefix  = true,
                    StringPrefix         = _config.Prefix,
                    IgnoreExtraArguments = true,
                    Dependencies         = dep
                });

                cnext.RegisterCommands <Interactivity>();

                /*_client.MessageCreated += async e =>
                 * {
                 *  if (e.Message.Content.ToLower().StartsWith("uptime"))
                 *  {
                 *
                 *  }
                 * };*/
                _client.Ready         += OnReadyAsync;
                _client.ClientErrored += ClientOnClientErrored;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
示例#21
0
        public Bot(Config config)
        {
            _logger.Trace($"WhConfig [OwnerId={config.OwnerId}, GuildId={config.GuildId}, Devices={config.Devices.Count}]");
            _config = config;

            AppDomain.CurrentDomain.UnhandledException += async(sender, e) =>
            {
                _logger.Debug("Unhandled exception caught.");
                _logger.Error((Exception)e.ExceptionObject);

                if (e.IsTerminating)
                {
                    if (_client != null)
                    {
                        var owner = await _client.GetUserAsync(_config.OwnerId);

                        if (owner == null)
                        {
                            _logger.Warn($"Failed to get owner from id {_config.OwnerId}.");
                            return;
                        }

                        await _client.SendDirectMessage(owner, Strings.CrashMessage, null);
                    }
                }
            };

            _client = new DiscordClient(new DiscordConfiguration
            {
                AutomaticGuildSync = true,
                AutoReconnect      = true,
                EnableCompression  = true,
                Token                 = _config.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true
            });
            _client.Ready += Client_Ready;
            //_client.MessageCreated += Client_MessageCreated;
            _client.ClientErrored += Client_ClientErrored;
            _client.DebugLogger.LogMessageReceived += DebugLogger_LogMessageReceived;

            DependencyCollection dep;

            using (var d = new DependencyCollectionBuilder())
            {
                d.AddInstance(new Dependencies(_config));
                dep = d.Build();
            }

            _commands = _client.UseCommandsNext
                        (
                new CommandsNextConfiguration
            {
                StringPrefix         = _config.CommandPrefix?.ToString(),
                EnableDms            = true,
                EnableMentionPrefix  = string.IsNullOrEmpty(_config.CommandPrefix),
                EnableDefaultHelp    = false,
                CaseSensitive        = false,
                IgnoreExtraArguments = true,
                Dependencies         = dep
            }
                        );
            _commands.CommandExecuted += Commands_CommandExecuted;
            _commands.CommandErrored  += Commands_CommandErrored;
            _commands.RegisterCommands <PhoneControl>();
        }
示例#22
0
        public TheStoryteller()
        {
            if (!File.Exists("config.json"))
            {
                Config.Instance.SaveToFile("config.json");
                Console.WriteLine("config file is empty");
                Environment.Exit(0);
            }

            Config.Instance.LoadFromFile("config.json");
            _client = new DiscordClient(new DiscordConfiguration
            {
                AutoReconnect         = true,
                EnableCompression     = true,
                LogLevel              = LogLevel.Debug,
                Token                 = Config.Instance.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true
            });

            _interactivity = _client.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehaviour = TimeoutBehaviour.Default,
                PaginationTimeout   = TimeSpan.FromSeconds(30),
                Timeout             = TimeSpan.FromSeconds(30)
            });

            _cts   = new CancellationTokenSource();
            _res   = new Dialog("textResources.json");
            _embed = new EmbedGenerator();

            _entityManager = new EntityManager();

            //Création et ajout des dépendances accessibles depuis toutes les commandes
            //(voir les exemples)
            DependencyCollection dep = null;

            using (DependencyCollectionBuilder d = new DependencyCollectionBuilder())
            {
                d.AddInstance(new Dependencies
                {
                    Interactivity = _interactivity,
                    Cts           = _cts,
                    Dialog        = _res,
                    Embed         = _embed,
                    Entities      = _entityManager
                });
                dep = d.Build();
            }

            _cnext = _client.UseCommandsNext(new CommandsNextConfiguration
            {
                CaseSensitive        = false,
                EnableDefaultHelp    = false,
                EnableDms            = true,
                EnableMentionPrefix  = true,
                StringPrefix         = Config.Instance.Prefix,
                IgnoreExtraArguments = true,
                Dependencies         = dep
            });


            /////////CHARACTER COMMANDS
            _cnext.RegisterCommands <Commands.CCharacter.CharacterInfo>();
            _cnext.RegisterCommands <Commands.CCharacter.Move>();
            _cnext.RegisterCommands <Commands.CCharacter.Start>();
            _cnext.RegisterCommands <Commands.CCharacter.ShowInventory>();
            _cnext.RegisterCommands <Commands.CCharacter.Trade>();
            _cnext.RegisterCommands <Commands.CCharacter.JoinVillage>();
            _cnext.RegisterCommands <Commands.CCharacter.LeaveVillage>();
            _cnext.RegisterCommands <Commands.CCharacter.Harvest>();


            /////////GUILD COMMANDS
            _cnext.RegisterCommands <Commands.CGuild.RegisterGuild>();

            ////////MAP COMMANDS
            _cnext.RegisterCommands <Commands.CMap.RegionInfo>();
            _cnext.RegisterCommands <Commands.CMap.CaseInfo>();


            ////////VILLAGE COMMANDS
            _cnext.RegisterCommands <Commands.CVillage.CreateVillage>();
            _cnext.RegisterCommands <Commands.CVillage.VillageInfo>();
            _cnext.RegisterCommands <Commands.CVillage.VillageApplicant>();
            _cnext.RegisterCommands <Commands.CVillage.FiringVillager>();


            _client.Ready        += OnReadyAsync;
            _client.GuildCreated += OnGuildCreated;
        }
示例#23
0
文件: Bot.cs 项目: ZombieCorn80/WhMgr
        /// <summary>
        /// Discord bot class
        /// </summary>
        /// <param name="whConfig">Configuration settings</param>
        public Bot(WhConfigHolder whConfig)
        {
            _logger.Trace($"WhConfig [Servers={whConfig.Instance.Servers.Count}, Port={whConfig.Instance.WebhookPort}]");
            _servers  = new Dictionary <ulong, DiscordClient>();
            _whConfig = whConfig;
            _whm      = new WebhookController(_whConfig);

            // Build form lists for icons
            IconFetcher.Instance.SetIconStyles(_whConfig.Instance.IconStyles);

            // Set translation language
            Translator.Instance.SetLocale(_whConfig.Instance.Locale);

            // Set database connection strings to static properties so we can access within our extension classes
            DataAccessLayer.ConnectionString        = _whConfig.Instance.Database.Main.ToString();
            DataAccessLayer.ScannerConnectionString = _whConfig.Instance.Database.Scanner.ToString();

            // Set unhandled exception event handler
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;

            // Initialize and start midnight reset timer
            var midnight = new DandTSoftware.Timers.MidnightTimer();

            midnight.TimeReached += async(e) => await OnMidnightTimer();

            midnight.Start();

            // Initialize the subscription processor if at least one Discord server wants custom notifications
            // and start database migrator
            if (_whConfig.Instance.Servers.Values.ToList().Exists(x => x.Subscriptions.Enabled))
            {
                // Start database migrator
                var migrator = new DatabaseMigrator();
                while (!migrator.Finished)
                {
                    Thread.Sleep(50);
                }

                _subProcessor = new SubscriptionProcessor(_servers, _whConfig, _whm);
            }

            // Create a DiscordClient object per Discord server in config
            foreach (var(guildId, serverConfig) in _whConfig.Instance.Servers)
            {
                serverConfig.LoadDmAlerts();
                var client = new DiscordClient(new DiscordConfiguration
                {
                    AutomaticGuildSync = true,
                    AutoReconnect      = true,
                    EnableCompression  = true,
                    Token                 = serverConfig.Token,
                    TokenType             = TokenType.Bot,
                    UseInternalLogHandler = true
                });

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

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

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

                client.Ready              += Client_Ready;
                client.GuildAvailable     += Client_GuildAvailable;
                client.GuildMemberUpdated += Client_GuildMemberUpdated;
                //_client.MessageCreated += Client_MessageCreated;
                client.ClientErrored += Client_ClientErrored;
                client.DebugLogger.LogMessageReceived += DebugLogger_LogMessageReceived;

                // Configure Discord interactivity module
                var interactivity = 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)
                }
                                    );

                // Build the dependency collection which will contain our objects that can be globally used within each command module
                DependencyCollection dep;
                using (var d = new DependencyCollectionBuilder())
                {
                    d.AddInstance(new Dependencies(interactivity, _whm, _subProcessor, _whConfig, new StripeService(_whConfig.Instance.StripeApiKey)));
                    dep = d.Build();
                }

                // Discord commands configuration
                var commands = client.UseCommandsNext
                               (
                    new CommandsNextConfiguration
                {
                    StringPrefix = serverConfig.CommandPrefix?.ToString(),
                    EnableDms    = true,
                    // If command prefix is null, allow for mention prefix
                    EnableMentionPrefix = string.IsNullOrEmpty(serverConfig.CommandPrefix),
                    // Use DSharpPlus's built-in help formatter
                    EnableDefaultHelp    = true,
                    CaseSensitive        = false,
                    IgnoreExtraArguments = true,
                    Dependencies         = dep
                }
                               );
                commands.CommandExecuted += Commands_CommandExecuted;
                commands.CommandErrored  += Commands_CommandErrored;
                // Register Discord command handler classes
                commands.RegisterCommands <Owner>();
                commands.RegisterCommands <Event>();
                commands.RegisterCommands <Nests>();
                commands.RegisterCommands <ShinyStats>();
                commands.RegisterCommands <Gyms>();
                commands.RegisterCommands <Quests>();
                commands.RegisterCommands <Settings>();
                if (serverConfig.Subscriptions.Enabled)
                {
                    commands.RegisterCommands <Notifications>();
                }
                if (serverConfig.EnableCities)
                {
                    commands.RegisterCommands <Feeds>();
                }

                _logger.Info($"Configured Discord server {guildId}");
                if (!_servers.ContainsKey(guildId))
                {
                    _servers.Add(guildId, client);
                }

                // Wait 3 seconds between initializing Discord clients
                Task.Delay(3000).GetAwaiter().GetResult();
            }

            RegisterConfigMonitor();
        }