示例#1
0
        public async Task RunAsync()
        {
            var json = string.Empty;

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

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

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

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

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

            var CommandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { configJson.Prefix },
                EnableDms           = false,
                EnableMentionPrefix = true,
                DmHelp = false,             //true = help berichten in dm's
                IgnoreExtraArguments = true //Zorgt dat teveel arguments niet meegenomen worden in de call
            };

            Commands = Client.UseCommandsNext(CommandsConfig);

            Commands.RegisterCommands <FunCommands>();
            Commands.RegisterCommands <PoeCommands>();
            Commands.RegisterCommands <DotaCommands>();
            Commands.RegisterCommands <LolCommands>();
            Commands.RegisterCommands <SteamCommands>();
            Commands.RegisterCommands <HueCommands>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
示例#2
0
        public async Task RunAsync()
        {
            var json = string.Empty;

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


            var configJson = JsonConvert.DeserializeObject <ConfigJson>(json);            //convert json to string

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

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

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

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

            Commands = Client.UseCommandsNext(commandsConfig);
            Commands.RegisterCommands <FlareCommands>();
            Commands.RegisterCommands <AdminCommands>();
            Commands.RegisterCommands <UserCommands>();


            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
示例#3
0
        public async Task RunAsync()
        {
            discord.DebugLogger.LogMessage(LogLevel.Info, ApplicationName, "Connecting", DateTime.Now);
            await discord.ConnectAsync();

            creator = await discord.GetUserAsync(IDs.Users.Ski);

            discord.DebugLogger.LogMessage(LogLevel.Info, ApplicationName, "Connected", DateTime.Now);
            await WaitForCancellationAsync();

            discord.DebugLogger.LogMessage(LogLevel.Info, ApplicationName, "Disconnecting", DateTime.Now);
            await discord.DisconnectAsync();

            discord.DebugLogger.LogMessage(LogLevel.Info, ApplicationName, $"Disconnected{Environment.NewLine}", DateTime.Now);
        }
示例#4
0
        public async Task RunBotAsync()
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json", false, true)
                         .Build();
            Discord discord = new Discord();

            config.GetSection("Discord").Bind(discord);
            var services = ConfigureService(config);
            var cfg      = new DiscordConfiguration
            {
                Token           = discord.DiscordToken,
                TokenType       = TokenType.Bot,
                AutoReconnect   = true,
                MinimumLogLevel = LogLevel.Debug
            };

            Client                 = new DiscordClient(cfg);
            Client.Ready          += ClientReady;
            Client.GuildAvailable += ClientGuildAvailable;
            Client.ClientErrored  += ClientErrored;
            Client.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehaviour = PaginationBehaviour.Ignore,
                Timeout             = TimeSpan.FromMinutes(5)
            });
            var ccfg = new CommandsNextConfiguration
            {
                StringPrefixes      = new[] { discord.Prefix },
                EnableDms           = true,
                EnableMentionPrefix = true,
                Services            = services
            };

            Commands = Client.UseCommandsNext(ccfg);
            Commands.CommandExecuted += CommandExecute;
            Commands.CommandErrored  += CommandErrored;
            Commands.RegisterCommands <ItemCommand>();
            Commands.RegisterCommands <OperatorCommand>();
            Commands.RegisterCommands <RecruitCommand>();
            Commands.RegisterCommands <TipCommand>();
            Commands.SetHelpFormatter <HelpFormatter>();
            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
示例#5
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);
        }
