private async Task SlashCommandErrorHandler(SlashCommandsExtension extension, SlashCommandErrorEventArgs args) { try { if (args.Exception is SlashExecutionChecksFailedException slex) { foreach (var check in slex.FailedChecks) { if (check is RequireChannelsAttribute requireChannelAttribute) { await args.Context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral(true).WithContent(Language.Current.DiscordCommandNotAvailableInChannel)); } else if (check is RequireRolesAttribute requireRoleAttribute) { await args.Context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral(true).WithContent(Language.Current.DiscordCommandMissingRoles)); } else { await args.Context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral(true).WithContent(Language.Current.DiscordCommandUnknownPrecondition)); } } } } catch (System.Exception ex) { _logger.LogError(ex, "Error while handling interaction error: " + ex.Message); } }
public WikiFeature(DiscordClient dClient, JobManager jobManager, WikiJob wikiJob) { this.cNext = dClient.GetCommandsNext(); this.jobManager = jobManager; this.wikiJob = wikiJob; this.slash = dClient.GetSlashCommands(); }
public static Task RegisterErrorHandler(ServiceProvider sp, Logger log, SlashCommandsExtension e) { ServiceProvider = sp; Log = log; e.SlashCommandErrored += Slash_SlashCommandErrored; return(Task.CompletedTask); }
private async Task OnSlashCommandExecuted(SlashCommandsExtension sender, DSharpPlus.SlashCommands.EventArgs.SlashCommandExecutedEventArgs args) { string logMessage = $"`{args.Context.User.Username}` ran `/{args.Context.CommandName}` in **[{(args.Context.Guild != null ? $"{args.Context.Guild.Name} - {args.Context.Channel.Name}" : "DM")}]**"; this.bloonLog.Information(LogConsole.Commands, CommandEmojis.Run, logMessage); Log.Debug(logMessage); using IServiceScope scope = this.scopeFactory.CreateScope(); using AnalyticsContext db = scope.ServiceProvider.GetRequiredService <AnalyticsContext>(); db.Commands.Add(new Analytics.Commands() { Command = args.Context.CommandName, Guild = args.Context.Guild != null ? args.Context.Guild.Id : ulong.MinValue, Channel = args.Context.Channel != null ? args.Context.Channel.Id : ulong.MinValue, UserId = args.Context.User.Id, Link = args.Context.Guild != null ? $"https://discord.com/channels/{args.Context.Guild.Id}/{args.Context.Channel.Id}/{args.Context.User.Id}" : "DM", Timestamp = DateTime.Now, }); await db.SaveChangesAsync(); return; }
private async Task OnContextMenuErrored(SlashCommandsExtension sender, DSharpPlus.SlashCommands.EventArgs.ContextMenuErrorEventArgs args) { if (args.Exception is ContextMenuExecutionChecksFailedException) { await args.Context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent("You do not have permission to do this.").AsEphemeral(true)); return; } Log.Error(args.Exception, $"Command '{args.Context.CommandName}' errored"); this.bloonLog.Error($"`{args.Context.User.Username}` ran `{args.Context.CommandName}` in **[{args.Context.Guild?.Name ?? "DM"} - {args.Context.Channel.Name}]**: {args.Exception.Message}"); }
public async Task RunAsync() { var json = string.Empty; var json1 = string.Empty; var json2 = string.Empty; using (var fs = File.OpenRead("AllTheLogin.json")) { using (var sr = new StreamReader(fs, new UTF8Encoding(false))) { json = await sr.ReadToEndAsync().ConfigureAwait(false); } } using (var fs = File.OpenRead("AvatarHashes.json")) { using (var sr = new StreamReader(fs, new UTF8Encoding(false))) { json1 = await sr.ReadToEndAsync().ConfigureAwait(false); } } using (var fs = File.OpenRead("AllTheStatus.json")) { using (var sr = new StreamReader(fs, new UTF8Encoding(false))) { json2 = await sr.ReadToEndAsync().ConfigureAwait(false); } } loginJson = JsonConvert.DeserializeObject <LoginInfo>(json); bigJson = JsonConvert.DeserializeObject <AH>(json1); statusJson = JsonConvert.DeserializeObject <SS>(json2); ftpClient = new FtpClient(loginJson.hostName, 21, loginJson.userName, loginJson.passWord); var config0 = new DiscordConfiguration { Token = loginJson.botToken, AutoReconnect = true, TokenType = TokenType.Bot, Intents = DiscordIntents.All }; discord = new DiscordClient(config0); SlashCommandsExtension commands = discord.UseSlashCommands(); commands.RegisterCommands <SVCommands>(); avatarEmbed = new DiscordEmbedBuilder { Title = "Avatar Update!" }; discord.GuildMemberUpdated += MemberUpdated; await discord.ConnectAsync(); discord.Ready += BotReady; await Task.Delay(-1); }
private async Task SlashCommandService_CommandErrored(SlashCommandsExtension sc, SlashCommandErrorEventArgs e) { e.Context.Client.Logger.LogError(TestBotEventId, e.Exception, "Exception occurred during {User}'s invocation of '{Command}'", e.Context.User.Username, e.Context.CommandName); var emoji = DiscordEmoji.FromName(e.Context.Client, ":no_entry:"); // let's wrap the response into an embed var embed = new DiscordEmbedBuilder { Title = "Error", Description = $"{emoji} Error!", Color = new DiscordColor(0xFF0000) // red }; await e.Context.CreateResponseAsync(embed); }
public ClientEventHandler(DiscordClient client, SlashCommandsExtension slash, IMongoConnection mongo) { this._client = client; this._slash = slash; this._mongo = mongo; this._client.Ready += (_, _) => { Console.WriteLine($"{this._client.CurrentUser.Username} ready."); return(Task.CompletedTask); }; this._slash.SlashCommandErrored += async(s, args) => { if (args.Exception is SlashExecutionChecksFailedException slex) { foreach (var check in slex.FailedChecks) { switch (check) { case SlashRequireUserPermissionsAttribute slashRequireUserPermissionsAttribute: var ruContent = $"Not enough permissions. You need: {slashRequireUserPermissionsAttribute.Permissions.ToPermissionString()}"; await args.Context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent(ruContent).AsEphemeral(true)); break; case SlashRequireOwnerAttribute slashRequireOwnerAttribute: var roContent = $"You have to be a bot owner to use that command."; await args.Context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent(roContent).AsEphemeral(true)); break; case SlashRequiredChannelsAttribute slashRequiredChannelsAttribute: var rcContent = $"You can only use this command in allowed channels, such as {String.Join(", ", slashRequiredChannelsAttribute.RequiredChannels.Select(x => $"<#{x}>"))}"; await args.Context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent(rcContent).AsEphemeral(true)); break; } } } }; }
public override Task Initialize() { this.cNext = this.dClient.UseCommandsNext(new CommandsNextConfiguration { Services = this.provider, StringPrefixes = Environment.GetEnvironmentVariable("COMMAND_PREFIXES").Split(","), }); this.slash = this.dClient.UseSlashCommands(new SlashCommandsConfiguration { Services = this.provider, }); AppDomain.CurrentDomain.ProcessExit += this.OnShutdown; return(base.Initialize()); }
public static async Task CommandErrored(SlashCommandsExtension slashCommandExtension, SlashCommandErrorEventArgs slashCommandErrorEventArgs) { if (slashCommandErrorEventArgs.Exception is SlashExecutionChecksFailedException) { return; } else if (slashCommandErrorEventArgs.Exception is InvalidOperationException && slashCommandErrorEventArgs.Exception.Message == "A slash command was executed, but no command was registered for it.") { return; } DiscordChannel discordChannel = await slashCommandExtension.Client.GetChannelAsync(832374606748188743); DiscordMessageBuilder discordMessageBuilder = new(); string stackTrace = string.Join("\n\n", slashCommandErrorEventArgs.Exception.StackTrace.Split('\n').Select(line => line.Trim())).Truncate(1800); discordMessageBuilder.Content = $"`/{slashCommandErrorEventArgs.Context.CommandName}` threw a {slashCommandErrorEventArgs.Exception.GetType()}: {slashCommandErrorEventArgs.Exception.Message ?? "<no message>"}\n{Formatter.BlockCode(stackTrace, "cs")}"; await discordChannel.SendMessageAsync(discordMessageBuilder); }
public static async Task CommandErrored(SlashCommandsExtension slashCommandExtension, SlashCommandExecutedEventArgs slashCommandExecutedEventArgs) { using IServiceScope scope = Program.ServiceProvider.CreateScope(); Database database = scope.ServiceProvider.GetService <Database>(); if (slashCommandExecutedEventArgs.Context.Guild == null) { return; } GuildMember guildMember = database.GuildMembers.FirstOrDefault(user => user.UserId == slashCommandExecutedEventArgs.Context.Member.Id && user.GuildId == slashCommandExecutedEventArgs.Context.Guild.Id); if (guildMember == null) { database.AddGuildMember(slashCommandExecutedEventArgs.Context.Member); await database.SaveChangesAsync(); } slashCommandExecutedEventArgs.Handled = true; }
public LTPFeature(DiscordClient dClient) { this.cNext = dClient.GetCommandsNext(); this.slash = dClient.GetSlashCommands(); }
public async Task RunAsync() { ReadConfig.Read(); var varrepo = new VariableRepository(ReadConfig.Config.ConnectionString); bool result; #if DEBUG result = varrepo.Read(3, out Variable prefix); //get testPrefix if in designmode #else result = varrepo.Read(2, out Variable prefix); //otherwise get default prefix #endif DiscordConfiguration config = new DiscordConfiguration { Token = ReadConfig.Config.Token, TokenType = TokenType.Bot, AutoReconnect = true, #if DEBUG MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Debug, #endif Intents = DiscordIntents.All }; Client = new DiscordClient(config); //Register client events Client.Ready += Events.OnClientReady; Client.GuildDownloadCompleted += Events.Client_GuildDownloadCompleted; Client.MessageCreated += Events.MessageCreated; Client.MessageUpdated += Events.MessageUpdated; Client.MessageDeleted += Events.MessageDeleted; Client.GuildMemberAdded += Events.MemberAdded; Client.MessageReactionAdded += Events.ReactionAdded; Client.MessageReactionRemoved += Events.ReactionRemoved; Client.VoiceStateUpdated += Events.VoiceStateUpdated; Client.ClientErrored += Events.ClientErrored; Client.ComponentInteractionCreated += Events.ComponentTriggered; //Register client events for logging Client.GuildBanAdded += Logger.BanAdded; Client.GuildBanRemoved += Logger.BanRemoved; Client.GuildMemberUpdated += Logger.MemberUpdated; Client.ChannelUpdated += Logger.ChannelUpdated; Client.GuildRoleUpdated += Logger.RoleUpdated; Client.MessageUpdated += Logger.MessageEdited; Client.MessageDeleted += Logger.MessageDeleted; Client.MessagesBulkDeleted += Logger.BulkMessagesDeleted; //Client.GuildEmojisUpdated += Logger.EmojiUpdated; Client.VoiceStateUpdated += Logger.VoiceUpdate; //Register timer events SystemService.Instance.WarnTimer.Elapsed += Events.TimerTick; //Register Logger events SystemService.Instance.Logger.RaiseLogEvent += Events.OnLog; Client.UseInteractivity(new InteractivityConfiguration { Timeout = TimeSpan.FromMinutes(5), PollBehaviour = PollBehaviour.KeepEmojis, AckPaginationButtons = true }); CommandsNextConfiguration commandsConfig = new CommandsNextConfiguration { StringPrefixes = new string[] { prefix.Value }, EnableMentionPrefix = true }; Commands = Client.UseCommandsNext(commandsConfig); //Register commands Commands.RegisterCommands <AuditCommands>(); Commands.RegisterCommands <EmbedCommands>(); Commands.RegisterCommands <InfoCommands>(); Commands.RegisterCommands <LavalinkCommands>(); Commands.RegisterCommands <ReactionCommands>(); Commands.RegisterCommands <RuleCommands>(); Commands.RegisterCommands <TechnicalCommands>(); Commands.RegisterCommands <WarnCommands>(); Commands.RegisterCommands <EventCommands>(); //Register command events Commands.CommandErrored += Events.CommandErrored; SlashCommands = Client.UseSlashCommands(); //Register interactions SlashCommands.RegisterCommands <WarnInteractions>(699555747591094344); //Register interaction events SlashCommands.ContextMenuErrored += Events.ContextMenuErrored; await Client.ConnectAsync(); LavalinkNodeConnection lavaNode = null; lavaNode = await ConnectLavaNodeAsync(); if (lavaNode != null) { //Register lava commands lavaNode.PlaybackFinished += Events.PlaybackFinished; } await Task.Delay(-1); }
static async Task MainAsync(string[] args) { //Настройка базовой конфигурации бота DiscordConfiguration DiscordConfig = new DiscordConfiguration { Token = DiscordToken, TokenType = TokenType.Bot, MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Debug, Intents = DiscordIntents.AllUnprivileged }; discord = new DiscordClient(DiscordConfig); string[] Prefixes = new string[1]; Prefixes[0] = "!!"; //Настройка списка комманд CommandsNextConfiguration commandsConfig = new CommandsNextConfiguration { StringPrefixes = Prefixes, EnableMentionPrefix = true }; InteractivityConfiguration interactivityConfig = new InteractivityConfiguration { PollBehaviour = DSharpPlus.Interactivity.Enums.PollBehaviour.KeepEmojis, Timeout = TimeSpan.FromSeconds(30) }; SlashCommandsExtension slashCommands = discord.UseSlashCommands(); //slashCommands.RegisterCommands<MyCommands>(); commands = discord.UseCommandsNext(commandsConfig); commands.RegisterCommands <MyCommands> (); commands.RegisterCommands <VozhbanCommands> (); MyCommands.FillList(); VozhbanCommands.LoadText(); Console.WriteLine("Bot staterted 3.0"); //Working when readction added discord.MessageReactionAdded += Clock; discord.MessageReactionAdded += Permission; discord.MessageCreated += RollDice; discord.MessageCreated += RollXDice; discord.MessageCreated += TolpojDS; async Task Clock(DiscordClient discordClient, 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(DiscordClient discordClient, MessageReactionAddEventArgs context) { if (context.Emoji.Name == "🔫") { await context.Message.RespondAsync(context.Message.Author.Username + " расстрелян"); } } async Task TolpojDS(DiscordClient discordClient, MessageCreateEventArgs context) { string message = context.Message.Content; if (message.Contains("<@&515543976678391808>")) //("<@&515543976678391808>")) { { await context.Message.CreateReactionAsync(DiscordEmoji.FromName(discordClient, ":r1:", true)); await context.Message.CreateReactionAsync(DiscordEmoji.FromName(discordClient, ":g6:", true)); } } async Task RollXDice(DiscordClient discordClient, 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; int Sum = 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) { 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; } if (RollCount == 1) { int Dice = Die.Next(1, Sides + 1); if (Mod == 0) { Respond += context.Message.Author.Mention + " кидает " + Sides + "-гранник и выкидывает **" + Dice + "**\n"; } else { Respond += context.Message.Author.Mention + " кидает " + Sides + "-гранник и выкидывает " + Dice + Sign + Mod + " = **" + (Dice + Mod) + "**\n"; } } else if (RollCount > 1) { if (Mod == 0) { Respond += context.Message.Author.Mention + " кидает " + Sides + "-гранник " + RollCount + " раз и выкидывает **"; } else { Respond += context.Message.Author.Mention + " кидает " + Sides + "-гранник [" + Sign + Mod + "] " + RollCount + " раз и выкидывает **"; } for (int i = 0; i < RollCount; i++) { int Dice = Die.Next(1, Sides + 1); Sum += Dice + Mod; Respond += (Dice + Mod); if (i == RollCount - 1) { Respond += "**."; } else { Respond += ", "; } } Respond += "\nСумма: **" + Sum + "**"; } await context.Message.RespondAsync(Respond); await context.Message.DeleteAsync(); } } async Task RollDice(DiscordClient discordClient, MessageCreateEventArgs context) { string Message = context.Message.Content.ToLower(); int d = Message.IndexOf("d"); if (d != -1) { string Respond = ""; int RollCount = 0; int Mod = 0; int Sum = 0; string Sign = ""; Random GreenDie = new Random(); Random RedDie = new Random(); 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"; } } } Console.Write("Message" + context.Message.Content + " RollCount: " + RollCount); if (int.TryParse(Message.Remove(0, d + 1), out Mod) == true) { if (Mod >= 0) { Sign = "+"; } } if (RollCount == 1) { int Green = GreenDie.Next(1, 7); int Red = RedDie.Next(1, 7); string SignD = ""; string EmoGreenDie; string EmoRedDie; EmoGreenDie = DiscordEmoji.FromName(discordClient, ":g" + Green + ":", true).ToString(); EmoRedDie = DiscordEmoji.FromName(discordClient, ":r" + Red + ":", true).ToString(); if (Green - Red + Mod > 0) { SignD = "+"; } /*if (Message.Length == d+1) { * Respond += context.Message.Author.Mention + " выкидывает " + EmoGreenDie + EmoRedDie + " | " + Green + " - " + Red + " = **" + SignD + (Green - Red); * return; * }*/ if (Mod == 0) { Respond += context.Message.Author.Mention + " выкидывает " + EmoGreenDie + EmoRedDie + " | " + Green + " - " + Red + " = **" + SignD + (Green - Red); } else { Respond += context.Message.Author.Mention + " выкидывает " + EmoGreenDie + EmoRedDie + " | " + Green + " - " + Red + " " + Sign + Mod + " = **" + SignD + (Green - Red + Mod); } if ((Green - Red) == 5) { Respond += ". Критический Успех"; } else if ((Green - Red) == -5) { Respond += ". Критический Провал"; } Respond += "**"; } else if (RollCount > 1) { if (Mod == 0) { Respond += context.Message.Author.Mention + " кидает кубы " + RollCount + " раз и выкидывает **"; } else { Respond += context.Message.Author.Mention + " кидает кубы [" + Sign + Mod + "] " + RollCount + " раз и выкидывает **"; } for (int i = 0; i < RollCount; i++) { int Green = GreenDie.Next(1, 7); int Red = RedDie.Next(1, 7); string SignD = ""; if (Green - Red + Mod > 0) { SignD = "+"; } Sum += Green - Red + Mod; if ((Green - Red) == 5) { Respond += "{__" + SignD + (Green - Red + Mod) + "__}"; } else if ((Green - Red) == -5) { Respond += "(__" + SignD + (Green - Red + Mod) + "__)"; } else { Respond += SignD + (Green - Red + Mod); } if (i == RollCount - 1) { Respond += "**."; } else { Respond += ", "; } } Respond += "\nСумма: **" + Sum + "**"; } 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); }
private Task SlashCommandService_CommandExecuted(SlashCommandsExtension sc, SlashCommandExecutedEventArgs e) { e.Context.Client.Logger.LogInformation(TestBotEventId, "User {User} executed '{Command}' in {Channel}", e.Context.User.Username, e.Context.CommandName, e.Context.Channel.Name); return(Task.CompletedTask); }
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); //}; }
private async Task RestartBot(DiscordSettings previousSettings, DiscordSettings newSettings, HashSet <ulong> currentGuilds) { if (!string.IsNullOrEmpty(newSettings.BotToken)) { if (!string.Equals(previousSettings.BotToken, newSettings.BotToken, StringComparison.OrdinalIgnoreCase)) { if (_client != null) { await _client.DisconnectAsync(); _client.Ready -= Connected; _client.ComponentInteractionCreated -= DiscordComponentInteractionCreatedHandler; _client.Dispose(); } if (_slashCommands != null) { _slashCommands.SlashCommandErrored -= SlashCommandErrorHandler; } var config = new DiscordConfiguration() { Token = newSettings.BotToken, TokenType = TokenType.Bot, AutoReconnect = true, MinimumLogLevel = LogLevel.Warning, Intents = DiscordIntents.All, ReconnectIndefinitely = true }; _client = new DiscordClient(config); _slashCommands = _client.UseSlashCommands(new SlashCommandsConfiguration { Services = new ServiceCollection() .AddSingleton <DiscordClient>(_client) .AddSingleton <ILogger>(_logger) .AddSingleton <DiscordSettingsProvider>(_discordSettingsProvider) .AddSingleton <MovieWorkflowFactory>(_movieWorkflowFactory) .AddSingleton <TvShowWorkflowFactory>(_tvShowWorkflowFactory) .BuildServiceProvider() }); _slashCommands.SlashCommandErrored += SlashCommandErrorHandler; _client.Ready += Connected; _client.ComponentInteractionCreated += DiscordComponentInteractionCreatedHandler; _currentGuilds = new HashSet <ulong>(); await _client.ConnectAsync(); } if (_client != null) { if (_client.Guilds.Any()) { await ApplyBotConfigurationAsync(newSettings); var prop = _slashCommands.GetType().GetProperty("_updateList", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); prop.SetValue(_slashCommands, new List <KeyValuePair <ulong?, Type> >()); var slashCommandType = SlashCommandBuilder.Build(_logger, newSettings, _serviceProvider.Get <RadarrSettingsProvider>(), _serviceProvider.Get <SonarrSettingsProvider>(), _serviceProvider.Get <OverseerrSettingsProvider>()); if (newSettings.EnableRequestsThroughDirectMessages) { try { _slashCommands.RegisterCommands(slashCommandType); } catch (System.Exception ex) { _logger.LogError(ex, "Error while registering global slash commands: " + ex.Message); } foreach (var guildId in _client.Guilds.Keys) { try { _slashCommands.RegisterCommands <EmptySlashCommands>(guildId); } catch (System.Exception ex) { _logger.LogError(ex, $"Error while emptying guild-specific slash commands for guid {guildId}: " + ex.Message); } } } else { try { _slashCommands.RegisterCommands <EmptySlashCommands>(); } catch (System.Exception ex) { _logger.LogError(ex, "Error while emptying global slash commands: " + ex.Message); } foreach (var guildId in _client.Guilds.Keys) { try { _slashCommands.RegisterCommands(slashCommandType, guildId); } catch (System.Exception ex) { _logger.LogError(ex, $"Error while registering guild-specific slash commands for guid {guildId}: " + ex.Message); } } } await _slashCommands.RefreshCommands(); await Task.Delay(TimeSpan.FromMinutes(1)); } } else { _logger.LogWarning("No Bot Token for Discord has been configured."); } } }