예제 #1
0
 private async Task DeleteMessages(DiscordMessage response, bool delete, TimeSpan timeout, bool deleteResponse = true)
 {
     try
     {
         if (delete && !_context.Channel.IsPrivate)
         {
             try
             {
                 await _message.DeleteAsync();
             }
             catch (Exception) { }
         }
         if (timeout.TotalMilliseconds == 0 && deleteResponse && !_context.Channel.IsPrivate)
         {
             await response.DeleteAsync();
         }
         else if (timeout.TotalMilliseconds > 0 && deleteResponse && !_context.Channel.IsPrivate)
         {
             await Task.Delay(timeout).ContinueWith(async(_) =>
             {
                 await response.DeleteAsync();
             });
         }
     }
     catch (Exception ex) when(LogError(ex))
     {
     }
 }
예제 #2
0
        public async Task Leave(CommandContext ctx)
        {
            DiscordMessage tmp = await ctx.RespondAsync("DC");

            VoiceNextExtension vnext = ctx.Client.GetVoiceNext();
            await tmp.DeleteAsync();

            tmp = await ctx.RespondAsync("DC: GVNC");

            VoiceNextConnection vnc = vnext.GetConnection(ctx.Guild);
            await tmp.DeleteAsync();

            tmp = await ctx.RespondAsync("DC: CVNC");

            if (vnc == null)
            {
                throw new InvalidOperationException("Not connected in this guild.");
            }
            await tmp.DeleteAsync();

            tmp = await ctx.RespondAsync("DC: DCXC");

            vnc.Disconnect();
            await tmp.DeleteAsync();

            await ctx.RespondAsync("👌");
        }
예제 #3
0
        private async Task <bool> VerificarAsync(DiscordChannel channel, DiscordUser autor, int time = 30)
        {
            DiscordMessage verificacion = await channel.SendMessageAsync(EasyDualLanguageFormatting("¿Estas seguro?", "Are you sure?"));

            await WoteAsync(verificacion, false);

            HelperMethods.Delay(1000);
            for (int i = 0; i < time; i++)
            {
                IReadOnlyList <DiscordUser> reaccionesOK = await verificacion.GetReactionsAsync(DiscordEmoji.FromName(Client, ":white_check_mark:"));

                IReadOnlyList <DiscordUser> reaccionesNOPE = await verificacion.GetReactionsAsync(DiscordEmoji.FromName(Client, ":x:"));

                if (reaccionesOK.Contains(autor))
                {
                    await verificacion.DeleteAsync();

                    return(true);
                }
                if (reaccionesNOPE.Contains(autor))
                {
                    await verificacion.DeleteAsync();

                    return(false);
                }
                HelperMethods.Delay(1000);
            }

            await verificacion.DeleteAsync();

            return(false);
        }
예제 #4
0
        internal static async Task MessagesUpdateAsync(DiscordMessage mess)
        {
            Duel d = duels.Find(cd => mess == cd);

            if (d != null)
            {
                if (d.duel.flag)
                {
                    await mess.DeleteAsync();

                    return;
                }

                DiscordMessage mess1 = null, mess2 = null;

                try { mess1 = await mess.Channel.GetMessageAsync(d.duel.message1); } catch { }
                try { mess2 = await mess.Channel.GetMessageAsync(d.duel.message2); } catch { }

                if (mess1?.Author.Id == mess.Author.Id)
                {
                    await mess1.DeleteAsync();
                }
                else if (mess2?.Author.Id == mess.Author.Id)
                {
                    await mess2.DeleteAsync();
                }

                if (mess.Author.Id == d.duel.duelist1)
                {
                    d.duel.message1 = mess.Id;
                }
                else
                {
                    d.duel.message2 = mess.Id;
                }

                await d.UpdateAsync();

                await mess.CreateReactionAsync(await mess.Channel.Guild.GetEmojiAsync(604972398424621066u));

                await mess.CreateReactionAsync(await mess.Channel.Guild.GetEmojiAsync(604973811154288660u));

                if (!IsDuelReactionAdded)
                {
                    Program.bot.MessageReactionAdded += DuelReactionsAdded;
                    IsDuelReactionAdded = true;
                }
            }
            else
            {
                await mess.DeleteAsync();
            }
        }
