Esempio n. 1
0
        public async Task Start(IGuildUser user)
        {
            if (_phase == Phase.Started || _phase == Phase.Ended)
            {
                await _channel.SendErrorAsync(user.Mention + GetText("ttt_already_running")).ConfigureAwait(false);

                return;
            }
            else if (_users[0] == user)
            {
                await _channel.SendErrorAsync(user.Mention + GetText("ttt_against_yourself")).ConfigureAwait(false);

                return;
            }

            _users[1] = user;

            _phase = Phase.Started;

            _timeoutTimer = new Timer(async(_) =>
            {
                await _moveLock.WaitAsync();
                try
                {
                    if (_phase == Phase.Ended)
                    {
                        return;
                    }

                    _phase = Phase.Ended;
                    if (_users[1] != null)
                    {
                        _winner = _users[_curUserIndex ^= 1];
                        var del = _previousMessage?.DeleteAsync();
                        try
                        {
                            await _channel.EmbedAsync(GetEmbed(GetText("ttt_time_expired"))).ConfigureAwait(false);
                            if (del != null)
                            {
                                await del.ConfigureAwait(false);
                            }
                        }
                        catch { }
                    }

                    OnEnded?.Invoke(this);
                }
                catch { }
                finally
                {
                    _moveLock.Release();
                }
            }, null, _options.TurnTimer * 1000, Timeout.Infinite);

            _client.MessageReceived += Client_MessageReceived;


            _previousMessage = await _channel.EmbedAsync(GetEmbed(GetText("game_started"))).ConfigureAwait(false);
        }
Esempio n. 2
0
            public async Task Start(IGuildUser user)
            {
                if (_phase == Phase.Started || _phase == Phase.Ended)
                {
                    await _channel.SendErrorAsync(user.Mention + " TicTacToe Game is already running in this channel.").ConfigureAwait(false);

                    return;
                }
                else if (_users[0] == user)
                {
                    await _channel.SendErrorAsync(user.Mention + " You can't play against yourself.").ConfigureAwait(false);

                    return;
                }

                _users[1] = user;
                _log.Warn($"User {user} joined a TicTacToe game.");

                _phase = Phase.Started;

                timeoutTimer = new Timer(async(_) =>
                {
                    await moveLock.WaitAsync();
                    try
                    {
                        if (_phase == Phase.Ended)
                        {
                            return;
                        }

                        _phase = Phase.Ended;
                        if (_users[1] != null)
                        {
                            _winner = _users[curUserIndex ^= 1];
                            var del = previousMessage?.DeleteAsync();
                            try
                            {
                                await _channel.EmbedAsync(GetEmbed("Time Expired!")).ConfigureAwait(false);
                                await del.ConfigureAwait(false);
                            }
                            catch { }
                        }

                        OnEnded?.Invoke(this);
                    }
                    catch { }
                    finally
                    {
                        moveLock.Release();
                    }
                }, null, 15000, Timeout.Infinite);

                NadekoBot.Client.MessageReceived += Client_MessageReceived;


                previousMessage = await _channel.EmbedAsync(GetEmbed("Game Started")).ConfigureAwait(false);
            }
Esempio n. 3
0
            public TicTacToe(ITextChannel channel, IGuildUser firstUser)
            {
                _channel = channel;
                _users   = new IGuildUser[2] {
                    firstUser, null
                };
                _state = new int?[3, 3] {
                    { null, null, null },
                    { null, null, null },
                    { null, null, null },
                };

                _log = LogManager.GetCurrentClassLogger();
                _log.Warn($"User {firstUser} created a TicTacToe game.");
                _phase   = Phase.Starting;
                moveLock = new SemaphoreSlim(1, 1);

                timeoutTimer = new Timer(async(_) =>
                {
                    await moveLock.WaitAsync();
                    try
                    {
                        if (_phase == Phase.Ended)
                        {
                            return;
                        }

                        _phase = Phase.Ended;
                        if (_users[1] != null)
                        {
                            _winner = _users[curUserIndex ^= 1];
                            var del = previousMessage?.DeleteAsync();
                            try
                            {
                                await _channel.EmbedAsync(GetEmbed("Time Expired!")).ConfigureAwait(false);
                                await del.ConfigureAwait(false);
                            }
                            catch { }
                        }

                        OnEnded?.Invoke(this);
                    }
                    catch { }
                    finally
                    {
                        moveLock.Release();
                    }
                }, null, 15000, Timeout.Infinite);
            }
