public async Task <EventHandlerResult> Handle(MessageReactionAddEventArgs eventArgs) { // https://discordapp.com/channels/366970031445377024/507515506073403402/686745124885364770 if (!(eventArgs.Message.Id == _config.VerificationMessageId && eventArgs.Message.ChannelId == _config.VerificationChannelId)) { return(EventHandlerResult.Continue); } if (!eventArgs.Emoji.Name.Equals(_config.VerificationEmojiName)) { return(EventHandlerResult.Continue); } DiscordUser user = eventArgs.User; DiscordDmChannel channel = await eventArgs.Guild.Members[user.Id].CreateDmChannelAsync(); string link = _urlProvider.GetAuthLink(user.Id, RolesPool.Auth); if (await _authorizationService.IsUserVerified(user.Id)) { await channel.SendMessageAsync( $"Ahoj, už jsi ověřený.\nPro aktualizaci rolí dle UserMap klikni na odkaz: {link}"); } else { await channel.SendMessageAsync( $"Ahoj, pro ověření a přidělení rolí dle UserMap klikni na odkaz: {link}"); } return(EventHandlerResult.Stop); }
private async Task EstablishTriviaMasterDm() { _triviaMasterDmChannel = await _client.CreateDmAsync(_triviaMaster); await _triviaMasterDmChannel.SendMessageAsync( $"You have been established as the Trivia Master for a Trivia {GetGameName()}"); }
public async Task SendErrorReportAsync(CommandContext ctx, [RemainingText, Description("Issue text.")] string issue) { if (string.IsNullOrWhiteSpace(issue)) { throw new InvalidCommandUsageException("Text missing."); } if (await ctx.WaitForBoolReplyAsync("Are you okay with your user and guild info being sent for further inspection?")) { ctx.Client.DebugLogger.LogMessage(LogLevel.Info, "TheGodfather", $"Report from {ctx.User.Username} ({ctx.User.Id}): {issue}", DateTime.Now); DiscordDmChannel dm = await ctx.Client.CreateDmChannelAsync(ctx.Client.CurrentApplication.Owners.First().Id); if (dm is null) { throw new CommandFailedException("Owner has disabled DMs."); } var emb = new DiscordEmbedBuilder { Title = "Issue", Description = issue }; emb.WithAuthor(ctx.User.ToString(), iconUrl: ctx.User.AvatarUrl ?? ctx.User.DefaultAvatarUrl); emb.AddField("Guild", $"{ctx.Guild.ToString()} owned by {ctx.Guild.Owner.ToString()}"); await dm.SendMessageAsync("A new issue has been reported!", embed : emb.Build()); await this.InformAsync(ctx, "Your issue has been reported.", important : false); } }
public async Task WarnAsync(CommandContext ctx, [Description("Member.")] DiscordMember member, [RemainingText, Description("Warning message.")] string msg = null) { var emb = new DiscordEmbedBuilder() { Title = "Warning received!", Description = $"Guild {Formatter.Bold(ctx.Guild.Name)} issued a warning to you through me.", Color = DiscordColor.Red, Timestamp = DateTime.Now }; if (!string.IsNullOrWhiteSpace(msg)) { emb.AddField("Warning message", msg); } try { DiscordDmChannel dm = await member.CreateDmChannelAsync(); await dm.SendMessageAsync(embed : emb.Build()); } catch { throw new CommandFailedException("I can't talk to that user..."); } await this.InformAsync(ctx, $"Successfully warned member {Formatter.Bold(member.DisplayName)} with message: {Formatter.BlockCode(msg)}", important : false); }
public async Task SendAsync(CommandContext ctx, [Description("u/c (for user or channel.)")] string desc, [Description("User/Channel ID.")] ulong xid, [RemainingText, Description("Message.")] string message) { if (string.IsNullOrWhiteSpace(message)) { throw new InvalidCommandUsageException(); } if (desc == "u") { DiscordDmChannel dm = await ctx.Client.CreateDmChannelAsync(xid); if (dm == null) { throw new CommandFailedException("I can't talk to that user..."); } await dm.SendMessageAsync(message); } else if (desc == "c") { DiscordChannel channel = await ctx.Client.GetChannelAsync(xid); await channel.SendMessageAsync(message); } else { throw new InvalidCommandUsageException("Descriptor can only be 'u' or 'c'."); } await this.InformAsync(ctx, $"Successfully sent the given message!", important : false); }
public async Task DisplayData(DiscordDmChannel d, bool Roles) { DiscordEmbedBuilder embed = new DiscordEmbedBuilder() { Color = DiscordColor.Blue, Title = "Secret Villain™" } .WithFooter("Heroes & Villains"); foreach (UserObject user in Players) { string statusString = user.Status == 0 ? "Alive" : user.Status == 1 ? "Dead" : "ERROR, Please report this to Jcryer."; string playerNumString = user.PlayerNum == -1 ? "N/A" : user.Status >= 0 ? user.PlayerNum.ToString() : "ERROR, Please report this to Jcryer."; string roleType = user.Role == 1 ? "Villain" : user.Role == 2 ? "Medic" : user.Role == 3 ? "Spy" : user.Role == 4 ? "Joker" : user.Role == 5 ? "Hero" : "ERROR, Please report this to Jcryer."; if (Roles) { embed.AddField(user.Username, "Role: " + roleType); } else { embed.AddField(user.Username, "Player number: " + playerNumString + Environment.NewLine + "Status: " + statusString); } } await d.SendMessageAsync("", embed : embed); }
public async Task AuthorizeCommand(CommandContext ctx) { DiscordMessage message = ctx.Message; DiscordUser user = message.Author; DiscordDmChannel channel = await message.Channel.Guild.Members[user.Id].CreateDmChannelAsync(); string link = _urlProvider.GetAuthLink(user.Id, RolesPool.Auth); if (await _authorizationService.IsUserVerified(user.Id)) { await channel.SendMessageAsync( $"You are already authorized.\nTo update roles follow this link: {link}"); } else { await channel.SendMessageAsync($"Hi, authorize by following this link: {link}"); } }
public override Task StopAsync(CancellationToken cancellationToken) { _supportChannel.SendMessageAsync($"I'm shutting down!"); Log.Information("disconnecting from Discord"); _discord.DisconnectAsync(); Task.Delay(1000); return(base.StopAsync(cancellationToken)); }
public static async Task <DiscordDmChannel> SendBanDMAsync(this DiscordDmChannel channel, string title, string description) { var e = new DiscordEmbedBuilder() .WithTitle(title) .WithColor(DiscordColor.Red) .WithDescription(description + " [here](https://forms.gle/PyxFAAKQ5W4GA8F5A)"); var message = await channel.SendMessageAsync(embed : e.Build()); return(channel); }
public static async Task <DiscordDmChannel> SendDMAsync(this DiscordDmChannel channel, string title, string description) { var e = new DiscordEmbedBuilder() .WithTitle(title) .WithColor(DiscordColor.Red) .WithDescription(description); var message = await channel.SendMessageAsync(embed : e.Build()); return(channel); }
public async Task Gibinvite(CommandContext ctx, int max_uses = 1, int age = 0) { DiscordChannel channel = await ctx.Client.GetChannelAsync(230004550973521932); DiscordInvite inv = await channel.CreateInviteAsync(age, max_uses, false, true, $"gibinvite command used in {ctx.Channel.Id}"); DiscordDmChannel chan = await ctx.Member.CreateDmChannelAsync(); await chan.SendMessageAsync($"Here's the invite you asked for: https://discord.gg/{inv.Code}"); await ctx.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Check} I've DMed you an invite to **Erisa's Corner** with `{max_uses}` use(s) and an age of `{age}`!"); }
private static void ManageException(DiscordMessage message, DiscordUser author, DiscordChannel channel, Exception ex, DiscordCommand command) { _appLogArea.WriteLine($"\n --- Something's f****d up! --- \n{ex.ToString()}\n"); TelemetryClient?.TrackException(ex, new Dictionary <string, string> { { "command", command.GetType().Name } }); if (!(ex is TaskCanceledException) && !(ex is OperationCanceledException)) { if (_ownerDm != null) { try { _ownerDm.SendMessageAsync($"An {ex.GetType().Name} has occured processing command \"{command.Name}\" in {channel.Mention}{(channel.Guild != null ? $" ({channel.Guild.Name})" : "")}"); _ownerDm.SendMessageAsync($"```\r\n" + $"{ex.ToString()}" + $"```"); _ownerDm.SendMessageAsync($"Message content: `{message.Content}`"); _ownerDm.SendMessageAsync($"Message author: {author.Mention}"); } catch { } } new Task(async() => { try { DiscordMessage msg = await channel.SendMessageAsync( $"Something's gone very wrong executing that command, and an {ex.GetType().Name} occured." + $"{(_ownerDm != null ? "\r\nThis error has been reported, and should be fixed soon:tm:!" : "")}" + $"\r\nThis message will be deleted in 10 seconds."); await Task.Delay(10_000); await msg.DeleteAsync(); } catch { } }).Start(); } }
public static async Task LogPrivate(DiscordDmChannel channel, string functionName, string description, string message, DiscordColor color) { DiscordEmbedBuilder builder = new DiscordEmbedBuilder(); builder.WithTitle("Changelog"); builder.WithThumbnailUrl("https://media.discordapp.net/attachments/496417444613586984/496671867109769216/logthumbnail.png"); builder.WithDescription("Info"); builder.AddField(name: "Command", value: $"{functionName}", inline: true); builder.AddField(name: "Description", value: $"{description}", inline: true); builder.AddField(name: "Message", value: $"{message}"); builder.WithFooter("Copyright 2018 Lala Sabathil"); await channel.SendMessageAsync(content : null, tts : false, embed : builder.Build()); }
public async Task JoinVillageCommand(CommandContext ctx) { //Vérification de base character + guild if (!dep.Entities.Characters.IsPresent(ctx.User.Id) || !dep.Entities.Guilds.IsPresent(ctx.Guild.Id)) { return; } Character character = dep.Entities.Characters.GetCharacterByDiscordId(ctx.User.Id); Case currentCase = dep.Entities.Map.GetCase(character.Location); //1 check existence village + appartenance village if (character.VillageName != null || currentCase.VillageId == ulong.MinValue) { DiscordEmbedBuilder embed = dep.Embed.CreateBasicEmbed(ctx.User, dep.Dialog.GetString("errorCantJoinVillage")); await ctx.RespondAsync(embed : embed); return; } //2 sinon ajout liste attente village // + prévenir roi ? Village village = dep.Entities.Villages.GetVillageById(currentCase.VillageId); if (!village.WaitingList.Contains(character.Id)) { village.WaitingList.Add(character.Id); } DiscordMember king = await ctx.Guild.GetMemberAsync(village.KingId); if (king != null) { DiscordDmChannel dm = await king.CreateDmChannelAsync(); DiscordEmbedBuilder embed = dep.Embed.CreateBasicEmbed(king, dep.Dialog.GetString("joinVillageMPKing")); await dm.SendMessageAsync(embed : embed); DiscordEmbedBuilder embedConfirm = dep.Embed.CreateBasicEmbed(king, dep.Dialog.GetString("joinvillageConfirmWaiting")); await ctx.RespondAsync(embed : embedConfirm); } else { DiscordEmbedBuilder embed = dep.Embed.CreateBasicEmbed(ctx.User, dep.Dialog.GetString("error")); await ctx.RespondAsync(embed : embed); } }
public Func <string, Task <DiscordMessage> > RespondTTS(bool delete, TimeSpan timeout) { return(async(content) => { DiscordMessage response; if (_directMessage) { DiscordDmChannel dm = await _context.Member.CreateDmChannelAsync(); response = await dm.SendMessageAsync(content, true); } else { response = await _message.RespondAsync(content, true); await DeleteMessages(response, delete, timeout); } return response; }); }
public async Task JoinAsync(CommandContext ctx) { if (!(this.Shared.GetEventInChannel(ctx.Channel.Id) is HoldemGame game)) { throw new CommandFailedException("There are no Texas Hold'Em games running in this channel."); } if (game.Started) { throw new CommandFailedException("Texas Hold'Em game has already started, you can't join it."); } if (game.Participants.Count >= 7) { throw new CommandFailedException("Texas Hold'Em slots are full (max 7 participants), kthxbye."); } if (game.IsParticipating(ctx.User)) { throw new CommandFailedException("You are already participating in the Texas Hold'Em game!"); } DiscordMessage handle; try { DiscordDmChannel dm = await ctx.Client.CreateDmChannelAsync(ctx.User.Id); handle = await dm.SendMessageAsync("Alright, waiting for Hold'Em game to start! Once the game starts, return here to see your hand!"); } catch { throw new CommandFailedException("I can't send you a message! Please enable DMs from me so I can send you the cards."); } using (DatabaseContext db = this.Database.CreateContext()) { if (!await db.TryDecreaseBankAccountAsync(ctx.User.Id, ctx.Guild.Id, game.MoneyNeeded)) { throw new CommandFailedException($"You do not have enough {this.Shared.GetGuildConfig(ctx.Guild.Id).Currency ?? "credits"}! Use command {Formatter.InlineCode("bank")} to check your account status."); } await db.SaveChangesAsync(); } game.AddParticipant(ctx.User, handle); await this.InformAsync(ctx, StaticDiscordEmoji.CardSuits[0], $"{ctx.User.Mention} joined the Hold'Em game."); }
public async Task ExecuteGroupAsync(CommandContext ctx) { DiscordEmbedBuilder builder = new DiscordEmbedBuilder() { Color = DiscordColor.Orange, Title = "Wolfy help", Description = "Hi, I'm Wolfy! <:awoo:254007902510120961>" }; builder.WithAuthor(ctx.Client.CurrentUser.Username, null, ctx.Client.CurrentUser.AvatarUrl); StringBuilder triggerBuilder = new StringBuilder(); triggerBuilder.AppendLine("There isn't any official help for my triggers. Offer me a <:wolfybone:259416003534913537>, or tell me to do a flip? Maybe regulars know a few more things I can do."); builder.AddField("Triggers", triggerBuilder.ToString()); builder.AddField("Commands", "`!awoo`: Posts an awoo image.\r\n`!winnie`: Posts a winnie image.\r\n`!help`: Displays this message."); DiscordDmChannel chan = await ctx.Client.CreateDmAsync(ctx.Message.Author); await chan.SendMessageAsync(embed : builder); }
private async Task RunCommand_Error(DiscordClient discord, MessageReactionAddEventArgs e, DiscordDmChannel supportChannel) { var _react = e.Emoji; // reaction to embed if (e.Message.Embeds != null && e.Message.Embeds.Any()) { var _embed = e.Message.Embeds[0]; var _splitDescription = _embed.Footer.Text.Split(">>"); //if (_splitDescription.Length != 2) return; var _area = _splitDescription[1].Split(':')[0].Trim(); var _recordId = _splitDescription[1].Split(':')[1].Trim(); //await e.Channel.SendMessageAsync("I see your thumbsdown"); await e.Channel.SendMessageAsync($"I've marked your {_area} entry with Id: {_recordId} for follow-up. Sorry for the inconvenience"); await supportChannel.SendMessageAsync("This was flagged as incorrect", false, _embed); } }
public async Task CreateAsync(CommandContext ctx, [Description("Channel to list webhooks for.")] DiscordChannel channel, [Description("Name.")] string name, [Description("Avatar URL.")] Uri avatarUrl = null, [RemainingText, Description("Reason.")] string reason = null) { DiscordWebhook wh; if (avatarUrl is null) { wh = await channel.CreateWebhookAsync(name, reason : ctx.BuildInvocationDetailsString(reason)); } else { try { using (Stream stream = await _http.GetStreamAsync(avatarUrl)) using (var ms = new MemoryStream()) { await stream.CopyToAsync(ms); ms.Seek(0, SeekOrigin.Begin); wh = await channel.CreateWebhookAsync(name, ms, reason : ctx.BuildInvocationDetailsString(reason)); } } catch (WebException e) { throw new CommandFailedException("Failed to fetch the image!", e); } } await this.InformAsync(ctx, "Created a new webhook! Sending you the token in private...", important : false); try { DiscordDmChannel dm = await ctx.Client.CreateDmChannelAsync(ctx.User.Id); if (dm is null) { throw new CommandFailedException("I failed to send you the token in private."); } await dm.SendMessageAsync($"Token for webhook {Formatter.Bold(wh.Name)} in {Formatter.Bold(ctx.Guild.ToString())}, {Formatter.Bold(channel.ToString())}: {Formatter.BlockCode(wh.Token)}\nWebhook URL: {wh.BuildUrlString()}"); } catch { // Failed to create DM or insufficient perms to send } }
public async Task MainAsync(string[] args) { string token = File.ReadAllText("callisto_token.key"); this.discord = new DiscordClient(new DiscordConfiguration { Token = token, TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Info }); this.discord.MessageCreated += async eventArgs => { if (this.ContainsBanned(eventArgs.Message.Content)) { //await eventArgs.Message.CreateReactionAsync(DiscordEmoji.FromName(this.discord, ":pika:")); await eventArgs.Channel.SendMessageAsync($"Bad {eventArgs.Author.Username}#{eventArgs.Author.Discriminator}!"); } }; this.discord.MessageCreated += async eventArgs => { if (eventArgs.Author.Id == this.discord.CurrentApplication.Owner.Id && eventArgs.Message.Content.ToLower() == "arcas") { await eventArgs.Channel.SendMessageAsync($"Goodbye"); Environment.Exit(0); } }; await this.discord.ConnectAsync(); Console.WriteLine("ready"); DiscordDmChannel dm = await this.discord.CreateDmAsync(this.discord.CurrentApplication.Owner); await dm.SendMessageAsync(content : $"{this.discord.CurrentUser.Username} ready"); await Task.Delay(-1); }
public async Task SendCooldownAlarm(CommandContext ctx, DiscordMessage msg, TimeSpan timeSpan) { try { await msg.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":alarm_clock:")); var interactivity = ctx.Client.GetInteractivity(); var reaction = await interactivity.WaitForReactionAsync( x => x.Message == msg && x.User.Id == ctx.Member.Id && x.Emoji == DiscordEmoji.FromName(ctx.Client, ":alarm_clock:")); if (!reaction.TimedOut) { await msg.DeleteAllReactionsAsync(); DiscordDmChannel dmChannel = ctx.Guild.GetMemberAsync(ctx.Member.Id).Result.CreateDmChannelAsync().Result; DiscordEmbedBuilder CooldownEmbed = new DiscordEmbedBuilder() { Title = $"Your timer has been set.", Color = DiscordColor.Red }; CooldownEmbed.WithFooter("Keep in mind this timer will only go off if the bot is not reset (which happens fairly often)."); await msg.ModifyAsync(embed : CooldownEmbed.Build()); System.Threading.Thread.Sleep(Convert.ToInt32(timeSpan.TotalMilliseconds)); await dmChannel.SendMessageAsync($"Your cooldown has ended, you can now rob to your hearts content."); } else { await msg.DeleteAllReactionsAsync(); } } catch { await msg.DeleteAllReactionsAsync().ConfigureAwait(false); } }
public async Task <IReactionHandler.Result> HandleAddAsync(MessageReactionAddEventArgs eventArgs) { // https://discordapp.com/channels/366970031445377024/507515506073403402/686745124885364770 if (!(eventArgs.Message.Id == _config.VerificationMessageId && eventArgs.Message.ChannelId == _config.VerificationChannelId)) { return(IReactionHandler.Result.Continue); } if (!eventArgs.Emoji.Name.Equals(_config.StaffVerificationEmojiName)) { return(IReactionHandler.Result.Continue); } DiscordUser user = eventArgs.User; DiscordDmChannel channel = await eventArgs.Guild.Members[user.Id].CreateDmChannelAsync(); string link = _urlProvider.GetAuthLink(user.Id, RolesPool.Staff); await channel.SendMessageAsync($"Ahoj, pro získání rolí zaměstnance klikni na: {link}"); return(IReactionHandler.Result.Stop); }
public async Task <IReactionHandler.Result> HandleRemoveAsync(MessageReactionRemoveEventArgs eventArgs) { if (!(eventArgs.Message.Id == _config.VerificationMessageId && eventArgs.Message.ChannelId == _config.VerificationChannelId)) { return(IReactionHandler.Result.Continue); } if (!eventArgs.Emoji.Name.Equals(_config.StaffVerificationEmojiName)) { return(IReactionHandler.Result.Continue); } bool ungranted = await _roleManager.RevokeRolesPoolAsync(eventArgs.User.Id, RolesPool.Staff); if (!ungranted) { _logger.LogWarning("Ungranting roles for user {0} (id {1}) failed.", eventArgs.User.Username, eventArgs.User.Id); DiscordDmChannel channel = await eventArgs.Guild.Members[eventArgs.User.Id].CreateDmChannelAsync(); await channel.SendMessageAsync("Staff role se nepodařilo odebrat. Prosím, kontaktujte moderátory."); } return(IReactionHandler.Result.Continue); }
private async Task SendDM(DiscordMember member, string message, bool kicked) { DiscordDmChannel dmChannel = await member.CreateDmChannelAsync(); DiscordChannel sbaChannel = await this.dClient.GetChannelAsync(SBGChannels.SecretBaseAlpha); try { await dmChannel.SendMessageAsync(message); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception e) #pragma warning restore CA1031 // Do not catch general exception types { // Send the message in SBA as a public message to warn the user before we kick them. if (!kicked) { await sbaChannel.SendMessageAsync($"{member.Mention}, we tried to send you a message but failed. {message}"); } Log.Error(e, $"Unable to send an inactivity DM to {member.Username} : {member.Id}"); this.bloonLog.Error($"Unable to send an inactivity DM to {member.Username} : {member.Id}"); } }
public async Task <CommandResult> Run() { using (AccountsContext context = new AccountsContext()) { if (Context.Author is DiscordMember member) { Account account = await context.Accounts.FindAsync(member.Id); account = await Meta.EnsureAccountAsync(context, member, account); DiscordDmChannel channel = await member.CreateDmChannelAsync(); DiscordEmbedBuilder builder = new DiscordEmbedBuilder() .WithAuthor($"{member.DisplayName} - Bank of Wam", null, member.AvatarUrl); builder.AddField("Balance", account.Balance.ToString("N2")); decimal balance = account.Balance; foreach (Transaction transaction in account.TransactionHistory.AsEnumerable().Reverse().Take(12)) { balance -= transaction.Amount; builder.AddField(transaction.Reason, $"[{transaction.Time.ToString("u")}] W${transaction.Amount:N2}", true); builder.AddField("Balance", $"W${balance:N2}", true); } context.Accounts.Update(account); await channel.SendMessageAsync(embed : builder); return("Your bank statement has been sent. Check your DMs!"); } else { return("Okay what the f**k??"); } } }
public override async Task SendMessageAsync(string message) { await dmChannel.SendMessageAsync(message); }
private async Task <bool> Introduction(DiscordDmChannel dm, CommandContext ctx) { bool userAgrees = false; while (!userAgrees) { await dm.TriggerTypingAsync(); await Task.Delay(8000); await dm.SendMessageAsync($"I'm gonna send you a bunch of Questions.{Environment.NewLine}" + $"Please answer them.{Environment.NewLine}" + $"Don't worry, this is not a Quiz. I'll give you enough time.{Environment.NewLine}" + $"Most questions will also have possible answers written below. Some may require you, to input a text, some may only require a number.{Environment.NewLine}" + $"For every Question, there will be a \"Default\" option. If you don't know what to take / don't have a preference, take this."); await dm.TriggerTypingAsync(); await Task.Delay(12000); var builder = new DiscordEmbedBuilder() { Title = "Do you understand what i just wrote?", Url = "http://IJustWantThisToBeBlue.com" }; builder.AddField("I understand. Please go on.", "Yes"); builder.AddField("What?", "No"); await dm.SendMessageAsync(embed : builder.Build()); var m = await ctx.Client.GetInteractivity().WaitForMessageAsync( x => x.Channel.Id == dm.Id && x.Author.Id == ctx.Member.Id && Regex.IsMatch(x.Content, ConfirmRegex), TimeSpan.FromSeconds(240)); if (m.TimedOut) { await dm.SendMessageAsync($"Or just don't respond at all. That's ok too :("); return(false); } if (Regex.IsMatch(m.Result.Content, YesRegex)) { userAgrees = true; } else { await dm.SendMessageAsync($"Ok, let me explain it to you.{Environment.NewLine}" + $"I've just sent you a Question. Directly underneath it, you can see a fat \"**I understand**\", and a smaller \"Yes\". Right?{Environment.NewLine}" + $"The \"**I understand**\", is basically just a Description of your possible answer. In this case, the Answer is \"Yes\".{Environment.NewLine}" + $"So you can either answer exactly with \"Yes\", or exactly with \"No\".{Environment.NewLine}" + $"So let's try this again."); await dm.TriggerTypingAsync(); await Task.Delay(10000); } } return(userAgrees); }
public async Task DeleteMessageByLinkAndNotify(CommandContext commandContext, [Description("Deleteing message")] DiscordMessage msg, [Description("Deleting reason"), RemainingText] string reason) { if (msg is null) { await commandContext.RespondAsync("Deleting message is not specified"); return; } if (string.IsNullOrEmpty(reason)) { reason = "not stated"; } DiscordEmbedBuilder builder = new DiscordEmbedBuilder() .WithFooter($"Mod: {commandContext.Message.Author.Username} {msg.Timestamp}", iconUrl: commandContext.Message.Author.AvatarUrl) .WithDescription(msg.Content); if (!(msg.Author is null)) { builder.WithAuthor(name: $"From {msg.Channel.Name} by {msg.Author.Username}", iconUrl: msg.Author.AvatarUrl); } DiscordMember user = await wavGuild.GetMemberAsync(msg.Author.Id); if (!user.IsBot) { DiscordDmChannel targetChannel = await user.CreateDmChannelAsync(); await targetChannel.SendMessageAsync(content : $"Удалено по причине по причине: {reason}", embed : builder.Build()); if (msg.Embeds?.Count != 0) { foreach (var embed in msg.Embeds) { await targetChannel.SendMessageAsync(embed : embed); } } if (msg.Attachments?.Count != 0) { foreach (var att in msg.Attachments) { await targetChannel.SendMessageAsync(att.Url); } } } await LogChannel.SendMessageAsync( embed : new DiscordEmbedBuilder().WithAuthor(name : commandContext.Message.Author.Username, iconUrl : commandContext.Message.Author.AvatarUrl) .AddField("**Action**:", "delete message", true) .AddField("**Violator**:", msg.Author.Mention, true) .AddField("**From**:", msg.Channel.Name, true) .AddField("**Reason**:", reason, true) .WithFooter() .Build()); await LogChannel.SendMessageAsync(content : $"Deleted message: \n{new string('=', 20)}\n{msg.Content}"); if (msg.Embeds?.Count != 0) { foreach (var embed in msg.Embeds) { await LogChannel.SendMessageAsync(embed: embed); } } if (msg.Attachments?.Count != 0) { foreach (var att in msg.Attachments) { await LogChannel.SendMessageAsync(att.Url); } } await msg.Channel.DeleteMessageAsync(msg, reason); }
public async Task AskQuestion(CommandContext ctx) { var question = GameMaster.GetQuestion(_askedQuestions.Select(q => q.Id).ToList()); await ctx.RespondAsync($"Question: {question.QuestionText} [Time limit: 1 min]"); var interactivity = ctx.Client.GetInteractivityModule(); var answer = await interactivity.WaitForMessageAsync(msg => { // If this user has already answered this question, do not accept any new answers. if (_players.ContainsKey(msg.Author) && _players[msg.Author].QuestionsAnswered.ContainsKey(question.Id)) { msg.DeleteAsync(); return(false); } var result = question.VerifyAnswer(msg.Content); var response = false; switch (result.AnswerStatus) { case AnswerStatus.PartiallyCorrect: if (_players.ContainsKey(msg.Author)) { var player = _players[msg.Author]; player.AddAnswer(question, msg.Content, (int)((double)question.Points / 2)); } else { var userData = new UserGameData(msg.Author); userData.AddAnswer(question, msg.Content, (int)((double)question.Points / 2)); _players.TryAdd(msg.Author, userData); } break; case AnswerStatus.Error: _logger.Error(result.Exception, $"Error parsing command for question: {question.QuestionText}"); _triviaMasterDmChannel.SendMessageAsync( $"Error occured processing an answer! \nAnswer: {msg.Content}\nError Message: {result.Exception.Message}\n"); break; case AnswerStatus.NormalCorrect: if (_players.ContainsKey(msg.Author)) { var player = _players[msg.Author]; player.AddAnswer(question, msg.Content, question.Points); } else { var userData = new UserGameData(msg.Author); userData.AddAnswer(question, msg.Content, question.Points); _players.TryAdd(msg.Author, userData); } response = true; break; case AnswerStatus.BonusCorrect: if (_players.ContainsKey(msg.Author)) { var player = _players[msg.Author]; player.AddAnswer(question, msg.Content, question.BonusPoints.Value); } else { var userData = new UserGameData(msg.Author); userData.AddAnswer(question, msg.Content, question.BonusPoints.Value); _players.TryAdd(msg.Author, userData); } response = true; break; case AnswerStatus.Incorrect: if (_players.ContainsKey(msg.Author)) { var player = _players[msg.Author]; player.AddAnswer(question, msg.Content, 0); } else { var userData = new UserGameData(msg.Author); userData.AddAnswer(question, msg.Content, 0); _players.TryAdd(msg.Author, userData); } break; } msg.DeleteAsync(); return(response); }, TimeSpan.FromMinutes(1)); if (answer != null) { await ctx.RespondAsync($"User: {answer.User.Mention} answered correctly! [Round Over]"); } else { await ctx.RespondAsync("Timeout reached! [Round Over]"); } _roundCount++; _askedQuestions.Add(question); }
private async Task ExecuteKickCommand(CommandContext ctx, DiscordMember member, String Reason, Boolean Silent, Boolean DmMember, Boolean Invite) { if (!ctx.Member.HasPermission("insanitybot.moderation.kick")) { await ctx.Channel.SendMessageAsync(InsanityBot.LanguageConfig["insanitybot.error.lacking_permission"]); return; } //actually do something with the usedefault value String KickReason = Reason switch { "usedefault" => GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.no_reason_given"], ctx, member), _ => GetFormattedString(Reason, ctx, member) }; DiscordEmbedBuilder embedBuilder = null; DiscordEmbedBuilder moderationEmbedBuilder = new() { Title = "KICK", Color = DiscordColor.Red, Footer = new DiscordEmbedBuilder.EmbedFooter { Text = "InsanityBot 2020-2021" } }; moderationEmbedBuilder.AddField("Moderator", ctx.Member.Mention, true) .AddField("Member", member.Mention, true) .AddField("Reason", KickReason, true); try { _ = member.TryAddModlogEntry(ModlogEntryType.kick, KickReason); embedBuilder = new DiscordEmbedBuilder { Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.kick.success"], ctx, member), Color = DiscordColor.Red, Footer = new DiscordEmbedBuilder.EmbedFooter { Text = "InsanityBot 2020-2021" } }; if (Invite || DmMember) { DiscordDmChannel channel = await member.CreateDmChannelAsync(); if (DmMember) { await channel.SendMessageAsync(GetReason(GetFormattedString( InsanityBot.LanguageConfig["insanitybot.moderation.kick.reason"], ctx, member), KickReason)); } if (Invite) { await channel.SendMessageAsync((await ctx.Channel.CreateInviteAsync()).ToString()); } } _ = member.RemoveAsync(KickReason); _ = InsanityBot.ModlogQueue.QueueMessage(ModlogMessageType.Moderation, new DiscordMessageBuilder { Embed = moderationEmbedBuilder }); } catch (Exception e) { embedBuilder = new DiscordEmbedBuilder { Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.kick.failure"], ctx, member), Color = DiscordColor.Red, Footer = new DiscordEmbedBuilder.EmbedFooter { Text = "InsanityBot 2020-2021" } }; InsanityBot.Client.Logger.LogError($"{e}: {e.Message}"); } finally { if (!Silent) { await ctx.Channel.SendMessageAsync(embed : embedBuilder.Build()); } } } }