Beispiel #1
0
        public override async Task Execute(Bot bot, DiscordUser user, DiscordMessage message, string[] args)
        {
            if (args.Length < 1)
            {
                await message.RespondAsync("Please supply your emblem as an argument.\nIt should be exactly one emoji, nothing before or after.");

                return;
            }

            string emojiUTF = args[0];

            DiscordEmoji guildEmoji = Extensions.ToDiscordEmoji(emojiUTF, bot);

            if (guildEmoji == null)
            {
                await message.RespondAsync("Unknown emoji: [" + emojiUTF + "].\nEmblem could not be set.");

                return;
            }

            if (Program.game == null || Program.game.map == null)
            {
                await message.RespondAsync("Sigwar does not seem to be running.\nEmblem could not be set.");

                return;
            }

            Program.game.map.emblems.SetEmblem(user.Id, guildEmoji.ToString());

            await message.RespondAsync("Emblem set: " + guildEmoji.ToString() + ".\nPlease wait for the next curse or message update for it to refresh.");
        }
Beispiel #2
0
        public async Task AddReactionListener(ulong guildId, ulong messageId, DiscordEmoji emoji, DiscordRole role, ReactionType type)
        {
            var guild = await redis.GetAsync <Guild>(RedisKeyNaming.Guild(guildId));

            if (type == ReactionType.Message)
            {
                guild.ReactionMessages ??= new List <ReactionMessage>();

                if (guild.ReactionMessages.Any(x => x.Id != messageId))
                {
                    guild.ReactionMessages.Add(new ReactionMessage()
                    {
                        Id            = messageId,
                        ReactionRoles = new List <ReactionRole>()
                    });
                }

                guild.ReactionMessages.Single(x => x.Id == messageId).ReactionRoles.Add(new ReactionRole()
                {
                    Emoji  = emoji.ToString(),
                    RoleId = role.Id
                });

                await redis.ReplaceAsync <Guild>(RedisKeyNaming.Guild(guildId), guild);

                await Task.CompletedTask;
            }

            if (type == ReactionType.Category)
            {
                guild.ReactionCategories ??= new List <ReactionCategory>();

                if (guild.ReactionCategories.Any(x => x.Id != messageId))
                {
                    guild.ReactionCategories.Add(new ReactionCategory()
                    {
                        Id            = messageId,
                        RoleId        = ulong.MinValue,
                        ReactionRoles = new List <ReactionRole>()
                    });
                }

                guild.ReactionMessages.Single(x => x.Id == messageId).ReactionRoles.Add(new ReactionRole()
                {
                    Emoji  = emoji.ToString(),
                    RoleId = role.Id
                });

                await redis.ReplaceAsync <Guild>(RedisKeyNaming.Guild(guildId), guild);

                await Task.CompletedTask;
            }
        }
Beispiel #3
0
        public Task AddRoleToListener(ulong messageId, DiscordEmoji emoji, DiscordRole role, BaseDiscordClient client)
        {
            if (_redis.SetMembers("MessageIds").All(e => e.ToString() != messageId.ToString()))
            {
                _redis.SetAdd("MessageIds", messageId);
            }

            _redis.HashSet($"Messages:{messageId}", new[] { new HashEntry(emoji.ToString(), role.Id.ToString()) });

            if (_listener.ContainsKey(messageId.ToString()))
            {
                _listener[messageId.ToString()].Add(emoji, role.Id);

                return(Task.CompletedTask);
            }

            var dictionary = new Dictionary <DiscordEmoji, ulong>
            {
                {
                    emoji,
                    role.Id
                }
            };

            _listener.Add(messageId.ToString(), dictionary);

            return(Task.CompletedTask);
        }
        private static List <string> SortLines(List <string> notes, DiscordEmoji piracyEmoji = null)
        {
            if (notes == null || notes.Count < 2)
            {
                return(notes);
            }

            var priorityList = new List <string>(EmojiPriority);

            if (piracyEmoji != null)
            {
                priorityList.Insert(0, piracyEmoji.ToString());
            }
            return(notes
                   .Select(s =>
            {
                var prioritySymbol = s.Split(PrioritySeparator, 2)[0];
                var priority = priorityList.IndexOf(prioritySymbol);
                return new
                {
                    priority = priority == -1 ? 69 : priority,
                    line = s
                };
            })
                   .OrderBy(i => i.priority)
                   .Select(i => i.line)
                   .ToList());
        }