Esempio n. 4
0
        private async Task DisplayProfile()
        {
            IUserMessage profile =
                await Context.Channel.SendFileAsync(await _userService.GenerateProfileCard(Context.Message.Author));

            await Task.Delay(10000);

            await Context.Message.DeleteAsync();

            await Task.Delay(TimeSpan.FromMinutes(3d));

            await profile.DeleteAsync();
        }
Esempio n. 5
0
        public async void SendStatusMessageAsync(object state)
        {
            if (Cooldowns.GetMessageTimerCooldown() >= BotConfig.Load().MessageTimerCooldown)
            {
                if (lastTimerMessage != null)
                {
                    await lastTimerMessage.DeleteAsync();
                }

                var embed = new EmbedBuilder()
                {
                    Color = Colours.generalCol
                };
                embed.WithAuthor("GTA5Police Help", References.GetGta5policeLogo());
                embed.WithUrl(References.GetDashboardURL());
                embed.Description = "Be sure to check out our rules and policies, as well as other useful links!";
                embed.WithThumbnailUrl(References.GetGta5policeLogo());
                embed.AddField(new EmbedFieldBuilder()
                {
                    Name = BotConfig.Load().Prefix + "Rules", Value = "Rules and How We Ban."
                });
                embed.AddField(new EmbedFieldBuilder()
                {
                    Name = BotConfig.Load().Prefix + "Apply", Value = "Police, EMS, Mechanic, and Whitelist Applications"
                });
                embed.AddField(new EmbedFieldBuilder()
                {
                    Name = BotConfig.Load().Prefix + "Links", Value = "Useful Links."
                });
                embed.AddField(new EmbedFieldBuilder()
                {
                    Name = BotConfig.Load().Prefix + "Status", Value = "View the current status of the servers."
                });
                embed.AddField(new EmbedFieldBuilder()
                {
                    Name = BotConfig.Load().Prefix + "Developer", Value = "Displays information on the developer(s) of the bot."
                });
                embed.WithFooter("Message Timer with " + BotConfig.Load().MessageTimerInterval + " minute interval");
                embed.WithCurrentTimestamp();

                lastTimerMessage = await channel.SendMessageAsync("", false, embed);

                Cooldowns.ResetMessageTimerCooldown();
                Statistics.AddTimerMessages();
                await Program.Logger(new LogMessage(LogSeverity.Info, "GTA5Police Timers", "Timer message delivered successfully."));
            }
            else
            {
                await Program.Logger(new LogMessage(LogSeverity.Info, "GTA5Police Timers", "Timer message was not delivered due to the cooldown."));
            }
        }
Esempio n. 6
0
        public override async Task Start(IUserMessage umsg, ICommandContext context)
        {
            StartingMessage         = umsg;
            _client.MessageDeleted += MessageDeletedEventHandler;

            try { await StartingMessage.AddReactionAsync(new Emoji("🌸")).ConfigureAwait(false); }
            catch
            {
                try { await StartingMessage.AddReactionAsync(new Emoji("🌸")).ConfigureAwait(false); }
                catch
                {
                    try { await StartingMessage.DeleteAsync().ConfigureAwait(false); }
                    catch { return; }
                }
            }
            using (StartingMessage.OnReaction(_client, (r) =>
            {
                try
                {
                    if (r.UserId == _botUser.Id)
                    {
                        return;
                    }

                    if (r.Emote.Name == "🌸" && r.User.IsSpecified && ((DateTime.UtcNow - r.User.Value.CreatedAt).TotalDays > 5) && _flowerReactionAwardedUsers.Add(r.User.Value.Id))
                    {
                        _toGiveTo.Enqueue(r.UserId);
                    }
                }
                catch
                {
                    // ignored
                }
            }))
            {
                try
                {
                    await Task.Delay(TimeSpan.FromHours(24), CancelToken).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                }
                if (CancelToken.IsCancellationRequested)
                {
                    return;
                }

                _log.Warn("Stopping flower reaction event because it expired.");
                await End();
            }
        }
