Exemplo n.º 1
0
        public async Task RunBotAsync()
        {
            // first, let's load our configuration file
            var json = string.Empty;

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

            //TODO: overrite help to be more verbose, example in one of samples

            #region Client
            Client = new DiscordClient(new DiscordConfiguration
            {
                Token     = cfgjson.Token,
                TokenType = TokenType.Bot,

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

            Client.ClientErrored += Client_ClientErrored;
            #endregion

            #region Commands
            Commands = Client.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefix        = cfgjson.CommandPrefix,
                EnableDms           = false,
                EnableMentionPrefix = true
            });

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

            Commands.RegisterCommands <Commands>();
            CommandsNextUtilities.RegisterConverter(new CommandConverters.NullableBoolConverter());
            CommandsNextUtilities.RegisterConverter(new CommandConverters.NullableIntConverter());
            #endregion

            #region Voice
            Voice = Client.UseVoiceNext(new VoiceNextConfiguration
            {
                VoiceApplication = VoiceApplication.Music
            });
            #endregion

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Exemplo n.º 2
0
        public async Task RunBotAsync()
        {
            var json = "";

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

            var cfgjson = JsonConvert.DeserializeObject <ConfigJson>(json);
            var cfg     = new DiscordConfiguration
            {
                Token     = cfgjson.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;

            var ccfg = new CommandsNextConfiguration
            {
                StringPrefix        = cfgjson.CommandPrefix,
                EnableDms           = true,
                EnableMentionPrefix = true
            };

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

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

            // Here we register our custom converter
            var customUserConverter = new CustomUserConverter();

            CommandsNextUtilities.RegisterConverter(customUserConverter);
            CommandsNextUtilities.RegisterUserFriendlyTypeName <CustomUserConverter>("CustomUser");

            this.Commands.RegisterCommands <ExampleConversionCommand>();

            await this.Client.ConnectAsync();

            await Task.Delay(-1);
        }
Exemplo n.º 3
0
        public async Task Bot()
        {
            client = new DiscordClient(new DiscordConfiguration()
            {
                AutoReconnect         = true,
                LargeThreshold        = 150,
                LogLevel              = LogLevel.Debug,
                Token                 = cfg.TokenDiscord,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true
            });

            client.Ready              += Client_Ready;
            client.GuildAvailable     += Client_GuildAvailable;
            client.ClientErrored      += Client_ClientErrored;
            client.GuildMemberAdded   += Client_GuildMemberAdded;
            client.MessageCreated     += Client_MessageCreated;
            client.GuildMemberUpdated += Client_GuildMemberUpdated;

            commands = client.UseCommandsNext(new CommandsNextConfiguration()
            {
                StringPrefix        = "!",
                EnableDms           = true,
                EnableMentionPrefix = true,
                CaseSensitive       = true,
                SelfBot             = false,
                EnableDefaultHelp   = true
            });

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

            CommandsNextUtilities.RegisterConverter(new GuruPlatformConverter());
            CommandsNextUtilities.RegisterUserFriendlyTypeName <GuruPlatform>("platform");

            commands.RegisterCommands <PublicCommands>();
            client.UseInteractivity(new InteractivityConfiguration());

            // Required if running on w7
            client.SetWebSocketClient <WebSocket4NetClient>();

            await client.ConnectAsync();

            // Makes bot be connected all the time until shut down manually
            await Task.Delay(-1);
        }
Exemplo n.º 4
0
        static Task <int> PrefixResolver(DiscordMessage message, DiscordUser client)
        {
            var mentionPrefixLength = CommandsNextUtilities.GetMentionPrefixLength(message, client);

            if (mentionPrefixLength != -1)
            {
                return(Task.FromResult(mentionPrefixLength));
            }
            var prefixes = context.Prefixes.Where(prefix => prefix.Server == message.Channel.GuildId.ToString())
                           .Select(prefix => prefix.PrefixText).OrderByDescending(prefix => prefix.Length).ToList();

            prefixes.Add(Configuration["Prefix"]);
            foreach (var prefix in prefixes)
            {
                var prefixLength = CommandsNextUtilities.GetStringPrefixLength(message, prefix);
                if (prefixLength != -1)
                {
                    return(Task.FromResult(prefixLength));
                }
            }
            return(Task.FromResult(-1));
        }
Exemplo n.º 5
0
        public async Task RunBotAsync()
        {
            var token = File.ReadAllText("../../../../.token");

            Client = new DiscordClient(new DiscordConfiguration
            {
                Token                 = token,
                TokenType             = TokenType.Bot,
                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            });


            Debug debug = new Debug();

            Client.Ready         += debug.Client_Ready;
            Client.ClientErrored += debug.Client_ClientError;

            var ccfg = new CommandsNextConfiguration
            {
                // Use string prefix from config.json
                //StringPrefix = cfgjson.CommandPrefix,

                // enables responding in direct messages
                EnableDms           = true,
                EnableMentionPrefix = true
            };

            // hooking up commands
            Commands = Client.UseCommandsNext(ccfg);

            // Event logging of commands
            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");

            // registrering commands
            Commands.RegisterCommands <ExampleUngrouppedCommands>();
            Commands.RegisterCommands <ExampleGrouppedCommands>();
            Commands.RegisterCommands <ExampleExecutableGroup>();

            // custom formatting help
            Commands.SetHelpFormatter <SimpleHelpFormatter>();

            Client.MessageCreated += async e =>
            {
                if (e.Author.Id != Client.CurrentUser.Id)
                {
                    var response = MessageParser.ParseIt(e.Message.Content).RunCommand(e.Author);

                    if (!string.IsNullOrWhiteSpace(response))
                    {
                        await e.Message.RespondAsync(response);
                    }
                }
            };

            await Client.ConnectAsync();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // enable responding in direct messages
                EnableDms = true,

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

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

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

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

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

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

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

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

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

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

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

            // and this is to prevent premature quitting
            await Task.Delay(-1);
        }
Exemplo n.º 7
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);
        }
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 DiscordConfig
            {
                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, install
            // DSharpPlus.WebSocket.WebSocket4Net from NuGet,
            // add appropriate usings, and uncomment the following
            // line
            //this.Client.SetWebSocketClient<WebSocket4NetClient>();

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

            // 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.ClientError    += 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;

            // 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
            this.Commands.RegisterCommands <ExampleUngrouppedCommands>();
            this.Commands.RegisterCommands <ExampleGrouppedCommands>();
            this.Commands.RegisterCommands <OwnerGrouppedCommands>();

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

            Client.Ready += async e => await e.Client.UpdateStatusAsync(new Game("Type $help for help!") { StreamType = GameStreamType.NoStream });

            // 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.º 9
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);

            this.Client.SetWebSocketClient <WebSocketClient>();

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

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

            // and this is to prevent premature quitting
            await Task.Delay(-1);
        }