示例#6
0
        public async Task RunAsync()
        {
            //Loading config 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().ConfigureAwait(false);
                }
            }

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

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

            Client = new DiscordClient(config);

            //Event
            Client.Ready += OnClientReady;


            //Bot Command Setting
            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefix        = configJson.Prefix,
                EnableDms           = true,
                EnableMentionPrefix = true,
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <FunCommands>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
示例#7
0
        public async Task RunAsync()
        {
            var json = string.Empty;

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


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

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

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

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

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

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <ListOfCommands>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
示例#8
0
        public Bot(IServiceProvider services)
        {
            var config = new DiscordConfiguration
            {
                Token           = Environment.GetEnvironmentVariable("BOT_TOKEN"),
                TokenType       = TokenType.Bot,
                AutoReconnect   = true,
                MinimumLogLevel = LogLevel.Debug,
            };

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

            Client.UseInteractivity(new InteractivityConfiguration
            {
            });

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes = new string[] { Environment.GetEnvironmentVariable("PREFIX") },
                // Enables users to "@" bot instead of using the assigned prefix
                EnableMentionPrefix = true,
                CaseSensitive       = false,
                DmHelp            = true,
                EnableDms         = true,
                EnableDefaultHelp = true,
                Services          = services
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            // Add command groups here
            // Automate this when your not in a bad mood
            Commands.RegisterCommands <Stress>();
            Commands.RegisterCommands <Polls>();
            Commands.RegisterCommands <RoleManager>();
            Commands.RegisterCommands <Reports>();
            Commands.RegisterCommands <Meetings>();
            //Commands.RegisterCommands<ConnectToGitHub>();

            Client.ConnectAsync();
        }
示例#9
0
        static void Main(string[] args)
        {
            DiscordClient client;

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

            client.MessageCreated += Client_MessageCreated;

            client.ConnectAsync();

            Console.ReadLine();
        }
示例#10
0
        public async Task RunAsync()
        {
            var json = "";

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

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

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

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

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

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <FunCommands>();
            Commands.RegisterCommands <ReminderCommands>();
            Commands.RegisterCommands <PrankCommands>();
            Commands.RegisterCommands <WeatherCommand>();


            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
示例#11
0
        public async Task RunBot()
        {
            var json    = JsonManager.ParseJsonAsync("Config/config.json").Result;
            var cfgjson = JsonConvert.DeserializeObject <ConfigJson>(json);
            var cfg     = new DiscordConfig
            {
                Token = cfgjson.Token, TokenType = TokenType.Bot, AutoReconnect = true, LogLevel = LogLevel.Info,
                UseInternalLogHandler = true
            };

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

            Client              = new DiscordClient(cfg);
            this.Commands       = Client.UseCommandsNext(ccfg);
            this.EventManager   = new EventManager(cfgjson.Prefix);
            this.CommandManager = new CommandManager();

            Client.UseInteractivity();

            Client.Ready          += this.EventManager.Ready;
            Client.ClientError    += this.EventManager.ClientError;
            Client.MessageCreated += this.EventManager.OnMessage;
            Client.SocketError    += this.EventManager.SocketError;

            Client.GuildMemberAdd += this.EventManager.GuildMemberAdd;

            this.Commands.CommandExecuted += this.CommandManager.CommandExecuted;
            this.Commands.CommandErrored  += this.CommandManager.CommandError;

            this.Commands.RegisterCommands <CommandManager>();
            this.Commands.RegisterCommands <SuperCommands>();
            this.Commands.RegisterCommands <AdminCommands>();
            this.Commands.RegisterCommands <MemberCommands>();
            this.Commands.RegisterCommands <GeneralCommands>();
            this.Commands.RegisterCommands <HighscoreCommands>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
示例#12
0
        /// <summary>
        /// TODO: Clean up Bot constructor/ConfigLoader interaction.
        /// </summary>
        /// <param name="serviceProvider"></param>
        public Bot(IServiceProvider serviceProvider)
        {
            ConfigLoader.LoadConfig();

            this.cts = serviceProvider.GetService <CancellationTokenSource>();

            Client = new DiscordClient(new DiscordConfiguration
            {
                Token           = ConfigLoader.Config.Token,
                TokenType       = TokenType.Bot,
                MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Trace,
                AutoReconnect   = ConfigLoader.Config.AutoReconnect,
                Intents         = DiscordIntents.All,
            });

            Client.UseInteractivity(new InteractivityConfiguration
            {
                PollBehaviour = DSharpPlus.Interactivity.Enums.PollBehaviour.KeepEmojis,
                Timeout       = TimeSpan.FromMinutes(2)
            });

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { ConfigLoader.Config.Prefix },
                EnableMentionPrefix = true,
                EnableDms           = true,
                DmHelp   = true,
                Services = serviceProvider
            };


            Client.Ready += Client_Ready;

            Commands = Client.UseCommandsNext(commandsConfig);
            Client.UseVoiceNext();
            //Client.MessageCreated += Client_ItsAFeeture;
            //Client.MessageCreated += Client_MessageDespacito;
            Commands.RegisterCommands <Commands.Fun>();
            Commands.RegisterCommands <Commands.Owner>();

            Client.ConnectAsync();
        }
示例#13
0
        static async Task MainAsync(string[] args)
        {
            string CurrentToken; string CurrentPrefix;

            if (DevMode)
            {
                CurrentToken  = "token";
                CurrentPrefix = "no1test/";
            }
            else
            {
                CurrentToken  = "token";
                CurrentPrefix = "no1/";
            }
            discord = new DiscordClient(new DiscordConfiguration
            {
                Token                 = $"{CurrentToken}",
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                LogLevel              = LogLevel.Error,
            });

            commands = discord.UseCommandsNext(new CommandsNextConfiguration
            {
                CaseSensitive = false,
                StringPrefix  = $"{CurrentPrefix}",
            });
            commands.RegisterCommands <StandardCommands>();
            commands.RegisterCommands <AdminCommands>();

            if (DevMode)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[WARNING]: Running in DevMode! NOT FOR PRODUCTION!");
                Console.ResetColor();
            }
            Console.ResetColor();
            Console.WriteLine("Bot is now online!");
            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
        static async Task MainAsync(string[] args)
        {
            discord = new DiscordClient(new DiscordConfiguration
            {
                Token     = "H1wBUFC6DV9JohuaZslSFavU7ZC2aBDI", // YOUR CLIENT'S TOKEN WHICH YOU SAVED IN BOT SETTINGS.
                TokenType = TokenType.Bot
            });

            discord.MessageCreated += async e =>
            {
                if (e.Message.Content.ToLower().StartsWith("Hi"))                        // The user's message
                {
                    await e.Message.RespondAsync("Hi dude!");                            // Bot's response
                }
                if (e.Message.Content.ToLower() == "Hello Bot, how're you?")             // The alternative code for sending message (w/o "StartsWith")
                {
                    await e.Message.RespondAsync("https://imgur.com/gallery/0000.jpeg"); //Sample for responsing with Image link
                }
                if (e.Message.Content.ToLower() == "!soldier")                           // You can create your own commands start with "!" or another thing.
                {
                    await e.Message.RespondAsync("Yes sir!");
                }

                if (e.Message.Content.ToLower() == "!random") // This is sample for random responsing from bot if you tpye "!random".
                {
                    Random rand = new Random();
                    int    r    = rand.Next(0, 2);
                    Console.WriteLine(r);
                    if (r == 0)
                    {
                        await e.Message.RespondAsync("https://imgur.com/gallery/111111.jpeg");
                    }
                    else
                    {
                        await e.Message.RespondAsync("https://imgur.com/gallery/222222.jpeg");
                    }
                }
            };
            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
示例#15
0
        static async Task MainAsync(string[] args)
        {
            //Makes a Logo Screen. In Green.
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("");
            }
            LOGGER.WriteMessageColor("▄▄▄█████▓ ▒█████  ▄▄▄█████▓ ██▓███   ▄▄▄       ██▓    \r\n▓  ██▒ ▓▒▒██▒  ██▒▓  ██▒ ▓▒▓██░  ██▒▒████▄    ▓██▒    \r\n▒ ▓██░ ▒░▒██░  ██▒▒ ▓██░ ▒░▓██░ ██▓▒▒██  ▀█▄  ▒██░    \r\n░ ▓██▓ ░ ▒██   ██░░ ▓██▓ ░ ▒██▄█▓▒ ▒░██▄▄▄▄██ ▒██░    \r\n  ▒██▒ ░ ░ ████▓▒░  ▒██▒ ░ ▒██▒ ░  ░ ▓█   ▓██▒░██████▒\r\n  ▒ ░░   ░ ▒░▒░▒░   ▒ ░░   ▒▓▒░ ░  ░ ▒▒   ▓▒█░░ ▒░▓  ░\r\n    ░      ░ ▒ ▒░     ░    ░▒ ░       ▒   ▒▒ ░░ ░ ▒  ░\r\n  ░      ░ ░ ░ ▒    ░      ░░         ░   ▒     ░ ░   \r\n             ░ ░                          ░  ░    ░  ░", "green", false);
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("");
            }
            Console.ForegroundColor = ConsoleColor.White;
            //Reigsters the bot with the Discord API
            DISCORD_CLIENT = new DiscordClient(new DiscordConfiguration
            {
                //Your Token Here!
                Token                 = "",
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                LogLevel              = LogLevel.Warning
            });
            LOGGER.WriteMessageColor("Client generated", "green", true);
            //Simple Ping Method, if you want one

            /*DISCORD_CLIENT.MessageCreated += async e =>
             * {
             *  if (e.Message.Content.ToLower().StartsWith("ping"))
             *      await e.Message.RespondAsync("pong!");
             * };*/
            COMMANDS = DISCORD_CLIENT.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefix = "!"
            });
            //Registering Comments, connectingn to the API
            COMMANDS.RegisterCommands <CommandsManager>();
            LOGGER.WriteMessageColor("Commands registered", "green", true);
            await DISCORD_CLIENT.ConnectAsync();

            LOGGER.WriteMessageColor("Connected", "green", true);
            await Task.Delay(-1);
        }