Esempio n. 7
0
        public async Task Trigger()
        {
            var toSend = "🔄 " + Repeater.Message;

            if (Repeater.NoRedundant)
            {
                var lastMsgInChannel = (await Channel.GetMessagesAsync(2).FlattenAsync()).FirstOrDefault();
                if (lastMsgInChannel != null && lastMsgInChannel.Id == oldMsg?.Id) //don't send if it's the same message in the channel
                {
                    return;
                }
            }

            if (oldMsg != null)
            {
                try
                {
                    await oldMsg.DeleteAsync();
                }
                catch
                {
                    // ignored
                }
            }
            try
            {
                if (Channel == null)
                {
                    Channel = Guild.GetTextChannel(Repeater.ChannelId);
                }

                if (Channel != null)
                {
                    oldMsg = await Channel.SendMessageAsync(toSend.SanitizeMentions()).ConfigureAwait(false);
                }
            }
            catch (HttpException ex) when(ex.HttpCode == System.Net.HttpStatusCode.Forbidden)
            {
                _log.Warn("Missing permissions. Repeater stopped. ChannelId : {0}", Channel?.Id);
                return;
            }
            catch (HttpException ex) when(ex.HttpCode == System.Net.HttpStatusCode.NotFound)
            {
                _log.Warn("Channel not found. Repeater stopped. ChannelId : {0}", Channel?.Id);
                return;
            }
            catch (Exception ex)
            {
                _log.Warn(ex);
            }
        }
Esempio n. 8
0
        public async Task AcronymCmd()
        {
            #region Preparation
            //Stage 1
            IUserMessage msg = await Context.Channel.SendMessageAsync("Welcome to the Acronym Game! In 10 seconds i will give 6 letters for you to make an acronym (You can do this with multiple people!)");

            string acroLetters = _lib.GetRandomLetters(6);
            await Task.Delay(TimeSpan.FromSeconds(10));

            //Stage 2
            await msg.ModifyAsync(x => x.Content = $":timer: *You have 1 minute to make an acronym with the following letters!* **{acroLetters}** *(Only 10 submissions will be included)*");

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

            IUserMessage msg2 = await Context.Channel.SendMessageAsync("To submit an acronym, send your message starting with '*'. After that, just write your acronym.\nhttps://cdn.discordapp.com/attachments/412350471584481291/473955216518021130/unknown.png");

            await Task.Delay(TimeSpan.FromMinutes(1));

            await msg2.DeleteAsync();

            #endregion

            //Stage 3
            var messages = await Context.Channel.GetMessagesAsync(10).FlattenAsync();

            IMessage[] messagesObj = messages.Where(x => x.Content.StartsWith("*")).ToArray();

            //Get Message Count
            int messageCount = messagesObj.Count();
            int winnerNum    = new Random().Next(-1, messageCount + 1);
            int otherShit    = 0;
            foreach (var message in messagesObj)
            {
                if (message == null)
                {
                    continue;
                }
                if (winnerNum == otherShit)
                {
                    if (message.Author.IsBot)
                    {
                        continue;
                    }
                    await msg.ModifyAsync(x => x.Content = $"{message.Author.Mention} has won the the acronym with '{message.Content}'");
                    await ReplyAsync("Game End! Before you start another game, please delete the previous submissions, as they would be included in the next game.");

                    return;
                }
                otherShit++;
            }
        }
Esempio n. 9
0
        public async Task RunCmd(string cmd, IUser um, IUserMessage x)
        {
            (string msg, Bitmap img) = GameBotEngine.HandelCommand(cmd, um as SocketUser);

            if (msg == null && img == null)
            {
                return;
            }


            if (img == null)
            {
                await x.Channel.SendMessageAsync(msg);
            }
            else
            {
                using (var mem = new MemoryStream())
                {
                    img.Save(mem, ImageFormat.Png);
                    mem.Position = 0;
                    img.Dispose();
                    var messages = await x.Channel.GetMessagesAsync(50).FlattenAsync();

                    var map = messages.First();

                    if (map.Author.Id == _client.CurrentUser.Id && map.Attachments.Count != 0)
                    {
                        await map.DeleteAsync();
                    }
                    else
                    {
                        foreach (var m in messages)
                        {
                            if (m.Author.Id == _client.CurrentUser.Id)
                            {
                                if (m.Attachments.Count != 0)
                                {
                                    await m.DeleteAsync();
                                }
                            }
                        }
                    }

                    await x.DeleteAsync();

                    var res = await x.Channel.SendFileAsync(mem, "map.png", msg);

                    await res.AddReactionAsync(new Emoji("🌀"));
                }
            }
        }