Beispiel #5
0
        public Task RemoveRoleFromListener(ulong messageId, DiscordEmoji emoji, BaseDiscordClient client)
        {
            if (_listener.ContainsKey(messageId.ToString()) && _listener[messageId.ToString()].ContainsKey(emoji))
            {
                _redis.HashDelete($"Messages:{messageId}", emoji.ToString());
                _listener[messageId.ToString()].Remove(emoji);

                return(Task.CompletedTask);
            }

            return(Task.CompletedTask);
        }
Beispiel #6
0
        public async Task SetRimboardEmote(CommandContext ctx, DiscordEmoji emote)
        {
            if (await Permissions.HandlePermissionsCheck(ctx))
            {
                Program.UpdateSettings(ref Program.Settings.RimboardEmoticon, new EmojiData(emote));

                await GenericResponses.SendMessageSettingChanged(
                    channel : ctx.Channel,
                    mention : ctx.Member.Mention,
                    title : @"Rimboard emoji changed",
                    valueName : @"Rimboard emoji",
                    newVal : emote.ToString());
            }
        }
Beispiel #7
0
        static int fromEmojiToTile34(DiscordEmoji emoji)
        {
            var emojiSplit = emoji.ToString().Split(':');
            var array      = TilesConverter.one_line_string_to_34_array(emojiSplit[1]);

            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] > 0)
                {
                    return(i);
                }
            }
            return(-1);
        }
        public async Task LogReactionAsync(DiscordEmoji emote, DiscordUser user, DiscordMessage message, DiscordChannel channel, bool action)
        {
            if (!this.Settings.Enabled)
            {
                return;
            }

            await this.Semaphore.WaitAsync();

            try
            {
                using (var cmd = this.Connection.CreateCommand())
                {
                    var tbl = string.Concat(this.Settings.TablePrefix, "reaction_log");

                    cmd.CommandText = string.Concat("INSERT INTO ", tbl, "(message_id, channel_id, user_id, reaction, action, action_timestamp) VALUES(@message_id, @channel_id, @user_id, @reaction, @action, @action_timestamp);");
                    cmd.Parameters.AddWithValue("message_id", NpgsqlDbType.Bigint, (long)message.Id);
                    cmd.Parameters.AddWithValue("channel_id", NpgsqlDbType.Bigint, (long)channel.Id);
                    cmd.Parameters.AddWithValue("user_id", NpgsqlDbType.Bigint, (long)user.Id);
                    cmd.Parameters.AddWithValue("reaction", NpgsqlDbType.Text, emote.ToString());
                    cmd.Parameters.AddWithValue("action", NpgsqlDbType.Boolean, action);
                    cmd.Parameters.AddWithValue("action_timestamp", NpgsqlDbType.TimestampTZ, DateTimeOffset.Now);
                    cmd.Prepare();

                    await cmd.ExecuteNonQueryAsync();
                }
            }
            catch (Exception ex)
            {
                var discord = this.MessageDiscordProperty.GetValue(message) as DiscordClient;

                if (discord != null)
                {
                    discord.DebugLogger.LogMessage(LogLevel.Error, "DEvI DB", string.Concat("An exception occured while logging message reaction: ", ex.GetType(), ": ", ex.Message), DateTime.Now);
                }
            }
            finally
            {
                this.Semaphore.Release();
            }
        }
 internal static string MessageReaction(
     ulong channelId,
     ulong messageId,
     DiscordEmoji emoji)
 => $"{MessageReactions(channelId, messageId)}/{emoji.ToString()}";
Beispiel #10
0
 public Task EmoteAsync(CommandContext ctx, DiscordEmoji emt = null)
 => ctx.RespondAsync(embed: new DiscordEmbedBuilder().WithDescription(emt?.ToString() ?? "<null>"));
