static async Task MainAsync(string[] args) { discord = new DiscordClient(new DiscordConfiguration { Token = BotSettings.Token, TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Debug }); discord.MessageCreated += async e => { if (e.Message.Content.ToLower().StartsWith("ping")) { await e.Message.RespondAsync("Dropping Database.....(type 'pretty pony' to cancel within specified timeframe)"); } }; commands = discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = "." }); interactivity = discord.UseInteractivity(new InteractivityConfiguration { }); commands.RegisterCommands <MyCommands>(); await discord.ConnectAsync(); await Task.Delay(-1); }
public void Dispose() { _client.Dispose(); _interactivity = null; _cnext = null; _config = null; }
static async Task MainAsync(string[] args) { discord = new DiscordClient(new DiscordConfiguration { Token = await File.ReadAllTextAsync(@"..\..\..\..\secrets\token"), TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Debug }); discord.MessageCreated += async e => { if (e.Message.Content.ToLower().StartsWith("ping")) { await e.Message.RespondAsync("pong!"); } }; commands = discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = ";;" }); commands.RegisterCommands <SimpleCommands>(); interactivity = discord.UseInteractivity(new InteractivityConfiguration()); await discord.ConnectAsync(); System.Console.WriteLine("Connected to Discord"); await Task.Delay(-1); }
public async Task Start() { try { _discordClient = new DiscordClient(new DiscordConfiguration { TokenType = TokenType.Bot, Token = _configuration["Discord:Token"] }); _interactivity = _discordClient.UseInteractivity(new InteractivityConfiguration { PaginationBehaviour = TimeoutBehaviour.Delete, PaginationTimeout = TimeSpan.FromSeconds(30), Timeout = TimeSpan.FromSeconds(30) }); var deps = BuildDeps(); _commands = _discordClient.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = _configuration["Discord:CommandPrefix"], Dependencies = deps }); _commands.RegisterCommands <BotCommands>(); await RunAsync(); } catch (Exception exc) { Console.Error.WriteLine(exc.ToString()); } }
public void Dispose() { this._client.Dispose(); this._interactivity = null; this._cnext = null; this._config = null; }
static async Task MainAsync(string[] args) { discord = new DiscordClient(new DiscordConfiguration { Token = "token here", TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Debug }); commands = discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = "~" }); commands.RegisterCommands <Commands>(); interactivity = discord.UseInteractivity(new InteractivityConfiguration()); voice = discord.UseVoiceNext(); discord.SetWebSocketClient <WebSocket4NetCoreClient>(); await discord.ConnectAsync(); await Task.Delay(-1); }
public async Task Poll(CommandContext ctx, [Description("How long the poll should last.")] TimeSpan duration, [Description("What options should the poll have.")] params DiscordEmoji[] options) { ctx.Client.DebugLogger.LogMessage(LogLevel.Info, "PotatoBot", $"{ctx.Member.Username} started a poll between: {options.ToString()}", DateTime.Now); // Load interactivity module and poll options InteractivityModule interactivity = ctx.Client.GetInteractivityModule(); var pollOptions = options.Select(xe => xe.ToString()); // Display the poll var embed = new DiscordEmbedBuilder { Title = "Poll Time!", Color = DiscordColor.DarkButNotBlack, Description = "Choose your fighter: " + string.Join(" ", pollOptions) }; DiscordMessage msg = await ctx.RespondAsync(embed : embed); // Add options as reactions for (int i = 0; i < options.Length; i++) { await msg.CreateReactionAsync(options[i]); } // Collect responses ReactionCollectionContext pollResult = await interactivity.CollectReactionsAsync(msg, duration); //TODO: Why this not working? var results = pollResult.Reactions.Where(xkvp => options.Contains(xkvp.Key)) .Select(xkvp => $"{xkvp.Key}: {xkvp.Value}"); // Post response await ctx.RespondAsync(string.Join("\n", results)); }
static async Task MainAsync(string[] args) { discord = new DiscordClient(new DiscordConfiguration { Token = "NDM5NDc1MjA5Mjk3MzMwMTgw.DcTtBA.w1MhM-5h-s1ZjYilzizNVwJ0hQw", TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Debug }); discord.MessageCreated += async e => { if (e.Message.Content.ToLower().StartsWith("ping")) { await e.Message.RespondAsync("pong!"); } }; commands = discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = ";;" }); commands.RegisterCommands <Commands>(); interactivity = discord.UseInteractivity(new InteractivityConfiguration()); await discord.ConnectAsync(); await Task.Delay(-1); }
public Drifter(DiscordClient client) { _instance = this; this._discord = client; this.redis = new CSRedisClient("localhost"); this.redis.SetDatabase(1).Wait(); this._rolemap = new RoleMap(this.redis); _interactivity = Discord.UseInteractivity(new InteractivityConfiguration() { }); _commands = Discord.UseCommandsNext(new CommandsNextConfiguration() { StringPrefix = ";" }); Commands.RegisterCommands <Commands.AdminCommands>(); Commands.RegisterCommands <Commands.MemeCommands>(); Commands.RegisterCommands <Commands.UtilityCommands>(); //Commands.RegisterCommands<Commands.VoiceCommand>(); Commands.RegisterCommands <Commands.ReactionRoleCommands>(); client.MessageReactionAdded += OnReactionAdded; client.MessageReactionRemoved += OnReactionRemoved; //client.VoiceStateUpdated += OnVoiceChange; }
static async Task MainAsync(string[] args) { discord = new DiscordClient(new DiscordConfiguration { Token = Environment.GetEnvironmentVariable("BOTTOKEN"), TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Debug }); interactivity = discord.UseInteractivity( new InteractivityConfiguration() { Timeout = TimeSpan.FromMinutes(1), PaginationTimeout = TimeSpan.FromMinutes(1), PaginationBehaviour = TimeoutBehaviour.Ignore }); commands = discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = "!", CaseSensitive = false }); commands.RegisterCommands <Commands> (); await discord.ConnectAsync(); await Task.Delay(-1); }
[RequirePermissions(Permissions.ManageRoles)] // and restrict this to users who have appropriate permissions public async Task WaitForCode(CommandContext ctx) { // first retrieve the interactivity module from the client InteractivityModule interactivity = ctx.Client.GetInteractivityModule(); // generate a code byte[] codebytes = new byte[8]; using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(codebytes); } string code = BitConverter.ToString(codebytes).ToLower().Replace("-", ""); // announce the code await ctx.RespondAsync($"The first one to type the following code gets a reward: `{code}`"); // wait for anyone who types it MessageContext msg = await interactivity.WaitForMessageAsync(xm => xm.Content.Contains(code), TimeSpan.FromSeconds(60)); if (msg != null) { // announce the winner await ctx.RespondAsync($"And the winner is: {msg.Message.Author.Mention}"); } else { await ctx.RespondAsync("Nobody? Really?"); } }
static async Task MainAsync(string[] args) { discord = new DiscordClient(new DiscordConfiguration() { Token = "",//TODO insert your bot token here TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Debug }); discord.MessageCreated += async e => { if (e.Message.Content.ToLower().Contains("ping")) { await e.Message.RespondAsync("pong!"); } }; commands = discord.UseCommandsNext(new CommandsNextConfiguration() { StringPrefix = ";;", CaseSensitive = false }); commands.RegisterCommands <MyCommands>(); interactivity = discord.UseInteractivity(new InteractivityConfiguration()); await discord.ConnectAsync(); await Task.Delay(-1); }
public async Task Poll(CommandContext ctx, [Description("How long should the poll last.")] TimeSpan duration, [Description("What options should people have.")] params DiscordEmoji[] options) { // first retrieve the interactivity module from the client InteractivityModule interactivity = ctx.Client.GetInteractivityModule(); var poll_options = options.Select(xe => xe.ToString()); // then let's present the poll DiscordEmbedBuilder embed = new DiscordEmbedBuilder { Title = "Poll time!", Description = string.Join(" ", poll_options) }; DiscordMessage msg = await ctx.RespondAsync(embed : embed); // add the options as reactions for (int i = 0; i < options.Length; i++) { await msg.CreateReactionAsync(options[i]); } // collect and filter responses ReactionCollectionContext poll_result = await interactivity.CollectReactionsAsync(msg, duration); var results = poll_result.Reactions.Where(xkvp => options.Contains(xkvp.Key)) .Select(xkvp => $"{xkvp.Key}: {xkvp.Value}"); // and finally post the results await ctx.RespondAsync(string.Join("\n", results)); }
public static async Task AsyncMain(string[] args) { if (args.Length < 2) { Console.WriteLine("You must pass at minimum 2 arguments: -t \"Token\""); return; } if (args[0].Equals("-t")) { discord = new DiscordClient(new DiscordConfiguration { Token = args[1], TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Debug }); interactivity = discord.UseInteractivity(new InteractivityConfiguration()); commands = discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = "::", }); /* * Code below this line must be left intact. */ commands.RegisterCommands <Commands>(); await discord.ConnectAsync(); await Task.Delay(-1); } else { Console.Write("Invalid Arugment"); } }
static async Task MainAsync(string[] args) { discord = new DiscordClient(new DiscordConfiguration { //Searches the Windows Environement Variables for the token Token = Environment.GetEnvironmentVariable("TOKEN"), TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Debug }); discord.SetWebSocketClient <WebSocketSharpClient>(); commands = discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = "!" });; commands.RegisterCommands <Commands>(); 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) }); await discord.ConnectAsync(); await Task.Delay(-1); }
public void Dispose() { _discord.Dispose(); _interactivity = null; _commands = null; _config = null; }
async Task InitBot(string[] args) { try { Console.WriteLine("[info] David is starting"); _cts = new CancellationTokenSource(); Console.WriteLine("[info] Loading config file.."); _config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config.json", optional: false, reloadOnChange: true) .Build(); Console.WriteLine("[info] Creating discord client.."); _discord = new DiscordClient(new DiscordConfiguration { Token = _config.GetValue <string>("discord:token"), TokenType = TokenType.Bot }); _interactivity = _discord.UseInteractivity(new InteractivityConfiguration() { PaginationBehaviour = TimeoutBehaviour.Delete, PaginationTimeout = TimeSpan.FromSeconds(30), Timeout = TimeSpan.FromSeconds(30) }); var deps = BuildDeps(); _commands = _discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = _config.GetValue <string>("discord:CommandPrefix"), Dependencies = deps }); Console.WriteLine("[info] Loading command modules.."); var type = typeof(IModule); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => type.IsAssignableFrom(p) && !p.IsInterface); var typeList = types as Type[] ?? types.ToArray(); foreach (var t in typeList) { _commands.RegisterCommands(t); } Console.WriteLine($"[info] Loaded {typeList.Count()} modules."); RunAsync(args).Wait(); } catch (Exception ex) { Console.Error.WriteLine(ex.ToString()); } }
public async Task ClearEmoji(CommandContext c) { if (c.Guild == null) { throw new InvalidOperationException("You cannot modify emojis in a DM."); } InteractivityModule i = c.Client.GetInteractivityModule(); IReadOnlyList <DiscordGuildEmoji> emojis = await c.Guild.GetEmojisAsync(); if (!emojis.Any()) { await c.RespondAsync("You have no emoji on this server to remove."); return; } DiscordMessage m = await c.RespondAsync("Are you sure that you want to clear all emoji from this server?"); await m.CreateReactionAsync(Reactions.YES); await m.CreateReactionAsync(Reactions.NO); ReactionContext react = await i.WaitForReactionAsync(x => x == Reactions.YES || x == Reactions.NO, c.User, TimeSpan.FromSeconds(30)); await m.DeleteAsync(); if (react != null) { if (react.Message == m) { DiscordMessage clear = await c.RespondAsync("Alright, I'm clearing all of the emojis on this server... This will take a couple of minutes due to Discord's ratelimits."); foreach (DiscordGuildEmoji e in emojis) { try { await c.Guild.DeleteEmojiAsync(e); } catch (BadRequestException) { await c.RespondAsync("I failed to delete the emoji. Discord gave me a bad response."); return; } } await clear.ModifyAsync("I've cleared all of the emojis on this server."); } else { await c.RespondAsync("You did not react to the original message. Aborting."); return; } } else { await c.RespondAsync("No response was given. Aborting."); } }
public Bot() { if (!File.Exists("config.json")) { configNotFound(); } _config = Config.LoadFromFile("config.json"); _discord = new DiscordClient(new DiscordConfiguration() { AutoReconnect = true, EnableCompression = true, LogLevel = LogLevel.Debug, Token = _config.Token, TokenType = TokenType.Bot, UseInternalLogHandler = true }); _cts = new CancellationTokenSource(); _interactivity = _discord.UseInteractivity(new InteractivityConfiguration()); //// DependencyCollection dep = null; using (var d = new DependencyCollectionBuilder()) { d.AddInstance(new Dependencies() { Interactivity = _interactivity, // StartTimes = _starttimes, Cts = _cts }); dep = d.Build(); } /// _commands = _discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = _config.Prefix, EnableDms = false, Dependencies = dep, IgnoreExtraArguments = true, EnableDefaultHelp = true, CaseSensitive = false, EnableMentionPrefix = true, }); _commands.RegisterCommands <Generals>(); _commands.RegisterCommands <Owner>(); /// _discord.MessageCreated += async e => { if (e.Message.Content.ToLower().StartsWith("ping")) { await e.Message.RespondAsync("pong!"); } }; }
public Dependencies(InteractivityModule interactivity, WebhookController whm, SubscriptionProcessor subProcessor, WhConfigHolder whConfig, StripeService stripe) { Interactivity = interactivity; Whm = whm; SubscriptionProcessor = subProcessor; _configHolder = whConfig; Stripe = stripe; OsmManager = new OsmManager(); }
static async Task MainAsync(string[] arg) { discord = new DiscordClient(new DiscordConfiguration //initializes the bot! { Token = "", TokenType = TokenType.Bot, UseInternalLogHandler = true, //output all state and doings in console LogLevel = LogLevel.Debug, }); discord.MessageCreated += async e => // MessageCreated is the event, += is subscribing the method to the event. When a MessageCreate event triggers, our method will run // async e is an async method. Async will run non blocking // e => is a lambda expression. It takes in input parameter e and returns with the statement { if (e.Message.Content.ToLower().StartsWith("ping")) { // await suspends execution of this method until the task is complete. // In this example, we suspend this method and wait for our message to parse. // control resumes here when e.message.content.tolower().startswith is complete //got em await e.Message.RespondAsync("pong!"); } }; commands = discord.UseCommandsNext(new CommandsNextConfiguration //configure the prefix with the commands { StringPrefix = ".", EnableDms = false }); commands.RegisterCommands <MyCommands>(); interactivity = discord.UseInteractivity(new InteractivityConfiguration //default configurations { // set default to delete reactions PaginationBehaviour = TimeoutBehaviour.Delete, // default pagination timeout to 5 minutes PaginationTimeout = TimeSpan.FromMinutes(1), // default timeout for other actions to 2 minutes Timeout = TimeSpan.FromMinutes(1) }); voice = discord.UseVoiceNext(); await discord.ConnectAsync(); //Have to await an async method (Also why we had to make an async main task) await Task.Delay(-1); // Prevent the bot from flashing and quitting immediately }
static async Task Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", false, true) .AddJsonFile("secrets.json", true, true); Configuration = builder.Build(); // Use this if you want App_Data off your project root folder string baseDir = Directory.GetCurrentDirectory(); AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.Combine(baseDir, "DataFiles")); discord = new DiscordClient(new DiscordConfiguration { Token = Environment.GetEnvironmentVariable("DiscordAPIKey") ?? Configuration["token"], TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Debug }); commands = discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = Configuration["commandPrefix"], CaseSensitive = false }); commands.RegisterCommands <Commands.DiceCommands>(); commands.RegisterCommands <Commands.CypherCommands>(); commands.RegisterCommands <Commands.AdminCommands>(); interactivity = discord.UseInteractivity(new InteractivityConfiguration() { }); //Initialize the database and migrate on start. var db = new CypherContext(); db.Database.Migrate(); if (Configuration["appInitialize"].ToLower() == "true") { Console.WriteLine("Initializing the database."); await Utilities.DatabaseHelper.InitializeDatabaseAsync(); Console.WriteLine("Database Initialized, please set the appInitialize flag in appsettings.json to false in order to stop the database from being overridden again."); System.Threading.Thread.Sleep(3000); } await discord.ConnectAsync(); await Task.Delay(-1); }
public async Task open(CommandContext ctx) { interactivity = ctx.Dependencies.GetDependency <InteractivityModule>(); await ctx.RespondAsync(ctx.Guild.EveryoneRole.Mention + " Signup is open Now!"); IsOpen = true; RequestChecker = new Task(CheckRequests); CheckingEnabled = true; RequestChecker.Start(); }
public Dependencies(InteractivityModule interactivity, WebhookManager whm, SubscriptionProcessor subProcessor, WhConfig whConfig, Translator language, StripeService stripe) { Interactivity = interactivity; Whm = whm; SubscriptionProcessor = subProcessor; WhConfig = whConfig; Language = language; Stripe = stripe; OsmManager = new OsmManager(); }
async Task InitBot(string[] args) { try { Console.WriteLine("[info] Welcome to the Turnip Bot!"); _cts = new CancellationTokenSource(); // Load the config file(we'll create this shortly) Console.WriteLine("[info] Loading config file.."); _config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config.json", optional: false, reloadOnChange: true) .Build(); // Create the DSharpPlus client Console.WriteLine("[info] Creating discord client.."); _discord = new DiscordClient(new DiscordConfiguration { Token = _config.GetValue <string>("discord:token"), TokenType = TokenType.Bot, AutoReconnect = true }); // Create the interactivity module(I'll show you how to use this later on) _interactivity = _discord.UseInteractivity(new InteractivityConfiguration() { PaginationBehaviour = TimeoutBehaviour.Delete, // What to do when a pagination request times out PaginationTimeout = TimeSpan.FromSeconds(30), // How long to wait before timing out Timeout = TimeSpan.FromSeconds(30) // Default time to wait for interactive commands like waiting for a message or a reaction }); // Build dependancies and then create the commands module. _commands = _discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = _config.GetValue <string>("discord:CommandPrefix"), // Load the command prefix(what comes before the command, eg "!" or "/") from our config file EnableDms = true }); // TODO: Add command loading! Console.WriteLine("[info] Loading command modules.."); _commands.RegisterCommands <TurnipCommands>(); _commands.RegisterCommands <SellCommands>(); RunAsync(args).Wait(); } catch (Exception ex) { // This will catch any exceptions that occur during the operation/setup of your bot. // Feel free to replace this with what ever logging solution you'd like to use. // I may do a guide later on the basic logger I implemented in my most recent bot. Console.Error.WriteLine(ex.ToString()); } }
public OysterMain( IOptions <BotSettings> options, ILogger <OysterMain> logger, DiscordClient client, InteractivityModule interactivity ) { _logger = logger; _client = client; _interactivity = interactivity; _settings = options.Value; }
public Bot() { var config = ConfigBuilder.Build(); _config = config; _discord = new DiscordClient(config.DiscordConfiguration); _commands = _discord.UseCommandsNext(config.CommandsNextConfiguration); _commands.RegisterCommands <Commands>(); _interactivity = _discord.UseInteractivity(new InteractivityConfiguration()); }
public async Task InitBot(string[] args) { try { Cts = new CancellationTokenSource(); _config = Program.BotConfig; Console.WriteLine("[Discord] Creating Discord client"); _discord = new DiscordClient(new DiscordConfiguration { Token = _config.GetValue <string>("discord:Token"), TokenType = TokenType.Bot }); _interactivity = _discord.UseInteractivity(new InteractivityConfiguration() { PaginationBehaviour = TimeoutBehaviour.Delete, PaginationTimeout = TimeSpan.FromSeconds(30), Timeout = TimeSpan.FromSeconds(30) }); var deps = BuildDependencies(); _commands = _discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = _config.GetValue <string>("discord:CommandPrefix"), Dependencies = deps }); Console.WriteLine("[Discord] Loading command modules"); var type = typeof(IModule); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => type.IsAssignableFrom(p) && !p.IsInterface); var typeList = types as Type[] ?? types.ToArray(); foreach (var t in typeList) { _commands.RegisterCommands(t); } Console.WriteLine($"[Discord] Loaded {typeList.Count()} modules"); await RunAsync(args); } catch (Exception ex) { Console.Error.WriteLine(ex.ToString()); } }
static public async Task RunAsync(string[] args) { discord = new DiscordClient(BotConfig.GetDiscordConfiguration("config.json")); interactivity = discord.UseInteractivity(new InteractivityConfiguration()); commands = discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = BotConfig.Prefix }); commands.RegisterCommands <CommandsContainer>(); await discord.ConnectAsync(); await Task.Delay(-1); }
static async Task MainAsync(string[] args) { discord = new DiscordClient(new DiscordConfiguration { Token = args[0], TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Debug }); interactivity = discord.UseInteractivity(new InteractivityConfiguration()); //responds to message with kimchi discord.MessageCreated += async e => { if (e.Message.Content.ToLower().StartsWith("kimchi")) { await e.Message.RespondAsync("hi, want sum Kimchi?"); } }; discord.MessageCreated += async e => { if (e.Message.Content.ToLower().StartsWith("no ty")) { await e.Message.RespondAsync("get outta here!! ಠ_ಠ"); } }; discord.MessageCreated += async e => { if (e.Message.Content.ToLower().StartsWith("yes plis")) { await e.Message.RespondAsync("Daily Menu\n```\nNoodles\nCookies```"); } }; //command using prefix "pls" commands = discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = "pls" }); commands.RegisterCommands <MyCommands>(); await discord.ConnectAsync(); await Task.Delay(-1); }