示例#16
0
        private static async Task MainAsync()
        {
            Console.WriteLine("Starting...");

            string decodedToken = System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(Token));

            _discord = new DiscordClient(new DiscordConfiguration
            {
                Token     = decodedToken,
                TokenType = TokenType.Bot
            });

            await _discord.ConnectAsync();

            AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);

            Console.WriteLine("Getting Channel...");
            var _jibberJabber = await _discord.GetChannelAsync(630368958498734099);

            Console.WriteLine("Getting pinned message...");
            var pinnedMessage = await _jibberJabber.GetMessageAsync(692849775690645555);

            var timedLocalTimeUpdate = new TimedLocalTimeUpdate(30000, pinnedMessage);

            Console.WriteLine("Starting local time updater!");
            timedLocalTimeUpdate.Start();

            var steamAppNewsLibrary = await Library.Create(LibraryType.SteamAppNews);

            var timedSteamAppNewsUpdate = await TimedSteamAppNewsUpdate.Create(3600000, steamAppNewsLibrary); //3600000 = 1 hour

            Console.WriteLine("Starting steam app news updater!");
            timedSteamAppNewsUpdate.Start();

            _commandList = await CommandList.Create(_discord, steamAppNewsLibrary);

            Console.WriteLine("Listening to new messages!");
            _discord.MessageCreated += async e => { await _commandList.Run(e); };

            Console.WriteLine("Setup complete!");
            await Task.Delay(-1);
        }