Beispiel #11
0
        public async void ManageRole(DiscordMessage message, DiscordChannel channel, DiscordMember member, DiscordEmoji emoji)
        {
            var guild = await redis.GetAsync <Guild>(RedisKeyNaming.Guild(channel.GuildId));

            var reactionCategory     = guild.ReactionCategories?.FirstOrDefault(x => x.Id == message.Id);
            var reactionCategoryItem = reactionCategory?.ReactionRoles.Single(x => x.Emoji == emoji.ToString());
            var reactionMessageItem  = guild.ReactionMessages?.Single(x => x.Id == message.Id)?.ReactionRoles.Single(x => x.Emoji == emoji.ToString());

            var roleId         = ulong.MinValue;
            var categoryRoleId = ulong.MinValue;

            if (reactionCategoryItem != null)
            {
                categoryRoleId = reactionCategory.RoleId;
                roleId         = reactionCategoryItem.RoleId;
            }

            if (reactionMessageItem != null)
            {
                roleId = reactionMessageItem.RoleId;
            }

            var role         = channel.Guild.GetRole(roleId);
            var categoryRole = channel.Guild.GetRole(categoryRoleId);

            if (role != null)
            {
                if (member.Roles.Contains(role))
                {
                    this.logger.Information($"The role '{role.Name}' was revoked from '{member.GetUsertag()}' on the guild '{channel.Guild.Name}' ({channel.GuildId}).");
                    await member.RevokeRoleAsync(role);

                    await member.SendMessageAsync($"The role {Formatter.InlineCode(role.Name)} has been revoked from you on {Formatter.Bold(channel.Guild.Name)}.");
                }
                else
                {
                    this.logger.Information($"The role '{role.Name}' was granted to '{member.GetUsertag()}' on the guild '{channel.Guild.Name}' ({channel.GuildId}).");
                    await member.GrantRoleAsync(role);

                    await member.SendMessageAsync($"The role {Formatter.InlineCode(role.Name)} has been granted to you on {Formatter.Bold(channel.Guild.Name)}.");
                }

                await message.DeleteReactionAsync(emoji, member);
            }
        }