예제 #5
0
        public async Task CheckForLeavers(CommandContext ctx, string clanTag)
        {
            var roles        = ctx.Member.Roles.ToList();
            var verification = await IsVerifiedAsync(ctx, true);

            var clan = await GetClanFromTagOrNameAsync(ctx, clanTag);

            clanTag = clanTag.ToLower();

            if (clan != null && verification == ErrorCode.Qualify && !string.IsNullOrEmpty(clan.details.Tag))
            {
                var            discordEmbed = Core.Discord.CreateFancyMessage(DiscordColor.Turquoise, "Checking for leavers...");
                DiscordMessage msg          = await ctx.RespondAsync(discordEmbed);

                var leavers = await BungieTools.CheckForLeaves(clan, true);

                if (leavers.Count > 0)
                {
                    await msg.DeleteAsync();

                    var fields = new List <Field>();
                    Core.Discord.SendFancyListMessage(ctx.Channel, clan, leavers, "Users found leaving " + clan.details.Name + ":");
                }
                else
                {
                    discordEmbed = Core.Discord.CreateFancyMessage(DiscordColor.SpringGreen, "No leavers found", "No one to remove from sheet <:unipeepo:601277029459034112>");
                    await msg.ModifyAsync(discordEmbed);
                }
                await ThankUsage(ctx, clan, 100);
            }
        }
예제 #6
0
            public async Task Disable(CommandContext ctx)
            {
                var GuildSettings = await discordUrie.Config.FindGuildSettings(ctx.Guild);

                if (GuildSettings.BansEnabled)
                {
                    discordUrie.Config.GuildSettings.Remove(GuildSettings);
                    GuildSettings.BansEnabled = false;

                    discordUrie.Config.GuildSettings.Add(GuildSettings);
                    await GuildSettings.SaveGuild(discordUrie.SQLConn);

                    DiscordMessage ImSoTired = await ctx.RespondAsync("Chat bans disabled...");

                    await Task.Delay(2070);

                    await ctx.Message.DeleteAsync("Command auto deletion.");

                    await ImSoTired.DeleteAsync("Command auto deletion.");
                }
                else
                {
                    DiscordMessage a = await ctx.RespondAsync("Chat bans are already disabled!");

                    await Task.Delay(2070);

                    await ctx.Message.DeleteAsync("Command auto deletion.");

                    await a.DeleteAsync("Command auto deletion.");
                }
            }
예제 #7
0
            public async Task AddBan(CommandContext ctx, [Description("The user id to add")] DiscordMember user)
            {
                var  util    = new Util(discordUrie);
                bool success = await util.AddBan(ctx.Client, user.Id, ctx.Guild);

                if (success == true)
                {
                    DiscordMessage IWishIWasDeadThanks = await ctx.RespondAsync("Id added sucessfully.");

                    await Task.Delay(2070);

                    await ctx.Message.DeleteAsync("Command auto deletion.");

                    await IWishIWasDeadThanks.DeleteAsync("Command auto deletion.");
                }
                else
                {
                    DiscordMessage IReallyWishIWasDeadThankYou = await ctx.RespondAsync("Id already in list...");

                    await Task.Delay(2070);

                    await ctx.Message.DeleteAsync("Command auto deletion.");

                    await IReallyWishIWasDeadThankYou.DeleteAsync("Command auto deletion.");
                }
            }
예제 #8
0
        public async Task Study(CommandContext ctx)
        {
            DiscordMessage mensaje = await ctx.RespondAsync("You need to put a subject!");

            System.Threading.Thread.Sleep(5000);
            await mensaje.DeleteAsync();
        }
예제 #9
0
            public async Task Enable(CommandContext ctx)
            {
                var GuildSettings = await discordUrie.Config.FindGuildSettings(ctx.Guild);

                if (GuildSettings.BansEnabled)
                {
                    DiscordMessage woah = await ctx.RespondAsync("Chat bans are already enabled!");

                    await Task.Delay(2070);

                    await ctx.Message.DeleteAsync("Command auto deletion.");

                    await woah.DeleteAsync("Command auto deletion.");
                }
                else
                {
                    discordUrie.Config.GuildSettings.Remove(GuildSettings);
                    GuildSettings.BansEnabled = true;
                    discordUrie.Config.GuildSettings.Add(GuildSettings);
                    await GuildSettings.SaveGuild(discordUrie.SQLConn);

                    DiscordMessage woaaah = await ctx.RespondAsync("Chat bans enabled...");

                    await Task.Delay(2070);

                    await ctx.Message.DeleteAsync("Command auto deletion.");

                    await woaaah.DeleteAsync("Command auto deletion.");
                }
            }