Esempio n. 10
0
        private async Task Navigation(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            if (arg1.Id == msg.Id && !arg3.User.Value.IsBot)
            {
                int prevRecord = currRecord;
                if (arg3.Emote.Equals(new Emoji("◀")))
                {
                    if (currRecord > 0)
                    {
                        currRecord--;
                    }
                }
                else if (arg3.Emote.Equals(new Emoji("▶")))
                {
                    if (currRecord < pages.Count - 1)
                    {
                        currRecord++;
                    }
                }
                else if (arg3.Emote.Equals(new Emoji("☠")))
                {
                    pages.ForEach(x => x.Dispose());
                    pages.Clear();
                    client.ReactionAdded   -= Navigation;
                    client.ReactionRemoved -= Navigation;
                    await msg.DeleteAsync();
                }

                if (prevRecord != currRecord)
                {
                    client.ReactionAdded   -= Navigation;
                    client.ReactionRemoved -= Navigation;
                    await msg.DeleteAsync();

                    await SendMessage();
                }
            }
        }
Esempio n. 11
0
        private async Task deletePostConfirm(IUserMessage message, ISocketMessageChannel channel, SocketReaction reaction, IUser user)
        {
            var client = Service.GetRequiredService <DiscordSocketClient>();

            if (message.Author.Id != client.CurrentUser.Id)
            {
                return;
            }

            if (message.Reactions.ContainsKey(new Emoji("❌")))
            {
                await message.DeleteAsync();
            }
        }
Esempio n. 12
0
        public async Task PurgeMessages(int amount)
        {
            if (Functions.CheckPermission(Context.User.Id, Context.Channel.Id, Context.Guild.Id) == true)
            {
                IEnumerable <IMessage> messages = await Context.Channel.GetMessagesAsync(amount + 1).FlattenAsync();

                await((ITextChannel)Context.Channel).DeleteMessagesAsync(messages);
                IUserMessage botMessage = await ReplyAsync($"I deleted {amount} messages.");

                await Task.Delay(5000);

                await botMessage.DeleteAsync();
            }
        }
Esempio n. 13
0
        public async Task PurgeChat(uint amount)
        {
            IEnumerable <IMessage> messages = await Context.Channel.GetMessagesAsync((int)(amount + 1)).FlattenAsync();

            await((ITextChannel)Context.Channel).DeleteMessagesAsync(messages);

            const int delay = 5000;

            IUserMessage msg = await ReplyAsync($"{amount} adet mesaj silindi :white_check_mark:");

            await Task.Delay(delay);

            await msg.DeleteAsync();
        }
Esempio n. 14
0
 public static IMessage DeleteAfter(this IUserMessage msg, int seconds, LogCommandService logService = null)
 {
     Task.Run(async() =>
     {
         await Task.Delay(seconds * 1000).ConfigureAwait(false);
         if (logService != null)
         {
             logService.AddDeleteIgnore(msg.Id);
         }
         try { await msg.DeleteAsync().ConfigureAwait(false); }
         catch { }
     });
     return(msg);
 }
Esempio n. 15
0
            public async Task Iamnot(IUserMessage umsg, [Remainder] IRole role)
            {
                var channel   = (ITextChannel)umsg.Channel;
                var guildUser = (IGuildUser)umsg.Author;

                GuildConfig conf;
                IEnumerable <SelfAssignedRole> roles;

                using (var uow = DbHandler.UnitOfWork())
                {
                    conf  = uow.GuildConfigs.For(channel.Guild.Id);
                    roles = uow.SelfAssignedRoles.GetFromGuild(channel.Guild.Id);
                }
                SelfAssignedRole roleModel;

                if ((roleModel = roles.FirstOrDefault(r => r.RoleId == role.Id)) == null)
                {
                    await channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false);

                    return;
                }
                if (!guildUser.Roles.Contains(role))
                {
                    await channel.SendMessageAsync($":anger:You don't have {role.Name} role.").ConfigureAwait(false);

                    return;
                }
                try
                {
                    await guildUser.RemoveRolesAsync(role).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    await channel.SendMessageAsync($":anger:`I am unable to add that role to you. I can't remove roles to owners or other roles higher than my role in the role hierarchy.`").ConfigureAwait(false);

                    Console.WriteLine(ex);
                    return;
                }
                var msg = await channel.SendMessageAsync($":ok: You no longer have {role.Name} role.").ConfigureAwait(false);

                if (conf.AutoDeleteSelfAssignedRoleMessages)
                {
                    var t = Task.Run(async() =>
                    {
                        await Task.Delay(3000).ConfigureAwait(false);
                        try { await msg.DeleteAsync().ConfigureAwait(false); } catch { } // if 502 or something, i don't want bot crashing
                        try { await umsg.DeleteAsync().ConfigureAwait(false); } catch { }
                    });
                }
            }