Beispiel #12
0
        public bool IsListener(ulong guildId, ulong messageId, DiscordEmoji emoji)
        {
            var guild = redis.GetAsync <Guild>(RedisKeyNaming.Guild(guildId)).Result;

            return(guild.ReactionCategories != null && guild.ReactionCategories.Any(x => x.Id == messageId && x.ReactionRoles.Any(x => x.Emoji == emoji.ToString())) ||
                   guild.ReactionMessages != null && guild.ReactionMessages.Any(x => x.Id == messageId && x.ReactionRoles.Any(x => x.Emoji == emoji.ToString())));
        }
        public async Task AdicionaCargoReactRoleAsync(CommandContext ctx, DiscordChannel canalReactRole = null, DiscordEmoji emojiServidor = null, DiscordRole cargoServidor = null, [RemainingText] string categoriaReact = null)
        {
            await ctx.TriggerTypingAsync();

            new Thread(async() =>
            {
                try
                {
                    DiscordEmbedBuilder embed = new DiscordEmbedBuilder();

                    if (canalReactRole == null || emojiServidor == null || cargoServidor == null || string.IsNullOrWhiteSpace(categoriaReact))
                    {
                        embed.WithColor(Program.Bot.Utilities.HelpCommandsColor())
                        .WithAuthor("Como executar este comando:", null, Values.infoLogo)
                        .AddField("PC/Mobile", $"{ctx.Prefix}rr cargo.add Canal[Id] Emoji Cargo[Id/Menção/Nome entre \"\"\"] Nome[Categoria]")
                        .WithFooter($"Comando requisitado pelo: {Program.Bot.Utilities.DiscordNick(ctx.Member)}", iconUrl: ctx.Member.AvatarUrl)
                        .WithTimestamp(DateTime.Now);

                        await ctx.RespondAsync(embed: embed.Build());
                        return;
                    }

                    if (string.IsNullOrWhiteSpace(emojiServidor.Url))
                    {
                        embed.WithAuthor("Emoji inválido!", null, Values.infoLogo)
                        .WithColor(Program.Bot.Utilities.RandomColorEmbed())
                        .WithDescription("Digite um emoji válido!")
                        .WithFooter($"Comando requisitado pelo: {Program.Bot.Utilities.DiscordNick(ctx.Member)}", iconUrl: ctx.Member.AvatarUrl)
                        .WithTimestamp(DateTime.Now);

                        await ctx.RespondAsync(embed: embed.Build());
                        return;
                    }

                    IMongoDatabase local = Program.Bot.LocalDB;

                    IMongoCollection <Jogos> jogos   = local.GetCollection <Jogos>(Values.Mongo.jogos);
                    IMongoCollection <Reacts> reacts = local.GetCollection <Reacts>(Values.Mongo.reacts);

                    List <Jogos> respostaJogos   = await(await jogos.FindAsync(Builders <Jogos> .Filter.Eq(x => x.idDoEmoji, emojiServidor.Id))).ToListAsync();
                    List <Reacts> respostaReacts = await(await reacts.FindAsync(Builders <Reacts> .Filter.Eq(x => x.categoria, categoriaReact))).ToListAsync();

                    if (respostaReacts.Count != 0 && respostaJogos.Count == 0)
                    {
                        DiscordMessage mensagem             = await canalReactRole.GetMessageAsync(respostaReacts.LastOrDefault().idDaMensagem);
                        DiscordEmbed embedMensagemReactRole = mensagem.Embeds.LastOrDefault();

                        DiscordEmbedBuilder builder = new DiscordEmbedBuilder(embedMensagemReactRole);

                        if (!embedMensagemReactRole.Description.Contains($"{emojiServidor.ToString()} - {cargoServidor.Name}"))
                        {
                            string descricaoEmbed     = embedMensagemReactRole.Description;
                            string novaDescricaoEmbed = descricaoEmbed += $"\n{emojiServidor.ToString()} - {cargoServidor.Name}";

                            builder.WithDescription(novaDescricaoEmbed);
                            builder.WithAuthor(builder.Author.Name, null, Values.logoUBGE);
                            builder.WithColor(builder.Color.Value);

                            await mensagem.ModifyAsync(embed: builder.Build());
                        }

                        await jogos.InsertOneAsync(new Jogos
                        {
                            nomeDaCategoria = categoriaReact,
                            idDoCargo       = cargoServidor.Id,
                            idDoEmoji       = emojiServidor.Id,
                        });

                        embed.WithAuthor("Jogo Adicionado!", null, Values.logoUBGE)
                        .WithDescription($"Categoria: \"{categoriaReact}\"\n\n" +
                                         $"Cargo do jogo: {cargoServidor.Mention}")
                        .WithThumbnailUrl(emojiServidor.Url)
                        .WithColor(Program.Bot.Utilities.RandomColorEmbed())
                        .WithFooter($"Comando requisitado pelo: {Program.Bot.Utilities.DiscordNick(ctx.Member)}", iconUrl: ctx.Member.AvatarUrl)
                        .WithTimestamp(DateTime.Now);

                        await mensagem.CreateReactionAsync(emojiServidor);
                        await ctx.RespondAsync(embed: embed.Build());
                    }
                    else if (respostaJogos.Count != 0)
                    {
                        await ctx.RespondAsync($"{ctx.Member.Mention}, este jogo já existe!");
                    }
                    else if (respostaReacts.Count == 0)
                    {
                        await ctx.RespondAsync($"{ctx.Member.Mention}, esta categoria não existe!");
                    }
                }
                catch (ArgumentException)
                {
                    await ctx.RespondAsync($"{ctx.Member.Mention}, este emoji não foi encontrado!");
                }
                catch (Exception exception)
                {
                    await Program.Bot.Logger.Error(Log.TypeError.Commands, exception);
                }
            }).Start();
        }
        public async Task RemoveCargoReactRoleAsync(CommandContext ctx, DiscordChannel canalReactRole = null, DiscordEmoji emoji = null)
        {
            await ctx.TriggerTypingAsync();

            new Thread(async() =>
            {
                try
                {
                    DiscordEmbedBuilder embed = new DiscordEmbedBuilder();

                    if (canalReactRole == null || emoji == null)
                    {
                        embed.WithColor(Program.Bot.Utilities.HelpCommandsColor())
                        .WithAuthor("Como executar este comando:", null, Values.infoLogo)
                        .AddField("PC/Mobile", $"{ctx.Prefix}rr cargo.del Canal[Id] Emoji")
                        .WithFooter($"Comando requisitado pelo: {Program.Bot.Utilities.DiscordNick(ctx.Member)}", iconUrl: ctx.Member.AvatarUrl)
                        .WithTimestamp(DateTime.Now);

                        await ctx.RespondAsync(embed: embed.Build());
                        return;
                    }

                    if (string.IsNullOrWhiteSpace(emoji.Url))
                    {
                        embed.WithAuthor("Emoji inválido!", null, Values.infoLogo)
                        .WithColor(Program.Bot.Utilities.RandomColorEmbed())
                        .WithDescription("Digite um emoji válido!")
                        .WithFooter($"Comando requisitado pelo: {Program.Bot.Utilities.DiscordNick(ctx.Member)}", iconUrl: ctx.Member.AvatarUrl)
                        .WithTimestamp(DateTime.Now);

                        await ctx.RespondAsync(embed: embed.Build());
                        return;
                    }

                    IMongoDatabase local = Program.Bot.LocalDB;

                    IMongoCollection <Jogos> jogos   = local.GetCollection <Jogos>(Values.Mongo.jogos);
                    IMongoCollection <Reacts> reacts = local.GetCollection <Reacts>(Values.Mongo.reacts);

                    FilterDefinition <Jogos> filtroJogos = Builders <Jogos> .Filter.Eq(x => x.idDoEmoji, emoji.Id);
                    List <Jogos> resultadoJogos          = await(await jogos.FindAsync(filtroJogos)).ToListAsync();

                    Jogos ultimoResultadoJogo = resultadoJogos.LastOrDefault();

                    List <Reacts> resultadoReacts = await(await reacts.FindAsync(Builders <Reacts> .Filter.Eq(x => x.categoria, ultimoResultadoJogo.nomeDaCategoria))).ToListAsync();

                    Reacts ultimoResultadoReact = resultadoReacts.LastOrDefault();

                    if (resultadoJogos.Count != 0 && resultadoReacts.Count != 0)
                    {
                        DiscordMessage mensagem             = await canalReactRole.GetMessageAsync(ultimoResultadoReact.idDaMensagem);
                        DiscordEmbed embedMensagemReactRole = mensagem.Embeds.LastOrDefault();

                        DiscordEmbedBuilder builder = new DiscordEmbedBuilder(embedMensagemReactRole);

                        DiscordRole cargoJogoEmbed = ctx.Guild.GetRole(ultimoResultadoJogo.idDoCargo);

                        IReadOnlyList <DiscordUser> MembrosReacoes = await mensagem.GetReactionsAsync(emoji);

                        string linhaMensagemEmbed = $"{emoji.ToString()} - {cargoJogoEmbed.Name}";

                        if (embedMensagemReactRole.Description.Contains(linhaMensagemEmbed))
                        {
                            string descricaoEmbed = embedMensagemReactRole.Description;

                            List <string> lista = descricaoEmbed.Split('\n').ToList();
                            lista.RemoveAt(lista.FindIndex(linha => linha.Contains(linhaMensagemEmbed)));

                            StringBuilder strEmbedFinal = new StringBuilder();

                            foreach (string linha in lista)
                            {
                                strEmbedFinal.Append($"{linha}\n");
                            }

                            builder.WithDescription(strEmbedFinal.ToString());
                            builder.WithAuthor(embedMensagemReactRole.Author.Name, null, Values.logoUBGE);
                            builder.WithColor(embedMensagemReactRole.Color.Value);

                            await mensagem.ModifyAsync(embed: builder.Build());
                        }

                        await jogos.DeleteOneAsync(filtroJogos);

                        DiscordMessage msgAguarde = await ctx.RespondAsync($"Aguarde, estou removendo as reações dos membros que está no {canalReactRole.Mention}...");

                        int i = 0;

                        foreach (DiscordUser Membro in MembrosReacoes)
                        {
                            try
                            {
                                await Task.Delay(200);

                                await mensagem.DeleteReactionAsync(emoji, Membro);
                            }
                            catch (Exception)
                            {
                                ++i;
                            }
                        }

                        await msgAguarde.DeleteAsync();

                        if (i != 0)
                        {
                            await ctx.RespondAsync($"Existem **{i}** reações que não foram removidas por que os membros saíram da {ctx.Guild.Name}, por favor, remova-as manualmente. :wink:");
                        }

                        embed.WithAuthor("Jogo removido!", null, Values.logoUBGE)
                        .WithColor(Program.Bot.Utilities.RandomColorEmbed())
                        .WithThumbnailUrl(emoji.Url)
                        .WithDescription($"O cargo: {cargoJogoEmbed.Mention} e a reação: {emoji.ToString()} foram removidos com sucesso!{(i != 0 ? $"\n\n{i} reações restantes para serem removidas manualmente." : string.Empty)}")
                        .WithFooter($"Comando requisitado pelo: {Program.Bot.Utilities.DiscordNick(ctx.Member)}", iconUrl: ctx.Member.AvatarUrl)
                        .WithTimestamp(DateTime.Now);

                        await ctx.RespondAsync(embed: embed.Build());
                    }
                    else if (resultadoReacts.Count == 0)
                    {
                        await ctx.RespondAsync($"{ctx.Member.Mention}, essa categoria não existe!");
                    }
                    else if (resultadoJogos.Count == 0)
                    {
                        await ctx.RespondAsync($"{ctx.Member.Mention}, esse jogo não existe!");
                    }
                }
                catch (ArgumentException)
                {
                    await ctx.RespondAsync($"{ctx.Member.Mention}, este emoji não foi encontrado!");
                }
                catch (Exception exception)
                {
                    await Program.Bot.Logger.Error(Log.TypeError.Commands, exception);
                }
            }).Start();
        }