示例#17
0
文件: Program.cs 项目: Firesz25/Tuwim
        private static async Task MainAsync()
        {
            var discord = new DiscordClient(new DiscordConfiguration()
            {
                Token     = Getjson("token"),
                TokenType = TokenType.Bot
            });

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

            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
示例#18
0
        public async Task RunBotAsync()
        {
            string 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 config  = new DiscordConfiguration
            {
                Token                 = cfgJson.Token,
                TokenType             = TokenType.Bot,
                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            Client                 = new DiscordClient(config);
            Client.Ready          += Client_Ready;
            Client.GuildAvailable += Client_GuildAvailable;
            Client.ClientErrored  += Client_ClientErrored;

            var comConfig = new CommandsNextConfiguration
            {
                StringPrefix        = cfgJson.CommandPrefix,
                EnableDms           = true,
                EnableMentionPrefix = true
            };

            Commands = Client.UseCommandsNext(comConfig);
            Commands.CommandExecuted += Commands_CommandExecuted;
            Commands.CommandErrored  += Commands_CommandErrored;

            System.Reflection.Assembly discordBotCommandsAssembly = System.Reflection.Assembly.Load("DiscordBot.Commands");
            Commands.RegisterCommands(discordBotCommandsAssembly);
            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
示例#19
0
        static async Task MainAsync()
        {
            ConfigurationHelper configurationHelper = new ConfigurationHelper();

            var discord = new DiscordClient(new DiscordConfiguration()
            {
                Token     = configurationHelper.GetOAuthValue().Token,
                TokenType = TokenType.Bot
            });

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

            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
示例#20
0
        public async Task RunAsync()
        {
            Setup();

            var discordConfig = await JsonStorage.RestoreObjectAsync <Configuration.DiscordConfiguration>(DiscordConfigPath);

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

            Client                 = new DiscordClient(config);
            Client.Ready          += OnClientReady;
            Client.MessageCreated += OnMessageCreated;
            Client.GuildAvailable += OnGuildAvailable;

            Client.UseInteractivity(new InteractivityConfiguration());

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { discordConfig.Prefix },
                EnableMentionPrefix = false,
                EnableDms           = true,
                CaseSensitive       = false,
                Services            = GetServiceProvider()
            };

            Commands = Client.UseCommandsNext(commandsConfig);
            Commands.CommandErrored  += OnCommandErrored;
            Commands.CommandExecuted += OnCommandExecuted;
            Commands.RegisterCommands <UnsortedCommands>();

            await Client.ConnectAsync(new DiscordActivity("like a Gucci", ActivityType.Playing));

            await Task.Delay(-1);
        }
示例#21
0
        public Bot(IServiceProvider services)
        {
            var json = string.Empty;

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

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

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

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

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

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <BaseCommands>();

            Client.ConnectAsync();
        }
示例#22
0
        public async Task RunAsync()
        {
            var json = string.Empty;


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

            Client        = new DiscordClient(config);
            Client.Ready += OnClientReady;
            Client.UseInteractivity(new InteractivityConfiguration
            {
                Timeout = TimeSpan.FromSeconds(10)
            });

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

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <FunCommands>();
            Commands.RegisterCommands <TeamCommands>();
            Commands.RegisterCommands <LolCommands>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
示例#23
0
        public async Task LaunchAsync(ILogger log)
        {
            Logger = log;

            Logger.LogInformation("Starting Discord Bot :)");

            await LoadConfig();

            SetupDiscordClient();
            CreateCommandConfig();

            _cmdModule.RegisterCommands <BaseCommands>();

            // Default help command is <prefix>help
            _cmdModule.SetHelpFormatter <BotHelpFormatter>();

            TwitchFilter            = new TwitchFiltering(config);
            _client.MessageCreated += MessageRecieved;

            await _client.ConnectAsync();

            await Task.Delay(-1);
        }
示例#24
0
        static async Task MainAsync(string[] args)
        {
            discord = new DiscordClient(new DiscordConfiguration {
                Token                 = "NDIxNzY1MjA5NzU4MjM2Njky.DpoxbA.gdPDqOHDKjBbo530XRm65KsCd_A",
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                LogLevel              = LogLevel.Debug
            });

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

            commands.RegisterCommands <Commands>();
            commands.RegisterCommands <SettingsCommands>();
            commands.RegisterCommands <AdminCommands>();
            commands.RegisterCommands <UtilityCommands>();

            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
示例#25
0
        public async Task RunAsync()
        {
            var loaded = LoadConfigAsync().GetAwaiter().GetResult();

            if (loaded)
            {
                var config = new DiscordConfiguration()
                {
                    Token                 = _token,
                    TokenType             = TokenType.Bot,
                    AutoReconnect         = true,
                    LogLevel              = LogLevel.Debug,
                    UseInternalLogHandler = true
                };

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

                var commandsConfig = new CommandsNextConfiguration()
                {
                    StringPrefixes      = new string[] { _prefix },
                    EnableDms           = false,
                    EnableMentionPrefix = true,
                    DmHelp = false,
                    IgnoreExtraArguments = false
                };

                Commands = Client.UseCommandsNext(commandsConfig);
                Commands.RegisterCommands <FirstCommand>();


                await Client.ConnectAsync();

                // wait for commands
                await Task.Delay(-1);
            }
        }
示例#26
0
        public async Task RunAsync(ConfigJson config)
        {
            //Discord Client config
            var discordConfig = new DiscordConfiguration
            {
                Token         = config.BotConfig.Token,
                TokenType     = TokenType.Bot,
                AutoReconnect = config.BotConfig.AutoReconnect,
                Intents       = DiscordIntents.All
            };

            //Initialize Discord Client
            Client = new DiscordClient(discordConfig);

            #region Events
            //Get Client Interactivity
            Client.UseInteractivity(new InteractivityConfiguration
            {
                Timeout = TimeSpan.FromMinutes(5)
            });

            //On new reaction
            Client.MessageReactionAdded += async(s, e) =>
            {
                //Grant Roles Anni Discord
                Functions.Functions.GrantRolesByReaction(s, e);
            };

            //On removed reaction
            Client.MessageReactionRemoved += async(s, e) =>
            {
                //Revoke Roles Anni Discord
                Functions.Functions.RemoveRolesByReaction(s, e);
            };

            //On message created
            Client.MessageCreated += async(s, e) =>
            {
                if (e.Message.Content.ToLower().Contains("datboi") && e.Author.Id != 853976207493038090)
                {
                    await e.Message.RespondAsync("https://cdn.discordapp.com/attachments/916043520610017301/943957313314754580/shitsfire.jpg");
                }
            };

            //On button press
            Client.ComponentInteractionCreated += async(s, e) =>
            {
                //Functions.Functions.ButtonPressed(s, e);
            };
            #endregion

            //Discord Command config
            var cmdConfig = new CommandsNextConfiguration
            {
                StringPrefixes       = new string[] { config.BotConfig.Prefix },
                EnableMentionPrefix  = config.CommandConfig.EnableMentionPrefix,
                EnableDms            = config.CommandConfig.EnableDms,
                IgnoreExtraArguments = config.CommandConfig.IgnoreExtraArguments
            };

            //Initialize Commands in Client
            Commands = Client.UseCommandsNext(cmdConfig);

            //Register Command Modules
            Commands.RegisterCommands <StandardCommands>();
            Commands.RegisterCommands <FishCommands>();
            Commands.RegisterCommands <TwitterCommands>();
            Commands.RegisterCommands <AnniCommands>();

            //Connect Client
            await Client.ConnectAsync();

            //Endless Task Delay
            await Task.Delay(-1);
        }
示例#27
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);
        }
示例#28
0
        public async Task RunAsync()
        {
            var fileContent = await File.ReadAllTextAsync("config.json");

            var configJson = JsonSerializer.Deserialize <ConfigJson>(fileContent);


            var botConfig = new DiscordConfiguration
            {
                Token              = configJson.Token,
                TokenType          = TokenType.Bot,
                AutoReconnect      = true,
                MinimumLogLevel    = LogLevel.Debug,
                LogTimestampFormat = "MMM dd yyyy - hh:mm:ss tt"
            };

            Client = new DiscordClient(botConfig);

            // Debug Purposes..
            Client.Ready += (Client, e) =>
            {
                Client.Logger.LogInformation(BotEventId, "Client is ready to process events.");
                return(Task.CompletedTask);
            };

            Client.GuildAvailable += (Client, e) =>
            {
                Client.Logger.LogInformation(BotEventId, $"Guild available: {e.Guild.Name} && Owner: {e.Guild.Owner.Username}");
                return(Task.CompletedTask);
            };

            Client.ClientErrored += (Client, e) =>
            {
                Client.Logger.LogInformation(BotEventId, e.Exception, "Exception occured");
                return(Task.CompletedTask);
            };

            Client.MessageCreated += (Client, e) =>
            {
                Client.Logger.LogInformation(BotEventId, $"Server: {e.Guild.Name}, Channel: #{e.Channel.Name}, Message Content: \"{e.Message.Content}\" (Sent by {e.Author.Username})");
                return(Task.CompletedTask);
            };

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

            Commands = Client.UseCommandsNext(config);

            Commands.SetHelpFormatter <CustomHelp>();
            Commands.RegisterCommands <BasicCommands>();
            Commands.RegisterCommands <UseFulCommands>();

            // Debug purposes..
            Commands.CommandExecuted += (Commands, e) =>
            {
                e.Context.Client.Logger.LogInformation(BotEventId, $"{e.Context.User.Username} successfully executed {e.Command.QualifiedName}");
                return(Task.CompletedTask);
            };



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

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
示例#29
0
        static async Task MainAsync(string[] args)
        {
            discord = new DiscordClient(new DiscordConfiguration
            {
                Token                 = token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                LogLevel              = LogLevel.Debug,
            });
            discord.MessageCreated += async e =>
            {
                /*if (e.Message.Content.Length>=350 && e.Message.Author.IsBot==false) //copypasta
                 * {
                 *  await e.Message.RespondAsync(e.Message.Content);
                 *  using (System.IO.StreamWriter file =
                 *      new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\pasta.txt", true))
                 *  {
                 *      file.WriteLine(e.Message.Content.ToString());
                 *      file.WriteLine();
                 *  }
                 * }*/

                /*if (cnt == 2 && e.Message.Author.IsBot == false)
                 * {
                 *  mes2 = e.Message.Content;
                 *  if (mes1 == mes2)
                 *  {
                 *      await e.Message.RespondAsync(mes2);
                 *      cnt = 0;
                 *  }
                 *  else
                 *  {
                 *      mes1 = e.Message.Content;
                 *      cnt = 1;
                 *  }
                 * }
                 * if (cnt == 1 && e.Message.Author.IsBot == false)
                 * {
                 *  mes2 = e.Message.Content;
                 *  if (mes2 == mes1)
                 *  {
                 *      cnt++;
                 *  }
                 *  else
                 *  {
                 *      mes1 = e.Message.Content;
                 *  }
                 * }
                 * if (cnt==0 && e.Message.Author.IsBot==false)
                 * {
                 *  mes1 = e.Message.Content;
                 *  cnt++;
                 * }*/

                switch (cnt) //the 4 horsemen
                {
                case 0:
                    if (e.Message.Author.IsBot == false)
                    {
                        mes1 = e.Message.Content;
                        cnt++;
                    }
                    break;

                case 1:
                    if (e.Message.Author.IsBot == false)
                    {
                        mes2 = e.Message.Content;
                        if (mes2 == mes1)
                        {
                            cnt++;
                        }
                        else
                        {
                            mes1 = e.Message.Content;
                        }
                    }
                    break;

                case 2:
                    if (e.Message.Author.IsBot == false)
                    {
                        mes2 = e.Message.Content;
                        if (mes1 == mes2)
                        {
                            await e.Message.RespondAsync(mes2);

                            cnt = 0;
                        }
                        else
                        {
                            mes1 = e.Message.Content;
                            cnt  = 1;
                        }
                    }
                    break;
                }

                if (e.Message.Content.StartsWith("FRANZ"))
                {
                    await e.Message.RespondAsync("HANSDI");
                }
                if (e.Message.Content.ToLower() == "bad bot")
                {
                    await e.Message.RespondAsync("no u");
                }
                if (e.Message.Content.ToLower() == "good bot")
                {
                    await e.Message.RespondAsync("yes me!");
                }
                if (e.Message.Content.ToLower() == "p!counter") //epic counter summon
                {
                    await e.Message.RespondAsync("Messages containing the E-word: " + epicCounter);
                }
                if (e.Message.Content.ToLower().Contains("epic")) //counting the epics coolchamp
                {
                    epicCounter += 1;
                    await e.Message.CreateReactionAsync(DiscordEmoji.FromUnicode("😎"));

                    using (System.IO.StreamWriter file =
                               new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
                    {
                        file.WriteLine(epicCounter.ToString()); //every time an epic is said it updates the counter file
                    }
                }
                if (e.Message.Content.ToLower() == "p!uptime") //uptime counter test
                {
                    TimeSpan taim = DateTime.Now - starterTime;
                    await e.Message.RespondAsync("Uptime: " + taim.Days + " days, " + taim.Hours + " hours, " + taim.Minutes + " minutes and " + taim.Seconds + " seconds");
                }
                if (e.Message.Content.ToLower().Contains("f**k pp"))
                {
                    await e.Message.RespondAsync("f**k you too");
                }
            };
            interactivity = 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)
            });
            commands = discord.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefix = "p!",
                EnableDms    = false
            });
            commands.RegisterCommands <MyCommands>();
            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
示例#30
0
        static async Task MainAsync(string[] args)
        {
            DiscordConfiguration discordConfiguration = new DiscordConfiguration();



            discordConfiguration.TokenType = TokenType.Bot;
            var    discord   = new DiscordClient(discordConfiguration);
            string BotAnswer = "";

            discord.MessageCreated += async e => {
                if (e.Message.Content.ToLower().StartsWith("!SHW".ToLower()))
                {
                    string message = e.Message.Content.ToLower();
                    message = message.Replace("!SHW".ToLower(), string.Empty);
                    message = message.Trim();

                    if (message.ToLower().StartsWith("admin".ToLower()))
                    {
                        #region AdminCommands
                        bool isAdmin = SqlFunctions.GetBotAdmins(e.Author.Id.ToString());
                        if (isAdmin)
                        {
                            message = message.Replace("admin".ToLower(), string.Empty);
                            message = message.Trim();

                            if (message.ToLower().StartsWith("add_admin".ToLower()))
                            {
                                var mentionedUser = e.Message.MentionedUsers;
                                foreach (DiscordUser discordUser in mentionedUser)
                                {
                                    string response = SqlFunctions.AddBotAdmins(discordUser.Id.ToString());
                                    await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n " + discordUser.Username + response);
                                }
                            }
                            if (message.ToLower().StartsWith("del_admin".ToLower()))
                            {
                                var mentionedUser = e.Message.MentionedUsers;
                                foreach (DiscordUser discordUser in mentionedUser)
                                {
                                    string response = SqlFunctions.DelBotAdmins(discordUser.Id.ToString());
                                    await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n " + discordUser.Username + response);
                                }
                            }
                            if (message.ToLower().StartsWith("add_host".ToLower()))
                            {
                                var mentionedUser = e.Message.MentionedUsers;
                                foreach (DiscordUser discordUser in mentionedUser)
                                {
                                    string response = SqlFunctions.AddBotHosts(discordUser.Id.ToString());
                                    await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n " + discordUser.Username + response);
                                }
                            }
                            if (message.ToLower().StartsWith("del_host".ToLower()))
                            {
                                var mentionedUser = e.Message.MentionedUsers;
                                foreach (DiscordUser discordUser in mentionedUser)
                                {
                                    string response = SqlFunctions.DelBotHosts(discordUser.Id.ToString());
                                    await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n " + discordUser.Username + response);
                                }
                            }
                        }
                        else
                        {
                            await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n You do Not Have Permissions to Use this Command");
                        }
                        #endregion
                    }
                    else if (message.ToLower().StartsWith("host".ToLower()))
                    {
                        #region SkillingHostCommands
                        bool isHost = SqlFunctions.GetBotHosts(e.Author.Id.ToString());
                        if (isHost)
                        {
                            message = message.Replace("host".ToLower(), string.Empty);
                            message = message.Trim();
                            if (message.ToLower().StartsWith("new".ToLower()))
                            {
                                message = message.Replace("new", string.Empty).Trim();
                                string[] CompSettingArray = message.Split('-');
                                foreach (string str in CompSettingArray)
                                {
                                    if (str.Contains("name"))
                                    {
                                        compSettings.Name = str.Split('"')[1];
                                    }
                                    if (str.Contains("start"))
                                    {
                                        compSettings.start = str.Split('"')[1];
                                    }
                                    if (str.Contains("end"))
                                    {
                                        compSettings.end = str.Split('"')[1];
                                    }
                                }
                                if (compSettings.Name != null && compSettings.start != null && compSettings.end != null)
                                {
                                    try {
                                        compSettings.status = "Awaiting";
                                        string response = SqlFunctions.CreateSkillingComp(compSettings);

                                        await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n Competition \"" + compSettings.Name + "\" " + response);
                                    } catch (Exception ex) {
                                        await e.Message.RespondAsync(ex + " " + ex.ToString());
                                    }
                                }
                                else
                                {
                                    await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n Missing Instructions make sure you've used the following syntax\n " +
                                                                 "!shw host new -name \"Skilling Name Super Here\" -start \"21/06/2020 12:00:00\" -end \"22/06/2020 00:00:00\"");
                                }
                            }
                        }
                        else
                        {
                            await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n You do Not Have Permissions to Use this Command");
                        }
                        #endregion
                    }
                    else
                    {
                        #region UserCommands
                        if (message.ToLower().StartsWith("commands".ToLower()))
                        {
                            Console.WriteLine(DateTime.Now + ": " + e.Message.Content);
                            await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n https://github.com/ShaggyHW/Rs3ServerSideXPTracker/blob/master/README.md");
                        }
                        if (message.ToLower().StartsWith("stats".ToLower()))
                        {
                            Console.WriteLine(DateTime.Now + ": " + e.Message.Content);
                            bool   alreadyAnswered = false;
                            string username        = "";
                            if (e.MentionedUsers.Count() > 0)
                            {
                                username = SqlFunctions.GetLinkedAccount(e.MentionedUsers[0].Id.ToString());
                            }
                            else
                            {
                                string[] mArray = message.Split(' ');
                                for (int i = 1; i < mArray.Length; i++)
                                {
                                    username += mArray[i] + " ";
                                }
                                username = username.Trim();
                                if (string.IsNullOrEmpty(username))
                                {
                                    username = SqlFunctions.GetLinkedAccount(e.Message.Author.Id.ToString());
                                }
                                else
                                {
                                    if (!alreadyAnswered)
                                    {
                                        alreadyAnswered = true;
                                        await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n No Linked Account Please use \"!SHW link username\" to link your discord and RS3 account");
                                    }
                                }
                            }
                            if (string.IsNullOrEmpty(username))
                            {
                                if (!alreadyAnswered)
                                {
                                    alreadyAnswered = true;
                                    await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n No Linked Account On Mentioned User! Please have him use \"!SHW link username\" to link his discord and RS3 account");
                                }
                            }
                            else
                            {
                                rs3Player = await functionsRS.GetCurrentStats(username);

                                if (rs3Player.Error != null)
                                {
                                    if (!string.IsNullOrEmpty(rs3Player.Error))
                                    {
                                        if (!alreadyAnswered)
                                        {
                                            alreadyAnswered = true;
                                            await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n" + rs3Player.Error + "");
                                        }
                                    }
                                    else
                                    {
                                        AnswerFormats answerFormats = new AnswerFormats();
                                        BotAnswer = await answerFormats.FormatXPAnswerTable(rs3Player, "Current");

                                        int xy = BotAnswer.Length;
                                        if (!alreadyAnswered)
                                        {
                                            alreadyAnswered = true;
                                            Console.WriteLine("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer);
                                            await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer + "");
                                        }
                                    }
                                }
                                else
                                {
                                    AnswerFormats answerFormats = new AnswerFormats();
                                    BotAnswer = await answerFormats.FormatXPAnswerTable(rs3Player, "Current");

                                    int xy = BotAnswer.Length;
                                    if (!alreadyAnswered)
                                    {
                                        alreadyAnswered = true;
                                        Console.WriteLine("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer);
                                        await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer + "");
                                    }
                                }
                            }
                        }
                        if (message.ToLower().StartsWith("link".ToLower()))
                        {
                            Console.WriteLine(DateTime.Now + ": " + e.Message.Content);
                            string[] mArray   = message.Split(' ');
                            string   username = "";
                            for (int i = 1; i < mArray.Length; i++)
                            {
                                username += mArray[i] + " ";
                            }
                            username = username.Trim();

                            rs3Player = await functionsRS.RegisterPlayer(username);

                            if (rs3Player.Error != null)
                            {
                                if (!string.IsNullOrEmpty(rs3Player.Error))
                                {
                                    await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n" + rs3Player.Error + "");
                                }
                                else
                                {
                                    BotAnswer = JsonConvert.SerializeObject(rs3Player);
                                    AnswerFormats answerFormats = new AnswerFormats();
                                    BotAnswer = await answerFormats.FormatXPAnswerTable(rs3Player, "Current");

                                    int xy = BotAnswer.Length;
                                    Console.WriteLine("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer);
                                    await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer + "");
                                }
                            }
                            else
                            {
                                SqlFunctions.CreateLink_DiscordAcc_Rs3Acc(username, e.Message.Author.Id.ToString());


                                Console.WriteLine("<@!" + e.Message.Author.Id + ">" + "\n" + username + " Linked with discord account");
                                await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n" + username + " Linked with discord account");
                            }
                        }
                        if (message.ToLower().StartsWith("new".ToLower()))
                        {
                            Console.WriteLine(DateTime.Now + ": " + e.Message.Content);

                            string[] mArray   = message.Split(' ');
                            string   username = "";
                            for (int i = 1; i < mArray.Length; i++)
                            {
                                username += mArray[i] + " ";
                            }
                            username = username.Trim();
                            var rs3Player = await functionsRS.RegisterPlayer(username);

                            if (rs3Player.Error != null)
                            {
                                if (!string.IsNullOrEmpty(rs3Player.Error))
                                {
                                    await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n" + rs3Player.Error + "");
                                }
                                else
                                {
                                    BotAnswer = JsonConvert.SerializeObject(rs3Player);
                                    AnswerFormats answerFormats = new AnswerFormats();
                                    BotAnswer = await answerFormats.FormatXPAnswerTable(rs3Player, "Current");

                                    int xy = BotAnswer.Length;
                                    Console.WriteLine("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer);
                                    await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer + "");
                                }
                            }
                            else
                            {
                                BotAnswer = JsonConvert.SerializeObject(rs3Player);
                                AnswerFormats answerFormats = new AnswerFormats();
                                BotAnswer = await answerFormats.FormatXPAnswerTable(rs3Player, "Current");

                                int xy = BotAnswer.Length;
                                Console.WriteLine("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer);
                                await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer + "");
                            }
                        }
                        if (message.ToLower().StartsWith("gains".ToLower()))
                        {
                            Console.WriteLine(DateTime.Now + ": " + e.Message.Content);
                            message = message.ToLower().Replace("gains", string.Empty).Trim();
                            bool   HasTimeParam = false;
                            string TimeParam    = "";
                            //!SHW GAINS -since "2020-06-23" ali the shag
                            if (message.ToLower().StartsWith("-since"))
                            {
                                HasTimeParam = true;
                                message      = message.Replace("-since", string.Empty).Trim();
                                TimeParam    = message.Split('"')[1];
                                message      = message.Split('"')[2].Trim();
                            }
                            bool   alreadyAnswered = false;
                            string username        = "";
                            if (e.MentionedUsers.Count() > 0)
                            {
                                username = SqlFunctions.GetLinkedAccount(e.MentionedUsers[0].Id.ToString());
                            }
                            else
                            {
                                string[] mArray = message.Split(' ');
                                for (int i = 1; i < mArray.Length; i++)
                                {
                                    username += mArray[i] + " ";
                                }
                                username = username.Trim();
                                if (string.IsNullOrEmpty(username))
                                {
                                    username = SqlFunctions.GetLinkedAccount(e.Message.Author.Id.ToString());
                                }
                                else
                                {
                                    if (!alreadyAnswered)
                                    {
                                        alreadyAnswered = true;
                                        await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n No Linked Account Please use \"!SHW link username\" to link your discord and RS3 account");
                                    }
                                }
                            }
                            if (string.IsNullOrEmpty(username))
                            {
                                if (!alreadyAnswered)
                                {
                                    alreadyAnswered = true;
                                    await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n No Linked Account On Mentioned User! Please have him use \"!SHW link username\" to link his discord and RS3 account");
                                }
                            }
                            else
                            {
                                if (HasTimeParam)
                                {
                                    rs3Player = await functionsRS.CalculateSince(username, TimeParam);
                                }
                                else
                                {
                                    rs3Player = await functionsRS.Calculate(username);
                                }
                                if (rs3Player.Error != null)
                                {
                                    if (!string.IsNullOrEmpty(rs3Player.Error))
                                    {
                                        if (!alreadyAnswered)
                                        {
                                            alreadyAnswered = true;
                                            await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n" + rs3Player.Error + "");
                                        }
                                    }
                                    else
                                    {
                                        BotAnswer = JsonConvert.SerializeObject(rs3Player);
                                        AnswerFormats answerFormats = new AnswerFormats();
                                        BotAnswer = await answerFormats.FormatXPAnswerTable(rs3Player, "Gainz");

                                        int xy = BotAnswer.Length;
                                        if (!alreadyAnswered)
                                        {
                                            alreadyAnswered = true;
                                            Console.WriteLine("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer);
                                            await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer + "");
                                        }
                                    }
                                }
                                else
                                {
                                    BotAnswer = JsonConvert.SerializeObject(rs3Player);
                                    AnswerFormats answerFormats = new AnswerFormats();
                                    BotAnswer = await answerFormats.FormatXPAnswerTable(rs3Player, "Gainz");

                                    int xy = BotAnswer.Length;
                                    if (!alreadyAnswered)
                                    {
                                        alreadyAnswered = true;
                                        Console.WriteLine("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer);
                                        await e.Message.RespondAsync("<@!" + e.Message.Author.Id + ">" + "\n" + BotAnswer + "");
                                    }
                                }
                            }
                        }

                        #endregion
                    }
                }
            };
            await discord.ConnectAsync();

            await Task.Delay(-1);
        }