Esempio n. 16
0
        public static async Task SendMessageAndDeleteAsync(this IMessageChannel channel, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, TimeSpan?after = null, IUserMessage alsoDelete = null)
        {
            var message = await channel.SendMessageAsync(text, isTTS, embed, options);

            _ = Task.Run(async() =>
            {
                await Task.Delay(after ?? TimeSpan.FromSeconds(5));
                await message.DeleteAsync();
                if (alsoDelete != null)
                {
                    await alsoDelete.DeleteAsync();
                }
            });
        }
        public async Task MuteAsync(IGuildUser user, string time, [Remainder] string reason = "No reason specified.") //TODO: temporary unmute, time to unmute
        {
            await user.AddRoleAsync(Context.Client.GetGuild(Context.Guild.Id).GetRole(Config.MutedRoleId));

            UserMuted?.Invoke(this, new MuteEventArgs()
            {
                OffendingUser = user, ResponsibleModerator = Context.User, Reason = reason, Time = time
            });
            IUserMessage MessageToDelete = await ReplyAsync($"User {user.Username} was muted for {time}, Reason: {reason}");

            await Task.Delay(2500);

            await MessageToDelete.DeleteAsync();
        }
Esempio n. 18
0
        public static async Task RemoveMessage(IUserMessage message, int timeInSeconds = 3)
        {
            try
            {
                var seconds = timeInSeconds * 1000;
                await Task.Delay(seconds);

                await message.DeleteAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Esempio n. 19
0
        private async void respond(IUserMessage response)
        {
            await Task.Delay(3000);

            if (response.Channel.GetMessageAsync(response.Id) != null)
            {
                try
                {
                    await response.DeleteAsync();
                }
                catch
                {}
            }
        }
Esempio n. 20
0
        public async Task <bool> RunBehavior(DiscordSocketClient client, IGuild guild, IUserMessage msg)
        {
            // maybe this message is a custom reaction
            var cr = await Task.Run(() => TryGetCustomReaction(msg)).ConfigureAwait(false);

            if (cr != null)
            {
                try
                {
                    if (_gperm.BlockedModules.Contains("ActualCustomReactions"))
                    {
                        return(true);
                    }

                    if (guild is SocketGuild sg)
                    {
                        var pc = _perms.GetCacheFor(guild.Id);
                        if (!pc.Permissions.CheckPermissions(msg, cr.Trigger, "ActualCustomReactions",
                                                             out int index))
                        {
                            if (pc.Verbose)
                            {
                                var returnMsg = _strings.GetText("trigger", guild.Id,
                                                                 "Permissions".ToLowerInvariant(),
                                                                 index + 1,
                                                                 Format.Bold(pc.Permissions[index].GetCommand(_cmd.GetPrefix(guild),
                                                                                                              (SocketGuild)guild)));
                                try { await msg.Channel.SendErrorAsync(returnMsg).ConfigureAwait(false); } catch { }
                                _log.Info(returnMsg);
                            }
                            return(true);
                        }
                    }
                    await cr.Send(msg, _client, this).ConfigureAwait(false);

                    if (cr.AutoDeleteTrigger)
                    {
                        try { await msg.DeleteAsync().ConfigureAwait(false); } catch { }
                    }
                    return(true);
                }
                catch (Exception ex)
                {
                    _log.Warn("Sending CREmbed failed");
                    _log.Warn(ex);
                }
            }
            return(false);
        }
Esempio n. 21
0
        public async Task GetWarnings([Optional] IGuildUser user)
        {
            var requestee = Context.User as SocketGuildUser;

            _user = user;
            Global.CommandExecutorId = Context.User.Id;

            using (var db = new Database())
            {
                IQueryable <WarnEntry> warnings = db.Warnings;
                IQueryable <WarnEntry> individualWarnings;

                if (user != null)
                {
                    warnings = warnings.Where(x => x.WarnedUserID == user.Id);
                }

                _total = warnings.Count();

                if (!requestee.Roles.Any(x => x.Name == "Staff"))
                {
                    individualWarnings = db.Warnings.Where(x => x.WarnedUserID == requestee.Id && !x.Decayed);
                    var totalWarnings = db.Warnings.Where(x => x.WarnedUserID == requestee.Id);

                    await ReplyAsync($"You have {individualWarnings.Count()} active out of {totalWarnings.Count()} total warnings.");

                    return;
                }

                if (_total == 0)
                {
                    await ReplyAsync("The specified user has no warnings.");

                    return;
                }

                warnings = warnings.Take(TakeAmount);

                _message = await CreateWarnList(warnings.ToArray());

                Context.Client.ReactionAdded += OnReactionAdded;
                _ = Task.Run(async() =>
                {
                    await Task.Delay(120_000);
                    Context.Client.ReactionAdded -= OnReactionAdded;
                    await _message.DeleteAsync();
                });
            }
        }
Esempio n. 22
0
            public async void respond(IUserMessage response)
            {
                await Task.Delay(3000);

                if (response.Channel.GetMessageAsync(response.Id) != null)
                {
                    //if message is deleted prior, to 3 second time, ignore error, otherwise delete message
                    try
                    {
                        await response.DeleteAsync();
                    }
                    catch
                    { }
                }
            }
Esempio n. 23
0
 private async void DeleteCurMessage()
 {
     if (curSongMessage != null)
     {
         try
         {
             await curSongMessage.DeleteAsync();
         }
         catch (Exception)
         {
             Console.WriteLine("Couldn't delete last message??");
             return;
         }
     }
 }
Esempio n. 24
0
        /// <summary>
        ///     Cancels the request. Does some basic cleanup tasks.
        /// </summary>
        /// <returns></returns>
        private async Task CancelRequest()
        {
            if (_userMessage != null)
            {
                await _context.Channel.SendMessageAsync("Request cancelled!");
            }
            else
            {
                await _context.Channel.SendMessageAsync("Interactive builder timed out!");
            }

            await _embedMessage.DeleteAsync();

            await _instructionsMessage.DeleteAsync();
        }
        public async Task Purge(int amount)
        {
            // get and delete messages
            IEnumerable <IMessage> messages = await Context.Channel.GetMessagesAsync(amount + 1).FlattenAsync();

            await((ITextChannel)Context.Channel).DeleteMessagesAsync(messages, null);

            // visual readout of howmany messages got deleted
            const int    delay = 3000;
            IUserMessage m     = await ReplyAsync($"I have deleted {amount} messages");

            await Task.Delay(delay);

            await m.DeleteAsync();
        }
Esempio n. 26
0
        public async Task <ulong> RepostRaidMessage(Raid raid)
        {
            SocketTextChannel channel = (SocketTextChannel)_client.GetChannel(raid.ChannelId);

            if (channel != null)
            {
                IUserMessage userMessage = (IUserMessage)await channel.GetMessageAsync(raid.MessageId);

                if (userMessage != null)
                {
                    await userMessage.DeleteAsync();
                }
            }
            return(await PostRaidMessageAsync(channel, raid));
        }
Esempio n. 27
0
 public async Task RemoveMessage(IUserMessage message)
 {
     if (!IsAvailable)
     {
         return;
     }
     try
     {
         await message.DeleteAsync();
     }
     catch (Exception ex)
     {
         await LogHelper.LogEx(nameof(RemoveMessage), ex, LogCat.Discord);
     }
 }
Esempio n. 28
0
        /// <summary>
        /// Builds an EmbedBuilder and sends it to the specified IUser.
        /// </summary>
        /// <param name="EmbedBuilder">The EmbedBuilder you wish to send.</param>
        /// <param name="User">The IUser you wish to send the embed to.</param>
        /// <param name="Fallback">The Fallback is the channel it will send the embed to if the user has blocked DMs.</param>
        /// <returns>A <c>Task</c> object, which can be awaited until this method completes successfully.</returns>

        public static async Task SendEmbed(this EmbedBuilder EmbedBuilder, IUser User, ITextChannel Fallback)
        {
            try {
                await User.SendMessageAsync(embed : EmbedBuilder.Build());
            } catch (HttpException) {
                IUserMessage Message = await Fallback.SendMessageAsync(User.Mention, embed : EmbedBuilder
                                                                       .WithAuthor($"Psst, {User.Username}! Please unblock me or allow direct messages from {Fallback.Guild.Name}. <3")
                                                                       .Build());

                _ = Task.Run(async() => {
                    await Task.Delay(5000);
                    await Message.DeleteAsync();
                });
            }
        }
Esempio n. 29
0
        /// <summary>Deletes target message after specified amount of time.</summary>
        public void SelfDestruct(IUserMessage message, int delaySeconds)
        {
            this.logger.Trace("({0}:{1})", nameof(delaySeconds), delaySeconds);

            Task.Run(async() =>
            {
                if (delaySeconds != 0)
                {
                    await Task.Delay(delaySeconds * 1000).ConfigureAwait(false);
                }
                await message.DeleteAsync().ConfigureAwait(false);
            });

            this.logger.Trace("(-)");
        }
Esempio n. 30
0
        public async Task PurgeChat(int amount = 0)
        {
            if (amount != 0)
            {
                IEnumerable <IMessage> messages = await Context.Channel.GetMessagesAsync(amount + 1).FlattenAsync();

                await((ITextChannel)Context.Channel).DeleteMessagesAsync(messages);
                const int    delay = 3000;
                IUserMessage m     = await ReplyAsync($"Messages purged. This message will be deleted in 3 seconds");

                await Task.Delay(delay);

                await m.DeleteAsync();
            }
        }
            public async Task Iamnot(IUserMessage umsg, [Remainder] IRole role)
            {
                var channel = (ITextChannel)umsg.Channel;
                var guildUser = (IGuildUser)umsg.Author;

                GuildConfig conf;
                IEnumerable<SelfAssignedRole> roles;
                using (var uow = DbHandler.UnitOfWork())
                {
                    conf = uow.GuildConfigs.For(channel.Guild.Id);
                    roles = uow.SelfAssignedRoles.GetFromGuild(channel.Guild.Id);
                }
                SelfAssignedRole roleModel;
                if ((roleModel = roles.FirstOrDefault(r => r.RoleId == role.Id)) == null)
                {
                    await channel.SendMessageAsync("💢 That role is not self-assignable.").ConfigureAwait(false);
                    return;
                }
                if (!guildUser.Roles.Contains(role))
                {
                    await channel.SendMessageAsync($"❎ You don't have **{role.Name}** role.").ConfigureAwait(false);
                    return;
                }
                try
                {
                    await guildUser.RemoveRolesAsync(role).ConfigureAwait(false);
                }
                catch (Exception)
                {
                    await channel.SendMessageAsync($"⚠️ I am unable to add that role to you. `I can't remove roles to owners or other roles higher than my role in the role hierarchy.`").ConfigureAwait(false);
                    return;
                }
                var msg = await channel.SendMessageAsync($"🆗 You no longer have **{role.Name}** role.").ConfigureAwait(false);

                if (conf.AutoDeleteSelfAssignedRoleMessages)
                {
                    var t = Task.Run(async () =>
                    {
                        await Task.Delay(3000).ConfigureAwait(false);
                        try { await msg.DeleteAsync().ConfigureAwait(false); } catch { } // if 502 or something, i don't want bot crashing
                        try { await umsg.DeleteAsync().ConfigureAwait(false); } catch { }
                    });
                }
            }
            public async Task Pick(IUserMessage imsg)
            {
                var channel = (ITextChannel)imsg.Channel;

                if (!channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages)
                {
                    await channel.SendMessageAsync("`I need manage channel permissions in order to process this command.`").ConfigureAwait(false);
                    return;
                }

                List<IUserMessage> msgs;

                try { await imsg.DeleteAsync().ConfigureAwait(false); } catch { }
                if (!plantedFlowers.TryRemove(channel.Id, out msgs))
                    return;

                await Task.WhenAll(msgs.Select(toDelete => toDelete.DeleteAsync())).ConfigureAwait(false);

                await CurrencyHandler.AddCurrencyAsync((IGuildUser)imsg.Author, "Picked flower(s).", msgs.Count, false).ConfigureAwait(false);
                var msg = await channel.SendMessageAsync($"**{imsg.Author.Username}** picked {msgs.Count}{Gambling.Gambling.CurrencySign}!").ConfigureAwait(false);
                var t = Task.Run(async () =>
                {
                    await Task.Delay(10000).ConfigureAwait(false);
                    try { await msg.DeleteAsync().ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); }
                });
            }