public BotAmongUs(JsonConfiguration configuration) { _Configuration = configuration; var config = new DiscordConfiguration { Token = _Configuration.Token, TokenType = TokenType.Bot, AutoReconnect = true, MinimumLogLevel = LogLevel.Debug }; _Client = new DiscordClient(config); var commands = new CommandsNextConfiguration { StringPrefixes = new List <string> { _Configuration.Prefix }, EnableDms = false, Services = GetServiceProvider() }; _CommandsExtension = _Client.UseCommandsNext(commands); _CommandsExtension.RegisterCommands <TextCommands>(); var interactivityConfiguration = new InteractivityConfiguration { Timeout = TimeSpan.FromMinutes(5) }; _Client.UseInteractivity(interactivityConfiguration); _Client.Ready += OnClientIsReady; _Client.GuildAvailable += OnGuildAvailable; }
public static void InitializeBot(Config config) { var clientConfiguration = new DiscordConfiguration { Token = config.GetToken(), TokenType = TokenType.Bot, AutoReconnect = true, Intents = DiscordIntents.AllUnprivileged, MinimumLogLevel = LogLevel.Information, }; var commandsConfig = new CommandsNextConfiguration { StringPrefixes = config.GetCommandPrefix(), EnableDms = true, EnableMentionPrefix = true, }; var interactivityConfig = new InteractivityConfiguration { PollBehaviour = PollBehaviour.KeepEmojis, Timeout = TimeSpan.FromSeconds(30), }; Client = new DiscordClient(clientConfiguration); Client.UseInteractivity(interactivityConfig); _commands = Client.UseCommandsNext(commandsConfig); _commands.RegisterCommands <RoleBotCommandModule>(); DbAccess = new DataAccessHelper("database.db"); }
public Bot(BotConfig botConfig, DBConfig dBConfig) { DiscordConfiguration discordConfiguration = new DiscordConfiguration { Token = botConfig.Token, TokenType = TokenType.Bot, LogLevel = LogLevel.Debug, UseInternalLogHandler = true, ShardCount = 1, ShardId = 0 }; ServiceProvider deps = new ServiceCollection() .AddSingleton(httpClient) .AddSingleton(utility) .AddSingleton(new WeebShAPIClient(botConfig.WeebSHToken, httpClient)) .AddDbContext <LanguageManager>(x => x.UseNpgsql(dBConfig.ConnString), ServiceLifetime.Transient) .AddDbContext <UserManager>(x => x.UseNpgsql(dBConfig.ConnString), ServiceLifetime.Transient) .BuildServiceProvider(); CommandsNextConfiguration commandsNextConfiguration = new CommandsNextConfiguration { StringPrefixes = new [] { botConfig.BetaPrefix }, Services = deps }; InteractivityConfiguration interactivityConfiguration = new InteractivityConfiguration { PaginationBehaviour = PaginationBehaviour.WrapAround, PaginationDeletion = PaginationDeletion.DeleteEmojis, PollBehaviour = PollBehaviour.DeleteEmojis }; VoiceNextConfiguration voiceNextConfiguration = new VoiceNextConfiguration { AudioFormat = AudioFormat.Default }; this.discordClient = new DiscordClient(discordConfiguration); this.commandsNextExtension = this.discordClient.UseCommandsNext(commandsNextConfiguration); this.interactivityExtension = this.discordClient.UseInteractivity(interactivityConfiguration); this.voiceNextExtension = this.discordClient.UseVoiceNext(voiceNextConfiguration); this.discordClient.ClientErrored += e => {; Console.WriteLine("Client Error:"); Console.WriteLine(e.EventName); Console.WriteLine(e.Exception); return(Task.CompletedTask); }; this.discordClient.SocketErrored += e => { Console.WriteLine("Socket Error:"); Console.WriteLine(e.Exception); return(Task.CompletedTask); }; this.discordClient.GuildDownloadCompleted += e => { this.commandsNextExtension.RegisterCommands <Dev>(); foreach (var f in Directory.EnumerateFiles(@"Commands\\")) { using (ZipFile zip = ZipFile.Read(@$ "{f}")) { var dll = zip.First(x => x.FileName.EndsWith(".dll")); var splitFileName = dll.FileName.Split('.'); var group = splitFileName[^ 2];
private async Task RunCopebot() { string json; using (var stream = File.OpenRead(Path.Combine(Environment.CurrentDirectory, "config.json"))) using (var reader = new StreamReader(stream, new UTF8Encoding(false))) json = await reader.ReadToEndAsync(); var configJson = JsonConvert.DeserializeObject <ConfigJson>(json); var config = new DiscordConfiguration { Token = configJson.MainToken, TokenType = TokenType.Bot, AutoReconnect = true, LogLevel = LogLevel.Info, UseInternalLogHandler = true }; var eventHandlers = new EventHandlers(configJson.TypingChannelId); Client = new DiscordClient(config); Client.MessageCreated += eventHandlers.Bot_MessageCreated; Client.ChannelPinsUpdated += eventHandlers.Bot_PinsUpdated; Client.TypingStarted += eventHandlers.Bot_TypingStarted; var interactivityConfig = new InteractivityConfiguration { Timeout = TimeSpan.FromMinutes(1.0) }; Client.UseInteractivity(interactivityConfig); var prefixes = new List <string> { configJson.CommandPrefix }; var minecraftServerHelper = new MinecraftServerHelper(HttpClient, configJson.ImgbbApiKey); var services = new ServiceCollection() .AddSingleton(minecraftServerHelper) .BuildServiceProvider(); var commandsConfig = new CommandsNextConfiguration { StringPrefixes = prefixes, Services = services, EnableMentionPrefix = true, EnableDms = true }; Commands = Client.UseCommandsNext(commandsConfig); Commands.RegisterCommands <UngroupedBotCommands>(); Commands.RegisterCommands <BotUserCommands>(); await Client.ConnectAsync(); await Task.Delay(-1); }
public DiscordConfiguration GetDiscordClientConfig() { _interactivity = new InteractivityConfiguration(); // Create bot with config from json 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); var config = new DiscordConfiguration { Token = ConfigJson.Token, TokenType = TokenType.Bot, AutoReconnect = true, LogLevel = LogLevel.Debug, UseInternalLogHandler = true, }; return(config); }
public DiscordWrapper(IOptions <DiscordConfig> options, IServiceProvider services, CommandConfigurator configurator, ILoggerFactory loggerFactory) { DiscordConfig optionsConfig = options.Value; var config = new DiscordConfiguration() { LoggerFactory = loggerFactory, Token = optionsConfig.Token, TokenType = TokenType.Bot, Intents = DiscordIntents.All }; Client = new DiscordClient(config); CommandsNextConfiguration cConfig = new() { Services = services, StringPrefixes = optionsConfig.Prefixes, EnableDms = true }; Commands = Client.UseCommandsNext(cConfig); InteractivityConfiguration iConfig = new InteractivityConfiguration() { PollBehaviour = PollBehaviour.KeepEmojis, Timeout = TimeSpan.FromSeconds(30) }; Interactivity = Client.UseInteractivity(iConfig); Client.Logger.LogInformation("Starting with secret: {0}", options.Value.Token); } }
private void InitializeInteractivity() { var interactivityConfig = new InteractivityConfiguration { PaginationBehaviour = PaginationBehaviour.Ignore, Timeout = TimeSpan.FromMinutes(2) }; Client.UseInteractivity(interactivityConfig); }
private static InteractivityExtension SetupInteractivity() { var interactivityConfig = new InteractivityConfiguration { PaginationBehaviour = PaginationBehaviour.Ignore, Timeout = TimeSpan.FromMinutes(5), PollBehaviour = PollBehaviour.KeepEmojis }; var interactivity = _discordClient.UseInteractivity(interactivityConfig); return(interactivity); }
public async Task RunBotAsync(string[] args) { try { _config = new ConfigurationBuilder() .AddUserSecrets(typeof(Program).Assembly, optional: false, reloadOnChange: true) .Build(); Client = new DiscordClient(new DiscordConfiguration { Token = _config["discord:token"], AutoReconnect = true, TokenType = TokenType.Bot, MinimumLogLevel = LogLevel.Debug | LogLevel.Information, }); InteractivityConfig = new InteractivityConfiguration { PaginationBehaviour = PaginationBehaviour.WrapAround, Timeout = TimeSpan.FromSeconds(30) }; Client.UseInteractivity(InteractivityConfig); var deps = BuildDeps(); CommandsNextConfig = new CommandsNextConfiguration { CaseSensitive = false, StringPrefixes = new List <string> { CommandPrefix, }, Services = deps }; Client.UseCommandsNext(CommandsNextConfig); MessagesHandler.Init(Client); RegisterCommandClasses(); await ConnectAndRunAsync(args); } catch (Exception ex) { Console.Error.WriteLine(ex.ToString()); } }
public async Task StartAsync(CancellationToken stoppingToken) { // Configuration settings for bot var botConfig = new DiscordConfiguration { AutoReconnect = true, Token = _settings.Discord.Token, TokenType = TokenType.Bot, LoggerFactory = _factory }; var cmdConfig = new CommandsNextConfiguration { EnableDefaultHelp = true, EnableDms = false, EnableMentionPrefix = true, Services = _sp, StringPrefixes = _settings.Discord.CommandPrefixes }; var interactivityConfig = new InteractivityConfiguration { Timeout = TimeSpan.FromSeconds(30), PaginationBehaviour = DSharpPlus.Interactivity.Enums.PaginationBehaviour.WrapAround, PaginationDeletion = DSharpPlus.Interactivity.Enums.PaginationDeletion.DeleteEmojis }; // Initialize the bot _discordClient = new DiscordClient(botConfig); _discordClient.UseCommandsNext(cmdConfig); _discordClient.UseInteractivity(interactivityConfig); // Add commands using assembly reflection // This will load all the commands from the commands folder _discordClient.GetCommandsNext().RegisterCommands(Assembly.GetEntryAssembly()); // Event listeners for guild activity _discordClient.GuildCreated += _discordClient_GuildHandler; _discordClient.GuildAvailable += _discordClient_GuildHandler; _discordClient.GuildDeleted += _discordClient_GuildDeleted; // Event listeners for bot actions _watcherService.OnGameAction += _watcherService_OnGameActionHandler; _watcherService.OnPlayerAction += _watcherService_OnPlayerActionHandler; await _discordClient.ConnectAsync(); await _watcherService.StartAsync(stoppingToken); }
private InteractivityConfiguration GetInteractivityConfiguration() { var icfg = new InteractivityConfiguration { // default pagination behaviour to just ignore the reactions PaginationDeletion = DSharpPlus.Interactivity.Enums.PaginationDeletion.DeleteEmojis, // default pagination timeout to 5 minutes //PaginationTimeout = TimeSpan.FromMinutes(5), // default timeout for other actions to 2 minutes Timeout = TimeSpan.FromMinutes(2) }; return(icfg); }
internal Bot(IServiceProvider serviceProvider, BotConfiguration botConfiguration) { _serviceProvider = serviceProvider; _botConfiguration = botConfiguration; var discordConfig = new DiscordConfiguration { Token = _botConfiguration.DiscordToken, LogLevel = LogLevel.Debug, UseInternalLogHandler = false, ReconnectIndefinitely = true }; _discordClient = new DiscordClient(discordConfig); var interactivityConfig = new InteractivityConfiguration { PaginationBehaviour = PaginationBehaviour.Ignore }; _discordClient.UseInteractivity(interactivityConfig); var commandsConfig = new CommandsNextConfiguration { StringPrefixes = new[] { COMMAND_PREFIX }, Services = serviceProvider, CaseSensitive = false, EnableMentionPrefix = false }; _commandsNextConfig = commandsConfig; _commands = _discordClient.UseCommandsNext(commandsConfig); _commands.RegisterCommands(Assembly.GetExecutingAssembly()); _commands.SetHelpFormatter <HelpFormatter>(); _discordClient.DebugLogger.LogMessageReceived += OnLogMessageReceived; _discordClient.GuildCreated += OnGuildAvailable; _discordClient.GuildDeleted += OnGuildDeleted; _discordClient.GuildMemberAdded += OnGuildMemberAdded; _discordClient.GuildMemberRemoved += OnGuildMemberRemoved; _discordClient.Ready += _ => Task.FromResult(_clientIsReady = true); _commands.CommandErrored += OnCommandError; }
public BotService( ILoggerFactory loggerFactory, IOptions <BotConfig> botConfig, IBotAccessProviderBuilder dataAccessProviderBuilder, IDateTimeZoneProvider timeZoneProvider, IServiceProvider services) { DiscordConfiguration ClientConfig = new DiscordConfiguration { Token = botConfig.Value.BotToken, TokenType = TokenType.Bot, MinimumLogLevel = LogLevel.Information, LoggerFactory = loggerFactory, Intents = DiscordIntents.All, }; this.commandsConfig = new CommandsNextConfiguration { PrefixResolver = PrefixResolver, Services = services, EnableDms = true, EnableMentionPrefix = true, }; this.interactivityConfig = new InteractivityConfiguration { PaginationBehaviour = PaginationBehaviour.Ignore, Timeout = TimeSpan.FromMinutes(2), }; this.Client = new DiscordShardedClient(ClientConfig); this._devUserId = botConfig.Value.DevId; this.logger = loggerFactory.CreateLogger("BotService"); this.providerBuilder = dataAccessProviderBuilder; this.timeZoneProvider = timeZoneProvider; using IBotAccessProvider provider = providerBuilder.Build(); provider.Migrate(); }
public DiscordService( IServiceProvider services, BotContext botContext, ILoggerFactory loggerFactory, IOptions <DiscordOptions> options, ILogger <DiscordService> logger) { _botContext = botContext; _logger = logger; // Discord configuration var discordOptions = options.Value; var discordConfiguration = new DiscordConfiguration { Token = discordOptions.Token, ShardCount = discordOptions.ShardCount, MinimumLogLevel = discordOptions.LogLevel, Intents = discordOptions.Intents, LoggerFactory = loggerFactory.AddSerilog() }; // Commands configuration Prefix = discordOptions.Prefix; var commandsConfiguration = new CommandsNextConfiguration { PrefixResolver = PrefixResolver, Services = services }; // Interactivity configuration var interactivityConfiguration = new InteractivityConfiguration(); // Initialize objects Discord = new DiscordClient(discordConfiguration); Commands = Discord.UseCommandsNext(commandsConfiguration); Interactivity = Discord.UseInteractivity(interactivityConfiguration); Commands.RegisterCommands(Assembly.GetExecutingAssembly()); // Subscribe to events Commands.CommandErrored += CommandsOnCommandErrored; }
/// <summary> /// Starts the Bot. /// </summary> /// <returns></returns> public async Task Start() { // Init Initialize(); SetUpEvents(); InstallCommands(); var icfg = new InteractivityConfiguration() { PaginationBehaviour = TimeoutBehaviour.Delete, PaginationTimeout = TimeSpan.FromSeconds(30), Timeout = TimeSpan.FromSeconds(30) }; _client.UseInteractivity(icfg); // Connect our client this._client.DebugLogger.Log("Connecting."); await this._client.ConnectAsync(); await Task.Delay(-1); }
public TestBot(TestBotConfig cfg, int shardid) { // global bot config this.Config = cfg; // discord instance config and the instance itself var dcfg = new DiscordConfiguration { AutoReconnect = true, LargeThreshold = 250, LogLevel = LogLevel.Debug, Token = this.Config.Token, TokenType = this.Config.UseUserToken ? TokenType.User : TokenType.Bot, UseInternalLogHandler = false, ShardId = shardid, ShardCount = this.Config.ShardCount, EnableCompression = true, MessageCacheSize = 50, AutomaticGuildSync = !this.Config.UseUserToken, DateTimeFormat = "dd-MM-yyyy HH:mm:ss zzz" }; Discord = new DiscordClient(dcfg); // events Discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageReceived; Discord.Ready += this.Discord_Ready; Discord.GuildAvailable += this.Discord_GuildAvailable; Discord.GuildBanAdded += this.Discord_GuildBanAdd; Discord.MessageCreated += this.Discord_MessageCreated; Discord.MessageReactionAdded += this.Discord_MessageReactionAdd; Discord.MessageReactionsCleared += this.Discord_MessageReactionRemoveAll; Discord.PresenceUpdated += this.Discord_PresenceUpdate; Discord.ClientErrored += this.Discord_ClientErrored; Discord.SocketErrored += this.Discord_SocketError; Discord.GuildCreated += this.Discord_GuildCreated; // voice config and the voice service itself var vcfg = new VoiceNextConfiguration { VoiceApplication = VoiceNext.Codec.VoiceApplication.Music, EnableIncoming = false }; this.VoiceService = this.Discord.UseVoiceNext(vcfg); // build a dependency collection for commandsnext var depco = new DependencyCollectionBuilder(); depco.AddInstance("This is a dependency string."); depco.Add <TestDependency>(); // commandsnext config and the commandsnext service itself var cncfg = new CommandsNextConfiguration { StringPrefix = this.Config.CommandPrefix, CustomPrefixPredicate = msg => { if (TestBotNextCommands.Prefixes.ContainsKey(msg.Channel.Id) && TestBotNextCommands.Prefixes.TryGetValue(msg.Channel.Id, out var pfix)) { return(Task.FromResult(msg.GetStringPrefixLength(pfix))); } return(Task.FromResult(-1)); }, EnableDms = true, EnableMentionPrefix = true, CaseSensitive = true, Dependencies = depco.Build(), SelfBot = this.Config.UseUserToken, IgnoreExtraArguments = false //DefaultHelpChecks = new List<CheckBaseAttribute>() { new RequireOwnerAttribute() } }; this.CommandsNextService = Discord.UseCommandsNext(cncfg); this.CommandsNextService.CommandErrored += this.CommandsNextService_CommandErrored; this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted; //this.CommandsNextService.RegisterCommands<TestBotCommands>(); //this.CommandsNextService.RegisterCommands<TestBotNextCommands>(); //this.CommandsNextService.RegisterCommands<TestBotEvalCommands>(); //this.CommandsNextService.RegisterCommands<TestBotDependentCommands>(); //this.CommandsNextService.RegisterCommands<TestBotGroupInheritedChecksCommands>(); this.CommandsNextService.RegisterCommands(typeof(TestBot).GetTypeInfo().Assembly); this.CommandsNextService.SetHelpFormatter <TestBotHelpFormatter>(); // interactivity service var icfg = new InteractivityConfiguration() { PaginationBehaviour = TimeoutBehaviour.Delete, PaginationTimeout = TimeSpan.FromSeconds(30), Timeout = TimeSpan.FromSeconds(30) }; this.InteractivityService = Discord.UseInteractivity(icfg); }
/// <summary> /// Enables interactivity for this <see cref="DiscordClient"/> instance. /// </summary> /// <param name="client">The client to enable interactivity for.</param> /// <param name="configuration">A configuration instance. Default configuration values will be used if none is provided.</param> /// <returns>A brand new <see cref="InteractivityExtension"/> instance.</returns> /// <exception cref="InvalidOperationException">Thrown if interactivity has already been enabled for the client instance.</exception> public static InteractivityExtension UseInteractivity(this DiscordClient client, InteractivityConfiguration configuration = null) { if (client.GetExtension <InteractivityExtension>() != null) { throw new InvalidOperationException($"Interactivity is already enabled for this {(client._isShard ? "shard" : "client")}."); } configuration ??= new InteractivityConfiguration(); var extension = new InteractivityExtension(configuration); client.AddExtension(extension); return(extension); }
public async Task RunBotAsync() { var cfg = new DiscordConfiguration { Token = BotSettings.Token, AutoReconnect = true, TokenType = TokenType.Bot, MinimumLogLevel = BotSettings.Debug ? LogLevel.Debug : LogLevel.Information }; Client = new DiscordClient(cfg); var ccfg = new CommandsNextConfiguration { StringPrefixes = new[] { BotSettings.Prefix }, EnableDms = true, CaseSensitive = false, EnableMentionPrefix = true }; Commands = Client.UseCommandsNext(ccfg); var icfg = new InteractivityConfiguration { PaginationBehaviour = PaginationBehaviour.WrapAround, PaginationDeletion = PaginationDeletion.DeleteEmojis, Timeout = TimeSpan.FromMinutes(2) }; Interactivity = Client.UseInteractivity(icfg); //Команды Commands.RegisterCommands(Assembly.GetExecutingAssembly()); //Кастомная справка команд Commands.SetHelpFormatter <HelpFormatter>(); //Ивенты AsyncListenerHandler.InstallListeners(Client, this); ConnectionString = $"Server={Bot.BotSettings.DatabaseHost}; Port=3306; Database={Bot.BotSettings.DatabaseName}; Uid={Bot.BotSettings.DatabaseUser}; Pwd={Bot.BotSettings.DatabasePassword}; CharSet=utf8mb4;"; await Client.ConnectAsync(); if (!Directory.Exists("generated")) { Directory.CreateDirectory("generated"); } if (!File.Exists("generated/attachments_messages.csv")) { File.Create("generated/attachments_messages.csv"); } if (!File.Exists("generated/find_channel_invites.csv")) { File.Create("generated/find_channel_invites.csv"); } if (!File.Exists("generated/top_inviters.xml")) { File.Create("generated/top_inviters.xml"); } if (!Directory.Exists("generated/stats")) { Directory.CreateDirectory("generated/stats"); } if (!File.Exists("generated/stats/ship_names.csv")) { File.Create("generated/stats/ship_names.csv"); } await Task.Delay(-1); }
public TestBot(TestBotConfig cfg, int shardid) { // global bot config this.Config = cfg; // discord instance config and the instance itself var dcfg = new DiscordConfiguration { AutoReconnect = true, LargeThreshold = 250, LogLevel = LogLevel.Debug, Token = this.Config.Token, TokenType = this.Config.UseUserToken ? TokenType.User : TokenType.Bot, UseInternalLogHandler = false, ShardId = shardid, ShardCount = this.Config.ShardCount, //GatewayCompressionLevel = GatewayCompressionLevel.Stream, MessageCacheSize = 2048, AutomaticGuildSync = !this.Config.UseUserToken, DateTimeFormat = "dd-MM-yyyy HH:mm:ss zzz" }; Discord = new DiscordClient(dcfg); // events Discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageReceived; Discord.Ready += this.Discord_Ready; Discord.GuildAvailable += this.Discord_GuildAvailable; Discord.ClientErrored += this.Discord_ClientErrored; Discord.SocketErrored += this.Discord_SocketError; Discord.GuildCreated += this.Discord_GuildCreated; Discord.VoiceStateUpdated += this.Discord_VoiceStateUpdated; Discord.GuildDownloadCompleted += this.Discord_GuildDownloadCompleted; Discord.GuildUpdated += this.Discord_GuildUpdated; Discord.ChannelDeleted += this.Discord_ChannelDeleted; // voice config and the voice service itself var vcfg = new VoiceNextConfiguration { VoiceApplication = VoiceNext.Codec.VoiceApplication.Music, EnableIncoming = false }; this.VoiceService = this.Discord.UseVoiceNext(vcfg); // build a dependency collection for commandsnext var depco = new ServiceCollection() .AddSingleton(new TestBotService()) .AddScoped <TestBotScopedService>(); // commandsnext config and the commandsnext service itself var cncfg = new CommandsNextConfiguration { StringPrefixes = this.Config.CommandPrefixes, //PrefixResolver = msg => //{ // if (TestBotCommands.PrefixSettings.ContainsKey(msg.Channel.Id) && TestBotCommands.PrefixSettings.TryGetValue(msg.Channel.Id, out var pfix)) // return Task.FromResult(msg.GetStringPrefixLength(pfix)); // return Task.FromResult(-1); //}, EnableDms = true, EnableMentionPrefix = true, CaseSensitive = false, Services = depco.BuildServiceProvider(true), IgnoreExtraArguments = false, UseDefaultCommandHandler = true, //DefaultHelpChecks = new List<CheckBaseAttribute>() { new RequireOwnerAttribute() } }; this.CommandsNextService = Discord.UseCommandsNext(cncfg); this.CommandsNextService.CommandErrored += this.CommandsNextService_CommandErrored; this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted; this.CommandsNextService.RegisterCommands(typeof(TestBot).GetTypeInfo().Assembly); this.CommandsNextService.SetHelpFormatter <TestBotHelpFormatter>(); // hook command handler //this.Discord.MessageCreated += this.Discord_MessageCreated; // interactivity service var icfg = new InteractivityConfiguration() { PaginationBehavior = TimeoutBehaviour.DeleteMessage, PaginationTimeout = TimeSpan.FromSeconds(30), Timeout = TimeSpan.FromSeconds(30) }; this.InteractivityService = Discord.UseInteractivity(icfg); this.LavalinkService = Discord.UseLavalink(); }
internal static async Task Main(string[] args) { var singleInstanceCheckThread = new Thread(() => { using (var instanceLock = new Mutex(false, @"Global\RPCS3 Compatibility Bot")) { if (instanceLock.WaitOne(1000)) { try { InstanceCheck.Release(); ShutdownCheck.Wait(); } finally { instanceLock.ReleaseMutex(); } } } }); try { singleInstanceCheckThread.Start(); if (!await InstanceCheck.WaitAsync(1000).ConfigureAwait(false)) { Config.Log.Fatal("Another instance is already running."); return; } if (string.IsNullOrEmpty(Config.Token)) { Config.Log.Fatal("No token was specified."); return; } using (var db = new BotDb()) if (!await DbImporter.UpgradeAsync(db, Config.Cts.Token)) { return; } using (var db = new ThumbnailDb()) if (!await DbImporter.UpgradeAsync(db, Config.Cts.Token)) { return; } await StatsStorage.RestoreAsync().ConfigureAwait(false); Config.Log.Debug("Restored stats from persistent storage"); var backgroundTasks = Task.WhenAll( AmdDriverVersionProvider.RefreshAsync(), new PsnScraper().RunAsync(Config.Cts.Token), GameTdbScraper.RunAsync(Config.Cts.Token), new AppveyorClient.Client().GetBuildAsync(Guid.NewGuid().ToString(), Config.Cts.Token), StatsStorage.BackgroundSaveAsync() ); try { if (!Directory.Exists(Config.IrdCachePath)) { Directory.CreateDirectory(Config.IrdCachePath); } } catch (Exception e) { Config.Log.Warn(e, $"Failed to create new folder {Config.IrdCachePath}: {e.Message}"); } var config = new DiscordConfiguration { Token = Config.Token, TokenType = TokenType.Bot, }; using (var client = new DiscordClient(config)) { var commands = client.UseCommandsNext(new CommandsNextConfiguration { StringPrefixes = new[] { Config.CommandPrefix, Config.AutoRemoveCommandPrefix }, Services = new ServiceCollection().BuildServiceProvider(), }); commands.RegisterConverter(new TextOnlyDiscordChannelConverter()); commands.RegisterCommands <Misc>(); commands.RegisterCommands <CompatList>(); commands.RegisterCommands <Sudo>(); commands.RegisterCommands <CommandsManagement>(); commands.RegisterCommands <ContentFilters>(); commands.RegisterCommands <Warnings>(); commands.RegisterCommands <Explain>(); commands.RegisterCommands <Psn>(); commands.RegisterCommands <Invites>(); commands.RegisterCommands <Moderation>(); commands.RegisterCommands <Ird>(); commands.RegisterCommands <BotMath>(); commands.RegisterCommands <Pr>(); commands.RegisterCommands <Events>(); commands.RegisterCommands <E3>(); commands.RegisterCommands <Cyberpunk2077>(); commands.RegisterCommands <Rpcs3Ama>(); commands.RegisterCommands <BotStats>(); commands.RegisterCommands <Syscall>(); commands.CommandErrored += UnknownCommandHandler.OnError; var interactivityConfig = new InteractivityConfiguration { }; client.UseInteractivity(interactivityConfig); client.Ready += async r => { Config.Log.Info("Bot is ready to serve!"); Config.Log.Info(""); Config.Log.Info($"Bot user id : {r.Client.CurrentUser.Id} ({r.Client.CurrentUser.Username})"); Config.Log.Info($"Bot admin id : {Config.BotAdminId} ({(await r.Client.GetUserAsync(Config.BotAdminId)).Username})"); Config.Log.Info(""); }; client.GuildAvailable += async gaArgs => { await BotStatusMonitor.RefreshAsync(gaArgs.Client).ConfigureAwait(false); Watchdog.DisconnectTimestamps.Clear(); if (gaArgs.Guild.Id != Config.BotGuildId) { #if DEBUG Config.Log.Warn($"Unknown discord server {gaArgs.Guild.Id} ({gaArgs.Guild.Name})"); #else Config.Log.Warn($"Unknown discord server {gaArgs.Guild.Id} ({gaArgs.Guild.Name}), leaving..."); await gaArgs.Guild.LeaveAsync().ConfigureAwait(false); #endif return; } Config.Log.Info($"Server {gaArgs.Guild.Name} is available now"); Config.Log.Info($"Checking moderation backlogs in {gaArgs.Guild.Name}..."); try { await Task.WhenAll( Starbucks.CheckBacklogAsync(gaArgs.Client, gaArgs.Guild).ContinueWith(_ => Config.Log.Info($"Starbucks backlog checked in {gaArgs.Guild.Name}."), TaskScheduler.Default), DiscordInviteFilter.CheckBacklogAsync(gaArgs.Client, gaArgs.Guild).ContinueWith(_ => Config.Log.Info($"Discord invites backlog checked in {gaArgs.Guild.Name}."), TaskScheduler.Default) ).ConfigureAwait(false); } catch (Exception e) { Config.Log.Warn(e, "Error running backlog tasks"); } Config.Log.Info($"All moderation backlogs checked in {gaArgs.Guild.Name}."); }; client.GuildUnavailable += guArgs => { Config.Log.Warn($"{guArgs.Guild.Name} is unavailable"); return(Task.CompletedTask); }; client.MessageReactionAdded += Starbucks.Handler; client.MessageReactionAdded += AntipiracyMonitor.OnReaction; client.MessageCreated += AntipiracyMonitor.OnMessageCreated; // should be first client.MessageCreated += ProductCodeLookup.OnMessageCreated; client.MessageCreated += LogParsingHandler.OnMessageCreated; client.MessageCreated += LogAsTextMonitor.OnMessageCreated; client.MessageCreated += DiscordInviteFilter.OnMessageCreated; client.MessageCreated += PostLogHelpHandler.OnMessageCreated; client.MessageCreated += BotReactionsHandler.OnMessageCreated; client.MessageCreated += AppveyorLinksHandler.OnMessageCreated; client.MessageCreated += GithubLinksHandler.OnMessageCreated; client.MessageCreated += NewBuildsMonitor.OnMessageCreated; client.MessageCreated += TableFlipMonitor.OnMessageCreated; client.MessageCreated += IsTheGamePlayableHandler.OnMessageCreated; client.MessageCreated += EmpathySimulationHandler.OnMessageCreated; client.MessageUpdated += AntipiracyMonitor.OnMessageUpdated; client.MessageUpdated += DiscordInviteFilter.OnMessageUpdated; client.MessageUpdated += EmpathySimulationHandler.OnMessageUpdated; client.MessageDeleted += ThumbnailCacheMonitor.OnMessageDeleted; client.MessageDeleted += EmpathySimulationHandler.OnMessageDeleted; client.UserUpdated += UsernameSpoofMonitor.OnUserUpdated; client.UserUpdated += UsernameZalgoMonitor.OnUserUpdated; client.GuildMemberAdded += Greeter.OnMemberAdded; client.GuildMemberAdded += UsernameSpoofMonitor.OnMemberAdded; client.GuildMemberAdded += UsernameZalgoMonitor.OnMemberAdded; client.GuildMemberUpdated += UsernameSpoofMonitor.OnMemberUpdated; client.GuildMemberUpdated += UsernameZalgoMonitor.OnMemberUpdated; client.DebugLogger.LogMessageReceived += (sender, eventArgs) => { Action <Exception, string> logLevel = Config.Log.Info; if (eventArgs.Level == LogLevel.Debug) { logLevel = Config.Log.Debug; } else if (eventArgs.Level == LogLevel.Info) { //logLevel = Config.Log.Info; if (eventArgs.Message?.Contains("Session resumed") ?? false) { Watchdog.DisconnectTimestamps.Clear(); } } else if (eventArgs.Level == LogLevel.Warning) { logLevel = Config.Log.Warn; if (eventArgs.Message?.Contains("Dispatch:PRESENCES_REPLACE") ?? false) { BotStatusMonitor.RefreshAsync(client).ConfigureAwait(false).GetAwaiter().GetResult(); } } else if (eventArgs.Level == LogLevel.Error) { logLevel = Config.Log.Error; } else if (eventArgs.Level == LogLevel.Critical) { logLevel = Config.Log.Fatal; if ((eventArgs.Message?.Contains("Socket connection terminated") ?? false) || (eventArgs.Message?.Contains("heartbeats were skipped. Issuing reconnect.") ?? false)) { Watchdog.DisconnectTimestamps.Enqueue(DateTime.UtcNow); } } logLevel(eventArgs.Exception, eventArgs.Message); }; Watchdog.DisconnectTimestamps.Enqueue(DateTime.UtcNow); await client.ConnectAsync().ConfigureAwait(false); if (args.Length > 1 && ulong.TryParse(args[1], out var channelId)) { Config.Log.Info($"Found channelId: {args[1]}"); DiscordChannel channel; if (channelId == InvalidChannelId) { channel = await client.GetChannelAsync(Config.ThumbnailSpamId).ConfigureAwait(false); await channel.SendMessageAsync("Bot has suffered some catastrophic failure and was restarted").ConfigureAwait(false); } else { channel = await client.GetChannelAsync(channelId).ConfigureAwait(false); await channel.SendMessageAsync("Bot is up and running").ConfigureAwait(false); } } Config.Log.Debug("Running RPCS3 update check thread"); backgroundTasks = Task.WhenAll( backgroundTasks, NewBuildsMonitor.MonitorAsync(client), Watchdog.Watch(client), InviteWhitelistProvider.CleanupAsync(client) ); while (!Config.Cts.IsCancellationRequested) { if (client.Ping > 1000) { Config.Log.Warn($"High ping detected: {client.Ping}"); } await Task.Delay(TimeSpan.FromMinutes(1), Config.Cts.Token).ContinueWith(dt => { /* in case it was cancelled */ }, TaskScheduler.Default).ConfigureAwait(false); } } await backgroundTasks.ConfigureAwait(false); } catch (Exception e) { if (!Config.inMemorySettings.ContainsKey("shutdown")) { Config.Log.Fatal(e, "Experienced catastrophic failure, attempting to restart..."); } } finally { ShutdownCheck.Release(); if (singleInstanceCheckThread.IsAlive) { singleInstanceCheckThread.Join(100); } } if (!Config.inMemorySettings.ContainsKey("shutdown")) { Sudo.Bot.Restart(InvalidChannelId); } }
private async Task MainAsync() { // getting versions and assembly info SetBotVersionInfo(); // init log channels _logChannels = new List <DiscordChannel>(); _lastLogChWrite = File.GetLastWriteTime("logchannels.txt"); string json = await FileHandler.ReadJsonConfig(); if (json.Length == 0) { return; } if (json == "default") { Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("Created default config file.\n" + "Now you need to get your discord bot token " + "and put it in config.json file.\n" + "Also make sure you set other parameters."); Console.ResetColor(); return; } // setting up client var cfgjson = JsonSerializer.Deserialize <ConfigJson>(json); if (cfgjson == null) { return; } var cfg = new DiscordConfiguration { Token = cfgjson.Token, TokenType = TokenType.Bot, AutoReconnect = true, MinimumLogLevel = RuntimeInfo == "Debug" ? LogLevel.Debug : LogLevel.Information, MessageCacheSize = 2048, LogTimestampFormat = "dd-MM-yyyy HH:mm:ss zzz" }; // client init and event hooks _discord = new DiscordClient(cfg); _discord.Ready += Discord_Ready; _discord.GuildAvailable += Discord_GuildAvailable; _discord.GuildUnavailable += Discord_GuildUnavailable; _discord.GuildCreated += Discord_GuildCreated; _discord.GuildDeleted += Discord_GuildDeleted; _discord.ChannelDeleted += Discord_ChannelDeleted; _discord.DmChannelDeleted += Discord_DmChannelDeleted; _discord.GuildDownloadCompleted += Discord_GuildDownloadCompleted; _discord.ClientErrored += Discord_ClientErrored; _discord.SocketClosed += Discord_SocketClosed; _discord.Resumed += Discord_Resumed; _discord.Heartbeated += Discord_Heartbeated; // setting up interactivity var intcfg = new InteractivityConfiguration { Timeout = TimeSpan.FromMinutes(cfgjson.ActTimeout), PaginationDeletion = PaginationDeletion.DeleteMessage, PollBehaviour = PollBehaviour.KeepEmojis }; _discord.UseInteractivity(intcfg); // setting up commands var cmdcfg = new CommandsNextConfiguration { StringPrefixes = new List <string> { cfgjson.CommandPrefix }, EnableDms = cfgjson.DmsEnabled, EnableMentionPrefix = cfgjson.MentionEnabled, CaseSensitive = cfgjson.CaseSensitive, EnableDefaultHelp = true }; // commands hooks and register _commands = _discord.UseCommandsNext(cmdcfg); _commands.CommandExecuted += Commands_CommandExecuted; _commands.CommandErrored += Commands_CommandErrored; _commands.RegisterCommands <Commands.Commands>(); _commands.RegisterCommands <LeetCommands>(); _commands.RegisterCommands <Interactivities.Interactivities>(); _commands.RegisterCommands <Administrative>(); _commands.RegisterCommands <Cats>(); _commands.RegisterCommands <DiceRolling>(); _commands.RegisterCommands <CryptoAes>(); _commands.RegisterCommands <CryptoRsa>(); _commands.RegisterCommands <MathCommands>(); _commands.RegisterCommands <StatusCommands>(); _commands.RegisterCommands <VoiceCommands>(); // adding math converter for custom type and name var mathopscvrt = new MathOperationConverter(); _commands.RegisterConverter(mathopscvrt); _commands.RegisterUserFriendlyTypeName <MathOperation>("operator"); // setting up and enabling voice var vcfg = new VoiceNextConfiguration { AudioFormat = AudioFormat.Default, EnableIncoming = false }; _discord.UseVoiceNext(vcfg); // setting custom help formatter _commands.SetHelpFormatter <HelpFormatter>(); // init twitch live and youtube video monitors _ttvApIclid = cfgjson.TwitchApiClid; _ttvApIsecret = cfgjson.TwitchApiSecret; _ytApIkey = cfgjson.YoutubeApiKey; _tlm = new TwitchLiveMonitor(); _yvm = new YoutubeVideoMonitor(); // getting aes and rsa keys from config AesKey = cfgjson.AesKey; AesIv = cfgjson.AesIv; RsaPublicKey = cfgjson.RsaPublicKey; RsaPrivateKey = cfgjson.RsaPrivateKey; // connecting discord try { await _discord.ConnectAsync(); } catch (Exception e) { _discord.Logger.LogCritical($"{e.Message}"); return; } await Task.Delay(-1); }
private static async Task MainAsync(string[] args) { var DayTask = new Timer(43200000); //12 hours in ms DayTask.Elapsed += DayEvent; DayTask.Start(); var config = new DiscordConfiguration { Token = token, TokenType = TokenType.Bot, ReconnectIndefinitely = true }; discord = new DiscordShardedClient(config); discordrest = new DiscordRestClient(config); Lavalink = await discord.UseLavalinkAsync(); var icfg = new InteractivityConfiguration { Timeout = TimeSpan.FromSeconds(20.0) }; Interactivity = await discord.UseInteractivityAsync(icfg); discord.GuildMemberAdded += Discord_GuildMemberAdded; discord.GuildCreated += Discord_GuildCreated; discord.VoiceStateUpdated += Discord_VoiceStateUpdated; Commands = await discord.UseCommandsNextAsync(new CommandsNextConfiguration { PrefixResolver = ResolvePrefix, EnableMentionPrefix = false }); foreach (var commands in Commands.Values) { //commands.SetHelpFormatter<HelpFormatter>(); commands.RegisterCommands <Commands>(); commands.RegisterCommands <UtilityCommands>(); commands.RegisterCommands <AudioCommands>(); commands.RegisterCommands <AdministrationCommands>(); commands.RegisterCommands <FunCommands>(); commands.RegisterCommands <ExternalCommands>(); commands.CommandErrored += Commands_CommandErrored; commands.CommandExecuted += Commands_CommandExecuted; } discord.MessageCreated += Discord_MessageCreated; discord.PresenceUpdated += Discord_PresenceUpdated; await discord.StartAsync(); foreach (var extension in Lavalink.Values) { AudioCommands.Lavalink = await extension.ConnectAsync(lavalinkConfig); } discord.Logger.Log(LogLevel.Information, "Connected to Lavalink."); await Task.Delay(2000); while (true) { try { /*if (!CustomStatus) * { * var totalmems = (from elem in discord.ShardClients.Values * from guild in elem.Guilds * from mem in guild.Value.Members.Values.Where(x => !x.IsBot) * select mem.Id).ToList(); * var amount = totalmems.Distinct().Count(); * var status = amount + " users"; * var activity = new DiscordActivity(status, ActivityType.Watching); * await discord.UpdateStatusAsync(activity); * } * * await Task.Delay(TimeSpan.FromMinutes(1));*/ if (!CustomStatus) { var amount = discord.ShardClients.Values.Sum(elem => elem.Guilds.Count); var status = amount + " servers"; var activity = new DiscordActivity(status, ActivityType.Watching); await discord.UpdateStatusAsync(activity); } await Task.Delay(TimeSpan.FromMinutes(1)); if (!CustomStatus) { foreach (var elem in discord.ShardClients.Values) { var activity = new DiscordActivity($"Shard {elem.ShardId + 1} of {elem.ShardCount}", ActivityType.Watching); await discord.UpdateStatusAsync(activity); } } await Task.Delay(TimeSpan.FromMinutes(1)); } catch { await Task.Delay(1000); } } }
public TestBot(TestBotConfig cfg, int shardid) { // global bot config this.Config = cfg; // discord instance config and the instance itself var dcfg = new DiscordConfiguration { AutoReconnect = true, LargeThreshold = 250, LogLevel = LogLevel.Debug, Token = this.Config.Token, TokenType = TokenType.Bot, UseInternalLogHandler = false, ShardId = shardid, ShardCount = this.Config.ShardCount, MessageCacheSize = 2048, DateTimeFormat = "dd-MM-yyyy HH:mm:ss zzz" }; Discord = new DiscordClient(dcfg); // events Discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageReceived; Discord.Ready += this.Discord_Ready; Discord.GuildAvailable += this.Discord_GuildAvailable; Discord.ClientErrored += this.Discord_ClientErrored; Discord.SocketErrored += this.Discord_SocketError; Discord.GuildCreated += this.Discord_GuildCreated; Discord.VoiceStateUpdated += this.Discord_VoiceStateUpdated; Discord.GuildDownloadCompleted += this.Discord_GuildDownloadCompleted; Discord.GuildUpdated += this.Discord_GuildUpdated; Discord.ChannelDeleted += this.Discord_ChannelDeleted; // voice config and the voice service itself var vcfg = new VoiceNextConfiguration { AudioFormat = AudioFormat.Default, EnableIncoming = true }; this.VoiceService = this.Discord.UseVoiceNext(vcfg); // build a dependency collection for commandsnext var depco = new ServiceCollection(); // commandsnext config and the commandsnext service itself var cncfg = new CommandsNextConfiguration { StringPrefixes = this.Config.CommandPrefixes, EnableDms = true, EnableMentionPrefix = true, CaseSensitive = false, Services = depco.BuildServiceProvider(true), IgnoreExtraArguments = false, UseDefaultCommandHandler = true, }; this.CommandsNextService = Discord.UseCommandsNext(cncfg); this.CommandsNextService.CommandErrored += this.CommandsNextService_CommandErrored; this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted; this.CommandsNextService.RegisterCommands(typeof(TestBot).GetTypeInfo().Assembly); this.CommandsNextService.SetHelpFormatter <TestBotHelpFormatter>(); // interactivity service var icfg = new InteractivityConfiguration() { Timeout = TimeSpan.FromSeconds(3) }; this.InteractivityService = Discord.UseInteractivity(icfg); this.LavalinkService = Discord.UseLavalink(); }
/// <summary> /// Use Interactivity with this Bot Client. /// </summary> /// <param name="client">Your TelegramBotClient</param> /// <param name="configuration">Interactivity Configuration</param> public static void UseInteractivity(this TelegramBotClient client, InteractivityConfiguration configuration) { var interactivity = new TelegramInteractivity(client, configuration); currentInteractivities.Add(client, interactivity); }
public TestBot(TestBotConfig cfg, int shardid) { // global bot config this.Config = cfg; // discord instance config and the instance itself var dcfg = new DiscordConfiguration { AutoReconnect = true, LargeThreshold = 250, MinimumLogLevel = LogLevel.Debug, Token = this.Config.Token, TokenType = TokenType.Bot, ShardId = shardid, ShardCount = this.Config.ShardCount, MessageCacheSize = 2048, LogTimestampFormat = "dd-MM-yyyy HH:mm:ss zzz", Intents = DiscordIntents.All // if 4013 is received, change to DiscordIntents.AllUnprivileged }; Discord = new DiscordClient(dcfg); // events Discord.Ready += this.Discord_Ready; Discord.GuildAvailable += this.Discord_GuildAvailable; Discord.PresenceUpdated += this.Discord_PresenceUpdated; //Discord.ClientErrored += this.Discord_ClientErrored; Discord.SocketErrored += this.Discord_SocketError; Discord.GuildCreated += this.Discord_GuildCreated; Discord.VoiceStateUpdated += this.Discord_VoiceStateUpdated; Discord.GuildDownloadCompleted += this.Discord_GuildDownloadCompleted; Discord.GuildUpdated += this.Discord_GuildUpdated; Discord.ChannelDeleted += this.Discord_ChannelDeleted; // For event timeout testing //Discord.GuildDownloadCompleted += async (s, e) => //{ // await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false); // throw new Exception("Flippin' tables"); //}; // voice config and the voice service itself var vcfg = new VoiceNextConfiguration { AudioFormat = AudioFormat.Default, EnableIncoming = true }; this.VoiceService = this.Discord.UseVoiceNext(vcfg); // build a dependency collection for commandsnext var depco = new ServiceCollection(); // commandsnext config and the commandsnext service itself var cncfg = new CommandsNextConfiguration { StringPrefixes = this.Config.CommandPrefixes, EnableDms = true, EnableMentionPrefix = true, CaseSensitive = false, Services = depco.BuildServiceProvider(true), IgnoreExtraArguments = false, UseDefaultCommandHandler = true, }; this.CommandsNextService = Discord.UseCommandsNext(cncfg); this.CommandsNextService.CommandErrored += this.CommandsNextService_CommandErrored; this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted; this.CommandsNextService.RegisterCommands(typeof(TestBot).GetTypeInfo().Assembly); this.CommandsNextService.SetHelpFormatter <TestBotHelpFormatter>(); // interactivity service var icfg = new InteractivityConfiguration() { Timeout = TimeSpan.FromSeconds(3) }; this.InteractivityService = Discord.UseInteractivity(icfg); this.LavalinkService = Discord.UseLavalink(); //this.Discord.MessageCreated += async e => //{ // if (e.Message.Author.IsBot) // return; // _ = Task.Run(async () => await e.Message.RespondAsync(e.Message.Content)).ConfigureAwait(false); //}; }
public InteractivityExtension UseInteractivity(InteractivityConfiguration interactivityConfiguration) { return(_Client.UseInteractivity(interactivityConfiguration)); }
/// <summary> /// Create a new telegram interactivity object. /// </summary> /// <param name="client">The client to associate with this object.</param> /// <param name="configuration">This object's configuration.</param> public TelegramInteractivity(TelegramBotClient client, InteractivityConfiguration configuration) { this.client = client; this.Configuration = configuration; Setup(); }
public TestBot(TestBotConfig cfg, int shardid) { // global bot config this.Config = cfg; // discord instance config and the instance itself var dcfg = new DiscordConfiguration { AutoReconnect = true, LargeThreshold = 250, MinimumLogLevel = LogLevel.Trace, Token = this.Config.Token, TokenType = TokenType.Bot, ShardId = shardid, ShardCount = this.Config.ShardCount, MessageCacheSize = 2048, LogTimestampFormat = "dd-MM-yyyy HH:mm:ss zzz", Intents = DiscordIntents.All // if 4013 is received, change to DiscordIntents.AllUnprivileged }; this.Discord = new DiscordClient(dcfg); // events this.Discord.Ready += this.Discord_Ready; this.Discord.GuildStickersUpdated += this.Discord_StickersUpdated; this.Discord.GuildAvailable += this.Discord_GuildAvailable; //Discord.PresenceUpdated += this.Discord_PresenceUpdated; //Discord.ClientErrored += this.Discord_ClientErrored; this.Discord.SocketErrored += this.Discord_SocketError; this.Discord.GuildCreated += this.Discord_GuildCreated; this.Discord.VoiceStateUpdated += this.Discord_VoiceStateUpdated; this.Discord.GuildDownloadCompleted += this.Discord_GuildDownloadCompleted; this.Discord.GuildUpdated += this.Discord_GuildUpdated; this.Discord.ChannelDeleted += this.Discord_ChannelDeleted; this.Discord.InteractionCreated += this.Discord_InteractionCreated; this.Discord.ComponentInteractionCreated += this.Discord_ModalCheck; this.Discord.ModalSubmitted += this.Discord_ModalSubmitted; //this.Discord.ComponentInteractionCreated += this.RoleMenu; //this.Discord.ComponentInteractionCreated += this.DiscordComponentInteractionCreated; //this.Discord.InteractionCreated += this.SendButton; // For event timeout testing //Discord.GuildDownloadCompleted += async (s, e) => //{ // await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false); // throw new Exception("Flippin' tables"); //}; this.Discord.ThreadCreated += this.Discord_ThreadCreated; this.Discord.ThreadUpdated += this.Discord_ThreadUpdated; this.Discord.ThreadDeleted += this.Discord_ThreadDeleted; this.Discord.ThreadListSynced += this.Discord_ThreadListSynced; this.Discord.ThreadMemberUpdated += this.Discord_ThreadMemberUpdated; this.Discord.ThreadMembersUpdated += this.Discord_ThreadMembersUpdated; // voice config and the voice service itself var vcfg = new VoiceNextConfiguration { AudioFormat = AudioFormat.Default, EnableIncoming = true }; this.VoiceService = this.Discord.UseVoiceNext(vcfg); // build a dependency collection for commandsnext var depco = new ServiceCollection(); // commandsnext config and the commandsnext service itself var cncfg = new CommandsNextConfiguration { StringPrefixes = this.Config.CommandPrefixes, EnableDms = true, EnableMentionPrefix = true, CaseSensitive = false, Services = depco.BuildServiceProvider(true), IgnoreExtraArguments = false, UseDefaultCommandHandler = true, DefaultParserCulture = CultureInfo.InvariantCulture, //CommandExecutor = new ParallelQueuedCommandExecutor(2), }; this.CommandsNextService = this.Discord.UseCommandsNext(cncfg); this.CommandsNextService.CommandErrored += this.CommandsNextService_CommandErrored; this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted; this.CommandsNextService.RegisterCommands(typeof(TestBot).GetTypeInfo().Assembly); this.CommandsNextService.SetHelpFormatter <TestBotHelpFormatter>(); // interactivity service var icfg = new InteractivityConfiguration() { Timeout = TimeSpan.FromSeconds(10), AckPaginationButtons = true, ResponseBehavior = InteractionResponseBehavior.Respond, PaginationBehaviour = PaginationBehaviour.Ignore, ResponseMessage = "Sorry, but this wasn't a valid option, or does not belong to you!", PaginationButtons = new PaginationButtons() { Stop = new DiscordButtonComponent(ButtonStyle.Danger, "stop", null, false, new DiscordComponentEmoji(862259725785497620)), Left = new DiscordButtonComponent(ButtonStyle.Secondary, "left", null, false, new DiscordComponentEmoji(862259522478800916)), Right = new DiscordButtonComponent(ButtonStyle.Secondary, "right", null, false, new DiscordComponentEmoji(862259691212242974)), SkipLeft = new DiscordButtonComponent(ButtonStyle.Primary, "skipl", null, false, new DiscordComponentEmoji(862259605464023060)), SkipRight = new DiscordButtonComponent(ButtonStyle.Primary, "skipr", null, false, new DiscordComponentEmoji(862259654403031050)) } }; this.InteractivityService = this.Discord.UseInteractivity(icfg); this.LavalinkService = this.Discord.UseLavalink(); this.SlashCommandService = this.Discord.UseSlashCommands(); this.SlashCommandService.SlashCommandErrored += this.SlashCommandService_CommandErrored; this.SlashCommandService.SlashCommandInvoked += this.SlashCommandService_CommandReceived; this.SlashCommandService.SlashCommandExecuted += this.SlashCommandService_CommandExecuted; if (this.Config.SlashCommandGuild != 0) { this.SlashCommandService.RegisterCommands(typeof(TestBot).GetTypeInfo().Assembly, this.Config.SlashCommandGuild); } //this.Discord.MessageCreated += async e => //{ // if (e.Message.Author.IsBot) // return; // _ = Task.Run(async () => await e.Message.RespondAsync(e.Message.Content)).ConfigureAwait(false); //}; }
public RPBot(Config cfg, int shardid) { // global bot config this.Config = cfg; // discord instance config and the instance itself var dcfg = new DiscordConfiguration { AutoReconnect = true, LargeThreshold = 250, LogLevel = LogLevel.Info, Token = this.Config.Token, TokenType = TokenType.Bot, UseInternalLogHandler = false, ShardId = shardid, ShardCount = this.Config.ShardCount, }; Discord = new DiscordClient(dcfg); //Discord.SetWebSocketClient<WebSocketSharpClient>(); // events Discord.DebugLogger.LogMessageReceived += this.DebugLogger_LogMessageReceived; Discord.Ready += this.Discord_Ready; Discord.GuildAvailable += this.Discord_GuildAvailable; Discord.MessageCreated += this.Discord_MessageCreated; Discord.MessageDeleted += this.Discord_MessageDeleted; Discord.MessageUpdated += this.Discord_MessageUpdated; Discord.MessageReactionAdded += this.Discord_MessageReactionAdd; Discord.MessageReactionsCleared += this.Discord_MessageReactionRemoveAll; Discord.PresenceUpdated += this.Discord_PresenceUpdate; Discord.SocketClosed += this.Discord_SocketClose; Discord.GuildMemberAdded += this.Discord_GuildMemberAdded; Discord.GuildMemberRemoved += this.Discord_GuildMemberRemoved; Discord.SocketErrored += this.Discord_SocketError; Discord.VoiceStateUpdated += this.Discord_VoiceStateUpdated; Discord.ClientErrored += this.Discord_ClientErrored; // commandsnext config and the commandsnext service itself var cncfg = new CommandsNextConfiguration { StringPrefixes = new List <string>() { Config.CommandPrefix, "" }, EnableDms = true, EnableMentionPrefix = true, CaseSensitive = false }; this.CommandsNextService = Discord.UseCommandsNext(cncfg); this.CommandsNextService.CommandErrored += this.CommandsNextService_CommandErrored; this.CommandsNextService.CommandExecuted += this.CommandsNextService_CommandExecuted; CommandsNextService.RegisterCommands(typeof(InstanceClass)); CommandsNextService.RegisterCommands(typeof(MoneyClass)); CommandsNextService.RegisterCommands(typeof(CommandsClass)); CommandsNextService.RegisterCommands(typeof(GuildClass)); CommandsNextService.RegisterCommands(typeof(LogClass)); CommandsNextService.RegisterCommands(typeof(ModClass)); CommandsNextService.RegisterCommands(typeof(TagClass)); CommandsNextService.RegisterCommands(typeof(WikiClass)); CommandsNextService.RegisterCommands(typeof(StatsClass)); CommandsNextService.RegisterCommands(typeof(SignupClass)); CommandsNextService.RegisterCommands(typeof(XPClass)); CommandsNextService.RegisterCommands(typeof(Status)); // WikiClass.InitWiki(); InteractivityConfiguration icfg = new InteractivityConfiguration(); this.InteractivityService = Discord.UseInteractivity(icfg); }
/// <summary> /// Enables interactivity for each shard. /// </summary> /// <param name="client">The shard client to enable interactivity for.</param> /// <param name="configuration">Configuration to use for all shards. If one isn't provided, default configuration values will be used.</param> /// <returns>A dictionary containing new <see cref="InteractivityExtension"/> instances for each shard.</returns> public static async Task <IReadOnlyDictionary <int, InteractivityExtension> > UseInteractivityAsync(this DiscordShardedClient client, InteractivityConfiguration configuration = null) { var extensions = new Dictionary <int, InteractivityExtension>(); await client.InitializeShardsAsync().ConfigureAwait(false); foreach (var shard in client.ShardClients.Select(xkvp => xkvp.Value)) { var extension = shard.GetExtension <InteractivityExtension>() ?? shard.UseInteractivity(configuration); extensions.Add(shard.ShardId, extension); } return(new ReadOnlyDictionary <int, InteractivityExtension>(extensions)); }