예제 #10
0
        private void ManageException(DiscordMessage message, DiscordUser author, DiscordChannel channel, Exception ex, BaseDiscordCommand command)
        {
            LogMessage?.Invoke(this, $"\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))
            {
                new Task(async() =>
                {
                    try
                    {
                        DiscordMessage msg = await channel.SendMessageAsync(
                            $"Something's gone very wrong executing that command, and an {ex.GetType().Name} occured." +
                            "\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();
            }
        }
예제 #11
0
        public async Task Sendreactiongear(CommandContext ctx, DiscordMessage embedMessage, bool userSelf)
        {
            if (userSelf == true)
            {
                DiscordEmoji gearEmoji = DiscordEmoji.FromName(ctx.Client, ":gear:");
                await embedMessage.CreateReactionAsync(gearEmoji).ConfigureAwait(false);

                var interactivity = ctx.Client.GetInteractivity();

                try
                {
                    var ReactionResult = await interactivity.WaitForReactionAsync(
                        x => x.Message == embedMessage &&
                        x.User == ctx.User &&
                        (x.Emoji == gearEmoji)).ConfigureAwait(false);

                    if (ReactionResult.Result.Emoji == gearEmoji)
                    {
                        await embedMessage.DeleteAsync(null);
                        await SetId(ctx, ctx.Member.Id, userSelf);

                        return;
                    }
                }
                catch
                {
                    await embedMessage.DeleteAllReactionsAsync(null);
                }
            }
        }
예제 #12
0
        public async Task EvaluateAsync(CommandContext ctx,
                                        [RemainingText, Description("desc-code")] string code)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                throw new InvalidCommandUsageException(ctx, "cmd-err-cmd-add-cb");
            }

            DiscordMessage msg = await ctx.RespondWithLocalizedEmbedAsync(emb => {
                emb.WithLocalizedTitle("str-eval");
                emb.WithColor(this.ModuleColor);
            });

            Script <object>?snippet = CSharpCompilationService.Compile(code, out ImmutableArray <Diagnostic> diag, out Stopwatch compileTime);

            if (snippet is null)
            {
                await msg.DeleteAsync();

                throw new InvalidCommandUsageException(ctx, "cmd-err-cmd-add-cb");
            }

            var emb = new LocalizedEmbedBuilder(this.Localization, ctx.Guild?.Id);

            if (diag.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                emb.WithLocalizedTitle("str-eval-fail-compile");
                emb.WithLocalizedDescription("fmt-eval-fail-compile", compileTime.ElapsedMilliseconds, diag.Length);
                emb.WithColor(DiscordColor.Red);

                foreach (Diagnostic d in diag.Take(3))
                {
                    FileLinePositionSpan ls = d.Location.GetLineSpan();
                    emb.AddLocalizedTitleField("fmt-eval-err", Formatter.InlineCode(d.GetMessage()),
                                               titleArgs: new object[] { ls.StartLinePosition.Line, ls.StartLinePosition.Character }
                                               );
                }

                if (diag.Length > 3)
                {
                    emb.AddLocalizedField("str-eval-omit", "fmt-eval-omit", contentArgs: new object[] { diag.Length - 3 });
                }

                await UpdateOrRespondAsync();

                return;
            }

            Exception?           exc = null;
            ScriptState <object>?res = null;
            var runTime = Stopwatch.StartNew();

            try {
                res = await snippet.RunAsync(new EvaluationEnvironment(ctx));
            } catch (Exception e) {
                exc = e;
            }
            runTime.Stop();

            if (exc is { } || res is null)
예제 #13
0
        public async Task UnbanWord(CommandContext ctx,
                                    [Description("The word you want to be removed from the list.")] string word)
        {
            await ctx.Message.DeleteAsync();

            await ctx.TriggerTypingAsync();

            string info = "";

            DB.DBLists.LoadBannedWords();
            var DBEntry = (from bw in DB.DBLists.AMBannedWords
                           where bw.Server_ID == ctx.Guild.Id
                           where bw.Word == word.ToLower()
                           select bw).FirstOrDefault();

            if (DBEntry != null)
            {
                var context = new DB.AMBannedWordsContext();
                context.Remove(DBEntry);
                context.SaveChanges();
                info = $"The word `{word.ToLower()}` has been removed from the list.";
            }
            else
            {
                info = $"The word `{word.ToLower()}` is not listed for this server.";
            }
            DiscordMessage msg = await ctx.RespondAsync(info);

            await Task.Delay(5000).ContinueWith(t => msg.DeleteAsync());
        }
예제 #14
0
            public async Task sil(CommandContext ctx, int miktar)
            {
                try
                {
                    await ctx.TriggerTypingAsync();

                    await ctx.Message.DeleteAsync();

                    DiscordChannel kanal = ctx.Channel;
                    int            sayi  = miktar;
                    do
                    {
                        List <DiscordMessage> messages = (await kanal.GetMessagesAsync(sayi > 100 ? 100 : sayi)).ToList();
                        await kanal.DeleteMessagesAsync(messages);

                        sayi -= 100;
                    } while (sayi >= 100);


                    DiscordMessage msg = await ctx.RespondAsync($"Son {miktar} Mesaj Başarı İle Silindi.");

                    await Task.Delay(TimeSpan.FromSeconds(3));

                    await msg.DeleteAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("HATA : " + ex.Message);
                }
            }
예제 #15
0
        private async Task <string?> WaitForFinishingMoveAsync(LocalizationService lcs)
        {
            if (this.Winner is null)
            {
                return(null);
            }

            string         fstr = lcs.GetString(this.Channel.GuildId, "fmt-game-duel-f", Emojis.DuelSwords, this.Winner.Mention, Emojis.DuelSwords);
            DiscordMessage msg  = await this.Channel.EmbedAsync(fstr);

            InteractivityResult <DiscordMessage> mctx = await this.Interactivity.WaitForMessageAsync(
                m => m.Channel == this.Channel && m.Author == this.Winner,
                TimeSpan.FromSeconds(15)
                );

            if (mctx.TimedOut || string.IsNullOrWhiteSpace(mctx.Result.Content))
            {
                return(null);
            }

            try {
                await msg.DeleteAsync();

                await mctx.Result.DeleteAsync();
            } catch (Exception e) when(e is UnauthorizedException or NotFoundException)
            {
                // No permissions to delete the messages
            }

            return(mctx.Result.Content.Trim());
        }
    }
예제 #16
0
        /// <summary>
        /// Respond to bulk deletion by bulk deleting the bot’s messages.
        /// </summary>
        /// <param name="e">Discord information.</param>
        static public async Task BulkDelete(DiscordClient sender, MessageBulkDeleteEventArgs e)
        {
            // Ignore bots / DMs
            if (e.Messages?[0]?.Author?.IsBot == true || e.Channel?.Guild == null)
            {
                return;
            }

            foreach (var item in e.Messages)
            {
                // Ignore messages not in cache
                if (!Cache.ContainsKey(item.Id))
                {
                    continue;
                }
                ulong id = item.Id;

                // Delete bot’s message if possible
                try
                {
                    DiscordMessage message = await e.Channel.GetMessageAsync(Cache[id]);

                    Cache.Remove(id);
                    await message.DeleteAsync();
                } catch (Exception ex)
                {
                    Program.LogMessage($"Deleting the bot’s message {Cache[id]} returned an exception: {ex}");
                }
            }
        }
예제 #17
0
        /// <summary>
        /// Delete the bot’s message if one of the messages in cache was deleted.
        /// </summary>
        /// <param name="e">Discord message information.</param>
        static public async Task Delete(DiscordClient sender, MessageDeleteEventArgs e)
        {
            // Ignore other bots / DMs
            bool isBot    = (e.Message?.Author?.IsBot == true);
            bool isOurBot = (isBot && e.Message?.Author == Program.Client.CurrentUser);

            if (isBot && !isOurBot || e.Guild == null)
            {
                return;
            }
            ulong id = e.Message.Id;

            // Clear cache if bot’s message was deleted
            if (isOurBot && Cache.ContainsValue(id))
            {
                ulong key = Cache.FirstOrDefault(x => x.Value == id).Key;
                Cache.Remove(key);
                return;
            }

            // Ignore unknown messages / messages from our bot
            if (isOurBot || !Cache.ContainsKey(id))
            {
                return;
            }

            // Delete message
            DiscordMessage response = await e.Channel.GetMessageAsync(Cache[id]);

            Cache.Remove(id);
            await response.DeleteAsync();
        }
예제 #18
0
        public async Task UpdateHub(CommandContext ctx)
        {
            TimerMethod.UpdateHubInfo(true);
            DiscordMessage msg = await ctx.RespondAsync("TCHub info has been force updated.");

            await Task.Delay(10000).ContinueWith(f => msg.DeleteAsync());
        }
예제 #19
0
        public async Task RequestPoints()
        {
            DiscordMessageBuilder discordMessage = new DiscordMessageBuilder
            {
                Content = $"For this rule you can reduce the users chances by {Rule.MinPoints} - {Rule.MaxPoints}"
            };

            for (int i = 0; i < 3; i++)
            {
                List <DiscordButtonComponent> buttons = new List <DiscordButtonComponent>();
                for (int index = i * 5; index < (i * 5) + 5; index++)
                {
                    buttons.Add(new DiscordButtonComponent
                                (
                                    ButtonStyle.Primary,
                                    (index + 1).ToString(),
                                    (index + 1).ToString(),
                                    (index + 1) < Rule.MinPoints || (index + 1) > Rule.MaxPoints)
                                );
                }
                discordMessage.AddComponents(buttons);
            }
            DiscordMessage pointsMessage = await WarnChannel.SendMessageAsync(discordMessage);

            var interactpointsMessage = await Interactivity.WaitForButtonAsync(pointsMessage, Mod, TimeSpan.FromMinutes(2));

            PointsDeducted = int.Parse(interactpointsMessage.Result.Id);
            await pointsMessage.DeleteAsync();
        }
예제 #20
0
        public async Task AddNote(CommandContext ctx, DiscordUser user, [RemainingText] string note)
        {
            await ctx.Message.DeleteAsync();

            await ctx.TriggerTypingAsync();

            DB.Warnings newEntry = new()
            {
                Server_ID = ctx.Guild.Id,
                Active    = false,
                Admin_ID  = ctx.Message.Author.Id,
                Type      = "note",
                User_ID   = user.Id,
                Date      = DateTime.Now.ToString("yyyy-MM-dd"),
                Reason    = note
            };
            DB.DBLists.InsertWarnings(newEntry);

            DiscordMessage response = await new DiscordMessageBuilder()
                                      .WithContent($"{ctx.User.Mention}, a note has been added to {user.Username}({user.Id})")
                                      .WithAllowedMention(new UserMention())
                                      .SendAsync(ctx.Channel);
            await Task.Delay(10000).ContinueWith(t => response.DeleteAsync());
        }
    }
예제 #21
0
        private async Task <string> WaitForFinishingMoveAsync()
        {
            DiscordMessage msg = await this.Channel.EmbedAsync($"{StaticDiscordEmoji.DuelSwords} {this.Winner.Mention}, FINISH HIM! {StaticDiscordEmoji.DuelSwords}");

            InteractivityResult <DiscordMessage> mctx = await this.Interactivity.WaitForMessageAsync(
                m => m.ChannelId == this.Channel.Id && m.Author.Id == this.Winner.Id,
                TimeSpan.FromSeconds(15)
                );

            if (mctx.TimedOut || string.IsNullOrWhiteSpace(mctx.Result.Content))
            {
                return(null);
            }

            try {
                await msg.DeleteAsync();

                await mctx.Result.DeleteAsync();
            } catch (Exception e) when(e is UnauthorizedException || e is NotFoundException)
            {
                // No permissions to delete the messages
            }

            return(mctx.Result.Content.Trim());
        }
예제 #22
0
        public static async Task <bool> PromptUserToConfirm(CommandContext Context, string PromptMessage, bool bDeleteOnComplete = true)
        {
            var Interactivity = Context.Client.GetExtension <InteractivityExtension>();
            await Context.TriggerTypingAsync();

            DiscordMessage Msg = await Context.RespondAsync(PromptMessage);

            await Msg.CreateReactionAsync(DiscordEmoji.FromName(Context.Client, ":white_check_mark:"));

            await Msg.CreateReactionAsync(DiscordEmoji.FromName(Context.Client, ":x:"));

            var ReactContext = await Interactivity.WaitForReactionAsync(x => x.Emoji.Name == "✅" || x.Emoji.Name == "❌", Msg, Context.User);


            if (bDeleteOnComplete)
            {
                await Msg.DeleteAsync();
            }

            if (ReactContext.Result != null && ReactContext.Result.Emoji.Name == "✅")
            {
                return(true);
            }

            return(false);
        }
예제 #23
0
        public async Task BanWord(CommandContext ctx,
                                  [Description("The word that is banned")] string BannedWord,
                                  [Description("What the user will be warned with when using such word")][RemainingText] string warning)
        {
            await ctx.Message.DeleteAsync();

            await ctx.TriggerTypingAsync();

            string info = "";

            DB.DBLists.LoadBannedWords();
            var duplicate = (from bw in DB.DBLists.AMBannedWords
                             where bw.Server_ID == ctx.Guild.Id
                             where bw.Word == BannedWord.ToLower()
                             select bw).FirstOrDefault();

            if (duplicate is null)
            {
                DB.AMBannedWords newEntry = new()
                {
                    Word      = BannedWord.ToLower(),
                    Offense   = warning,
                    Server_ID = ctx.Guild.Id
                };
                DB.DBLists.InsertBannedWords(newEntry);
                info = $"The word `{BannedWord.ToLower()}` has been added to the list. They will be warned with `{warning}`";
            }
            else
            {
                info = $"The word `{BannedWord.ToLower()}` is already in the database for this server.";
            }
            DiscordMessage msg = await ctx.RespondAsync(info);

            await Task.Delay(5000).ContinueWith(t => msg.DeleteAsync());
        }
예제 #24
0
        public async Task RemoveServerAsync(IPEndPoint endPoint, ulong guildID)
        {
            GameServer serverToRemove = (await _dbContext.GameServers.AsQueryable().ToListAsync()).FirstOrDefault(x => x.ServerIP.Address.ToString() == endPoint.Address.ToString() && x.ServerIP.Port == endPoint.Port && x.GuildID == guildID);

            if (serverToRemove == null)
            {
                throw new ArgumentException("The specified server does not exist");
            }
            if (serverToRemove.MessageID != null)
            {
                try
                {
                    if (!_discordClient.Guilds.TryGetValue(serverToRemove.GuildID, out DiscordGuild guild))
                    {
                        return;
                    }
                    DiscordChannel channel = guild?.GetChannel(serverToRemove.ChannelID);
                    DiscordMessage msg     = await(channel?.GetMessageAsync(serverToRemove.MessageID.Value));
                    if (msg != null)
                    {
                        await msg.DeleteAsync();
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e, $"Error trying to remove message for game server {endPoint.Address}");
                }
            }
            _dbContext.GameServers.Remove(serverToRemove);
            await _dbContext.SaveChangesAsync();
        }
예제 #25
0
        public async Task CMDUpdated(CommandContext ctx,
                                     [Description("The name of the command you want to change the output of")] string command,
                                     [Description("Language tag (e.g. english is gb)")] string language,
                                     [Description("Text you want the bot to output for this command")][RemainingText] string BotResponse)
        {
            await ctx.TriggerTypingAsync();

            await ctx.Message.DeleteAsync();

            var BotOutputEntry = DB.DBLists.BotOutputList.FirstOrDefault(w => w.Command.Equals(command) && w.Language.Equals(language));

            if (BotOutputEntry is null)
            {
                await new DiscordMessageBuilder()
                .WithContent($"{ctx.Member.Mention}, This combination of command and language tag does not exist in the databse.")
                .WithAllowedMention(new UserMention())
                .SendAsync(ctx.Channel);
            }
            else
            {
                string completion_response = $"The response for `/{command}` was changed\n**From:** `{BotOutputEntry.Command_Text}`\n**To:** `{BotResponse}`";
                BotOutputEntry.Command_Text = BotResponse;
                DB.DBLists.UpdateBotOutputList(BotOutputEntry);
                DB.DBLists.LoadBotOutputList();
                DiscordMessage OutMSG = await ctx.RespondAsync(completion_response);

                await Task.Delay(10000).ContinueWith(t => OutMSG.DeleteAsync());
            }
        }
예제 #26
0
        async Task awaitdel(DiscordMessage discordMessage, int ms)
        {
            await Task.Delay(ms);

            try { await discordMessage.DeleteAsync(); }
            catch (Exception e) { Console.WriteLine($"Deleting message with ID {discordMessage.Id} failed. Reason: {e.Message}"); }
        }
예제 #27
0
            public async Task approvemimic(CommandContext ctx, [Description("The member in the mimic")] DiscordMember member, [Description("The Id or link of submission message.")] DiscordMessage discordMessage)
            {
                await ctx.Message.DeleteAsync().ConfigureAwait(false);

                int newId = 0;

                try
                {
                    newId = Directory.GetFiles($"Resources/Sound/Mimics/{ member.Id }/", "*", SearchOption.AllDirectories).Length;
                    using (WebClient client = new WebClient())
                    {
                        client.DownloadFile(discordMessage.Attachments.FirstOrDefault().Url, $"Resources/Sound/Mimics/{ member.Id }/{discordMessage.Attachments[0].FileName}.mp3");
                    }
                }
                catch
                {
                    Directory.CreateDirectory($"Resources/Sound/Mimics/{ member.Id }/");
                    using (WebClient client = new WebClient())
                    {
                        client.DownloadFile(discordMessage.Attachments.FirstOrDefault().Url, $"Resources/Sound/Mimics/{ member.Id }/{discordMessage.Attachments[0].FileName}");
                    }
                }

                await discordMessage.DeleteAsync();

                await ctx.Channel.SendMessageAsync($"Mimic for {member.Username} was added, Id is {newId}, name is {discordMessage.Attachments[0].FileName}.");
            }
예제 #28
0
        public async Task FlagMessageAsync(CommandContext ctx,
                                           [Description("Message.")] DiscordMessage msg        = null,
                                           [Description("Voting timespan.")] TimeSpan?timespan = null)
        {
            msg = msg ?? (await ctx.Channel.GetMessagesBeforeAsync(ctx.Channel.LastMessageId, 1))?.FirstOrDefault();

            if (msg is null)
            {
                throw new CommandFailedException("Cannot retrieve the message!");
            }

            if (timespan?.TotalSeconds < 5 || timespan?.TotalMinutes > 5)
            {
                throw new InvalidCommandUsageException("Timespan cannot be greater than 5 minutes or lower than 5 seconds.");
            }

            IEnumerable <PollEmoji> res = await msg.DoPollAsync(new[] { StaticDiscordEmoji.ArrowUp, StaticDiscordEmoji.ArrowDown }, PollBehaviour.Default, timeout : timespan ?? TimeSpan.FromMinutes(1));

            var votes = res.ToDictionary(pe => pe.Emoji, pe => pe.Voted.Count);

            if (votes.GetValueOrDefault(StaticDiscordEmoji.ArrowDown) > 2 * votes.GetValueOrDefault(StaticDiscordEmoji.ArrowUp))
            {
                string sanitized = FormatterExtensions.Spoiler(FormatterExtensions.StripMarkdown(msg.Content));
                await msg.DeleteAsync();

                await ctx.RespondAsync($"{msg.Author.Mention} said: {sanitized}");
            }
            else
            {
                await this.InformOfFailureAsync(ctx, "Not enough downvotes required for deletion.");
            }
        }
예제 #29
0
        public async Task Unbind(CommandContext ctx)
        {
            if (ctx.Channel.Get(ConfigManager.Enabled)
                .And(ctx.Channel.GetMethodEnabled()))
            {
                await ctx.TriggerTypingAsync();

                (ulong?channel, ulong?message) = ctx.Guild.GetReactionRoleMessage() ??
                                                 throw new Exception("Most likely already unbound");
                if (!channel.HasValue || !message.HasValue)
                {
                    await ctx.RespondAsync("Already unbound");

                    return;
                }
                DiscordMessage msg =
                    await(await ctx.Client.GetChannelAsync(channel.Value)).GetMessageAsync(message.Value);
                if (msg.Author.IsCurrent)
                {
                    await msg.DeleteAsync();
                }
                ctx.Guild.SetReactionRoleMessage(null);
                await ctx.RespondAsync("Done.");
            }
        }
예제 #30
0
        public async Task Addhours(CommandContext ctx)
        {
            DiscordMessage mensaje = await ctx.RespondAsync("You need to put a the number of hours and the subject! *in that order*");

            System.Threading.Thread.Sleep(5000);
            await mensaje.DeleteAsync();
        }