Example #1
0
        }                                                                  // not yet set for now

        public async Task RunAsync(string token)
        {
            var config = new DiscordConfiguration
            {
                Token           = token,
                TokenType       = TokenType.Bot,
                AutoReconnect   = true,
                MinimumLogLevel = LogLevel.Debug
            };

            _Client = new DiscordClient(config);
            // every client ready, guild available and client error
            _Client.Ready          += Client_OnReady;
            _Client.GuildAvailable += Client_GuildConnected;
            _Client.ClientErrored  += Client_ClientError;


            SharedData.prefixes.Add("i!"); //default prefix
            //might wanna add a interactivity here along with its config
            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = SharedData.prefixes, // for now it is default prefix can turn this to a list
                EnableDms           = true,                // so botDev can set himself as dev lmao
                EnableMentionPrefix = false,
                EnableDefaultHelp   = true,
                DmHelp = false
            };

            _Commands = _Client.UseCommandsNext(commandsConfig);
            _Commands.CommandExecuted += Command_CommandExecuted;
            _Commands.CommandErrored  += Command_CommandError;


            _Commands.RegisterCommands <IamagesCmds>();
            _Commands.RegisterCommands <UtilCmds>();
            _Commands.SetHelpFormatter <HelpFormatter>();

            var emojis = new PaginationEmojis() //emojis to be used in the pagination
            {
                Left      = DiscordEmoji.FromName(_Client, ":arrow_backward:"),
                Right     = DiscordEmoji.FromName(_Client, ":arrow_forward:"),
                SkipLeft  = null,
                SkipRight = null
            };

            _Interactivity = _Client.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehaviour = DSharpPlus.Interactivity.Enums.PaginationBehaviour.WrapAround,
                PaginationEmojis    = emojis,
                Timeout             = TimeSpan.FromSeconds(60) //increase timeout
            });

            SharedData.reportChannel = await _Client.GetChannelAsync(SharedData.reportChannelid);

            SharedData.startTime = DateTime.Now;
            //client connection to bot application on the discord api
            await _Client.ConnectAsync();

            await Task.Delay(-1); // <------ needs to re looked upon
        }
Example #2
0
        public async Task ImgSearch(CommandContext ctx, string searchTag)
        {
            var emojis = new PaginationEmojis() //emojis to be used in the pagination
            {
                Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_backward:"),
                Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_forward:"),
                SkipLeft  = null,
                SkipRight = null
            };

            IamagesAPIWrapper api = new IamagesAPIWrapper();
            var response          = api.postSearch(searchTag);

            if (response.FileIDs.Length != 0)                  // no search was found
            {
                List <Page> pages         = new List <Page>(); // paginated embeds to be sent
                var         interactivity = ctx.Client.GetInteractivity();
                int         count         = 0;
                foreach (int fileID in response.FileIDs)
                {
                    count++;
                    var imgInfo = api.getImgInfo(fileID);
                    var embed   = defaultImgEmbed(imgInfo, api);
                    embed.WithTitle($"Image #{count}/{response.FileIDs.Length}");
                    var page = new Page($"Images Found! Searching for: `{response.searchTag}`\nPress :stop_button: to stop interacting", embed);
                    pages.Add(page);
                }
                await interactivity.SendPaginatedMessageAsync(ctx.Channel, ctx.User, pages, emojis);
            }
            else
            {
                await BotServices.SendEmbedAsync(ctx, "Sorry! No Iamages were found!", "Similar descriptions were either not found or something else went wrong!", ResponseType.Warning);
            }
        }
Example #3
0
        public async Task GetQueue()
        {
            if (_ctx.Member.VoiceState == null || _ctx.Member.VoiceState.Channel == null)
            {
                await _ctx.RespondAsync("You are not in a voice channel.");

                return;
            }

            if (Connection == null)
            {
                await _ctx.RespondAsync("Lavalink is not connected.");

                return;
            }

            if (Playlist == null)
            {
                await _ctx.RespondAsync("No playlist loaded.");

                return;
            }

            var interactivity = _ctx.Client.GetInteractivity();

            var pageCount = Queue.Count / 5 + 1;

            if (Queue.Count % 5 == 0)
            {
                pageCount--;
            }

            var pages = Queue.Select(x => x.Title)
                        .Select((t, i) => new { title = t, index = i })
                        .GroupBy(x => x.index / 5)
                        .Select(page => new Page("",
                                                 new DiscordEmbedBuilder
            {
                Title       = "Playlist",
                Description = $"Now playing: {Queue.Peek().Title}\n\n{string.Join("\n", page.Select(track => $"`{track.index + 1:00}` {track.title}"))}",
                Footer      = new EmbedFooter
                {
                    Text = $"Page {page.Key + 1}/{pageCount}"
                }
            }
                                                 )).ToArray();

            var emojis = new PaginationEmojis
            {
                SkipLeft  = null,
                SkipRight = null,
                Stop      = null,
                Left      = DiscordEmoji.FromUnicode("◀"),
                Right     = DiscordEmoji.FromUnicode("▶")
            };

            await interactivity.SendPaginatedMessageAsync(_ctx.Channel, _ctx.User, pages, emojis, PaginationBehaviour.Ignore, PaginationDeletion.KeepEmojis, TimeSpan.FromMinutes(2));
        }
Example #4
0
        public async Task create(CommandContext ctx, [Description("Nome do time"), RemainingText] String nome)
        {
            List <EventoModel> eventos = new Evento().FindAll(_ => true);

            if (eventos.Count > 0)
            {
                TimeModel time = new TimeModel
                {
                    Nome      = nome,
                    LiderId   = ctx.Member.Id,
                    Jogadores = new[] { ctx.Member.Id }.ToList()
                };
                List <Page> pages = new List <Page>();
                eventos.ForEach(async e => pages.Add(new Page($"", new DiscordEmbedBuilder(await EmbedExtended.AsyncEventoEmbed(e)))));
                PaginationEmojis emojis = new PaginationEmojis
                {
                    Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                    Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
                    Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                    SkipLeft  = null,
                    SkipRight = null
                };
                var msg = await ctx.RespondAsync(embed : EmbedBase.InputEmbed($"Selecione o evento que deseja participar. Depois clique em {emojis.Stop.ToString()} para confirmar."));

                await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis, PaginationBehaviour.WrapAround, PaginationDeletion.Default, TimeSpan.FromMinutes(30));

                var lastMsg = (await ctx.Channel.GetMessagesAfterAsync(msg.Id)).ToList().FirstOrDefault(x => x.Author == msg.Author && msg.Embeds.Count > 0);
                var id      = int.Parse(lastMsg.Embeds[0].Fields.ToList().Find(x => x.Name == "Id").Value);
                var evento  = eventos.Find(x => x.Id == id);
                if (new Time().Find(x => x.EventoId == id && x.LiderId == ctx.Member.Id) != null)
                {
                    await lastMsg.DeleteAsync();

                    await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Você já possui um time nesse evento."));
                }
                else
                {
                    time.EventoId = id;
                    await lastMsg.DeleteAsync();

                    if (evento.LimiteTimes == 0 || evento.Times == null || evento.Times.Count < evento.LimiteTimes)
                    {
                        new Time().Insert(time);
                        await msg.ModifyAsync(embed : EmbedBase.OutputEmbed($"Selecionado : {evento.Nome}. Time criado."));
                    }
                    else
                    {
                        await msg.ModifyAsync(embed : EmbedBase.OutputEmbed($"Inscrições para esse evento foram fechadas. Peça uma vaga aos organizadores do evento."));
                    }
                }
            }
            else
            {
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há eventos ativos no momento. Inscrição de times foi desativada."));
            }
        }
 public TestBotPaginator(DiscordClient client, DiscordUser usr, DiscordMessage msg, List <Page> pages)
 {
     this._pages = pages;
     this._tcs   = new TaskCompletionSource <bool>();
     this._cts   = new CancellationTokenSource(TimeSpan.FromSeconds(30));
     this._cts.Token.Register(() => this._tcs.TrySetResult(true));
     this._msg    = msg;
     this._emojis = new PaginationEmojis();
     this._usr    = usr;
 }
Example #6
0
        public async Task MusicListCommandAsync(CommandContext ctx)
        {
            var conn = await this._voice.GetGuildConnection(ctx);

            if (conn is null)
            {
                await RespondBasicErrorAsync("I'm not connected to any Voice Channels!");

                return;
            }


            var    nowPlaying = conn.CurrentState.CurrentTrack;
            string data       = $":green_circle: :notes:] {nowPlaying.Title} by {nowPlaying.Author} - `{conn.CurrentState.PlaybackPosition:mm\\:ss}/{nowPlaying.Length:mm\\:ss}`";

            if (this._voice.GuildQueues.TryGetValue(ctx.Guild.Id, out var queue))
            {
                int i    = 1;
                int last = queue.Count;
                foreach (var track in queue)
                {
                    if (i == 1)
                    {
                        data += $"\n:yellow_circle: **{i}]** {track.Title} by {track.Author} - `{track.Length:mm\\:ss}`";
                    }
                    else if (i == last)
                    {
                        data += $"\n:red_circle: **{i}]** {track.Title} by {track.Author} - `{track.Length:mm\\:ss}`";
                    }
                    else
                    {
                        data += $"\n:black_circle: **{i}]** {track.Title} by {track.Author} - `{track.Length:mm\\:ss}`";
                    }

                    i++;
                }
            }

            var interact = ctx.Client.GetInteractivity();

            var pages = interact.GeneratePagesInEmbed(data, SplitType.Line, CommandModule.SuccessBase());

            var emojis = new PaginationEmojis()
            {
                Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_up_small:"),
                SkipLeft  = DiscordEmoji.FromName(ctx.Client, ":arrow_double_up:"),
                Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_down_small:"),
                SkipRight = DiscordEmoji.FromName(ctx.Client, ":arrow_double_down:"),
                Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
            };

            await interact.SendPaginatedMessageAsync(ctx.Channel, ctx.Member, pages, emojis);
        }
Example #7
0
        public async Task QueueAsync(CommandContext ctx)
        {
            var interactivity = ctx.Client.GetInteractivity();

            if (this.GuildMusic.RepeatMode == RepeatMode.Single)
            {
                var track = this.GuildMusic.NowPlaying;
                await ctx.RespondAsync($"Queue repeats {Formatter.Bold(Formatter.Sanitize(track.Track.Title))} by {Formatter.Bold(Formatter.Sanitize(track.Track.Author))}.");

                return;
            }

            var pageCount = this.GuildMusic.Queue.Count / 10 + 1;

            if (this.GuildMusic.Queue.Count % 10 == 0)
            {
                pageCount--;
            }
            var pages = this.GuildMusic.Queue.Select(x => x.ToTrackString())
                        .Select((s, i) => new { str = s, index = i })
                        .GroupBy(x => x.index / 10)
                        .Select(xg => new Page($"Now playing: {this.GuildMusic.NowPlaying.ToTrackString()}\n\n{string.Join("\n", xg.Select(xa => $"`{xa.index + 1:00}` {xa.str}"))}\n\n{(this.GuildMusic.RepeatMode == RepeatMode.All ? "The entire queue is repeated.\n\n" : "")}Page {xg.Key + 1}/{pageCount}", null))
                        .ToArray();

            var trk = this.GuildMusic.NowPlaying;

            if (!pages.Any())
            {
                if (trk.Track?.TrackString == null)
                {
                    await ctx.RespondAsync("Queue is empty!");
                }
                else
                {
                    await ctx.RespondAsync($"Now playing: {this.GuildMusic.NowPlaying.ToTrackString()}");
                }

                return;
            }

            var ems = new PaginationEmojis
            {
                SkipLeft  = null,
                SkipRight = null,
                Stop      = DiscordEmoji.FromUnicode("⏹"),
                Left      = DiscordEmoji.FromUnicode("◀"),
                Right     = DiscordEmoji.FromUnicode("▶")
            };
            await interactivity.SendPaginatedMessageAsync(ctx.Channel, ctx.User, pages, ems, PaginationBehaviour.Ignore, PaginationDeletion.KeepEmojis, TimeSpan.FromMinutes(2));
        }
Example #8
0
        /// <summary>
        /// Replys with a paginated message
        /// </summary>
        /// <param name="c"></param>
        /// <param name="u"></param>
        /// <param name="pages"></param>
        /// <param name="emojis"></param>
        /// <param name="behaviour"></param>
        /// <param name="deletion"></param>
        /// <param name="timeoutoverride"></param>
        /// <returns></returns>
        public static async Task ReplyPaginatedAsync(this CommandContext ctx, IEnumerable <Page> pages,
                                                     PaginationEmojis emojis       = null,
                                                     PaginationBehaviour behaviour = PaginationBehaviour.Default,
                                                     PaginationDeletion deletion   = PaginationDeletion.Default,
                                                     TimeSpan?timeoutoverride      = null)
        {
            var m = await ctx.ReplyAsync(pages.First().Content, pages.First().Embed);

            var timeout = timeoutoverride ?? TimeSpan.FromMinutes(1);

            var ems      = emojis ?? new PaginationEmojis();
            var prequest = new KoalaBot.Interactivity.PaginationRequest(m, ctx.Member, behaviour, deletion, ems, timeout, pages.ToArray());
            await ctx.Client.GetInteractivity().WaitForCustomPaginationAsync(prequest);
        }
Example #9
0
        public async Task SimpleAsync(CommandContext ctx, [RemainingText, Description("String to analyze.")] string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentNullException(nameof(text), "You need to supply a non-null string.");
            }

            var cps = text.ToCodepoints().Select(xcp => string.Concat("`U+", xcp.Codepoint, "` (", xcp.Name, xcp.UnihanData.IsUnihan ? string.Concat(" / ", xcp.UnihanData.Definition) : "", ") - ", Formatter.Sanitize(xcp.CodepointString), " - <http://www.fileformat.info/info/unicode/char/", xcp.Codepoint, ">"));

            var pages = new List <StringBuilder>(cps.Sum(x => x.Length) / 1000 + 1);
            var sb    = new StringBuilder();
            var pn    = 1;

            foreach (var xcp in cps)
            {
                if (sb.Length + xcp.Length > 1024)
                {
                    sb.Append("\nPage: ").Append(pn++).Append(" of ");
                    pages.Add(sb);
                    sb = new StringBuilder();
                }

                sb.Append(xcp).Append("\n");
            }

            if (pn != 1)
            {
                sb.Append("\nPage: ").Append(pn).Append(" of ");
                pages.Add(sb);

                var pga = pages.Select(x => new Page(x.Append(pn).ToString(), null)).ToArray();
                var ems = new PaginationEmojis
                {
                    SkipLeft  = null,
                    SkipRight = null,
                    Stop      = DiscordEmoji.FromUnicode("⏹"),
                    Left      = DiscordEmoji.FromUnicode("◀"),
                    Right     = DiscordEmoji.FromUnicode("▶")
                };

                var interact = ctx.Client.GetInteractivity();
                await interact.SendPaginatedMessageAsync(ctx.Channel, ctx.User, pga, ems, PaginationBehaviour.Ignore, PaginationDeletion.KeepEmojis);
            }
            else
            {
                var cnt = sb.ToString();
                await ctx.RespondAsync(cnt);
            }
        }
Example #10
0
        public async Task apagar(CommandContext ctx)
        {
            List <EventoModel> eventos = new Evento().FindAll(_ => true);

            if (eventos.Count > 0)
            {
                List <Page> pages = new List <Page>();
                eventos.ForEach(async e => pages.Add(new Page($"", new DiscordEmbedBuilder(await EmbedExtended.AsyncEventoEmbed(e)))));
                PaginationEmojis emojis = new PaginationEmojis
                {
                    Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                    Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
                    Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                    SkipLeft  = null,
                    SkipRight = null
                };
                var msg = await ctx.RespondAsync(embed : EmbedBase.InputEmbed($"Selecione o evento a ser apagado, Depois clique em {emojis.Stop.ToString()} para confirmar."));

                await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis, PaginationBehaviour.WrapAround, PaginationDeletion.Default, TimeSpan.FromMinutes(30));

                var lastMsg = (await ctx.Channel.GetMessagesAfterAsync(msg.Id)).ToList().FirstOrDefault(x => x.Author == msg.Author && msg.Embeds.Count > 0);
                var id      = int.Parse(lastMsg.Embeds[0].Fields.ToList().Find(x => x.Name == "Id").Value);
                var evento  = eventos.Find(x => x.Id == id);
                await lastMsg.DeleteAsync();

                await msg.ModifyAsync(embed : EmbedBase.InputEmbed($"Selecionado : {evento.Nome}, Deseja apagar? [s/n]"));

                var input = await ctx.Message.GetNextMessageAsync();

                switch (input.Result.Content.ToLowerInvariant()[0])
                {
                case 's':
                case 'y':
                    new Evento().Delete(evento);
                    await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Evento apagado com sucesso!"));

                    break;

                case 'n':
                    await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Comando cancelado."));

                    break;
                }
            }
            else
            {
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há eventos cadastrados no sistema. Considere criar alguns!"));
            }
        }
Example #11
0
        public async Task ShowInventory(CommandContext ctx)
        {
            foreach (var player in players)
            {
                if (player.User == ctx.User)
                {
                    var pages = player.ShowInventory();
                    PaginationEmojis emojis = new PaginationEmojis();

                    await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis);

                    break;
                }
            }
        }
Example #12
0
        public async Task MyCards(CommandContext ctx, DiscordUser user = null)
        {
            if (user == null)
            {
                user = ctx.User;
            }

            List <Card> cardsCollected = DBConnector.GetUserCards(user.Id.ToString());
            var         interactivity  = ctx.Client.GetInteractivity();

            List <string> uqCards  = cardsCollected.Where(c => c.Rarity == Rarity.UQ).Select(c => $"{c.Id}: {c.Name} ({c.Amount})").ToList();
            List <string> hhqCards = cardsCollected.Where(c => c.Rarity == Rarity.HHQ).Select(c => $"{c.Id}: {c.Name} ({c.Amount})").ToList();
            List <string> hqCards  = cardsCollected.Where(c => c.Rarity == Rarity.HQ).Select(c => $"{c.Id}: {c.Name} ({c.Amount})").ToList();
            List <string> nqpCards = cardsCollected.Where(c => c.Rarity == Rarity.NQP).Select(c => $"{c.Id}: {c.Name} ({c.Amount})").ToList();
            List <string> nqCards  = cardsCollected.Where(c => c.Rarity == Rarity.NQ).Select(c => $"{c.Id}: {c.Name} ({c.Amount})").ToList();

            int totalCards = 0;

            cardsCollected.ForEach(c => totalCards += c.Amount);

            var embed = new DiscordEmbedBuilder
            {
                Title       = $"{user.Username} Cards Collected",
                Description = $"{user.Username} has collected ({cardsCollected.Count}/{GachaTable.Instance.Cards.Count}) ({totalCards} cards)",
                Color       = DiscordColor.Gold
            };

            List <DiscordEmbedBuilder> embeds = new List <DiscordEmbedBuilder>();

            embeds.AddRange(GeneratePageText(uqCards, $"**{DiscordEmoji.FromName(ctx.Client, ":UQ:")} UQ Cards ({uqCards.Count}/{GachaTable.Instance.Cards.Where(c => c.Rarity == Rarity.UQ).ToList().Count})**", embed));
            embeds.AddRange(GeneratePageText(hhqCards, $"**{DiscordEmoji.FromName(ctx.Client, ":HHQ:")} HHQ Cards ({hhqCards.Count}/{GachaTable.Instance.Cards.Where(c => c.Rarity == Rarity.HHQ).ToList().Count})**", embed));
            embeds.AddRange(GeneratePageText(hqCards, $"**{DiscordEmoji.FromName(ctx.Client, ":HQ:")} HQ Cards ({hqCards.Count}/{GachaTable.Instance.Cards.Where(c => c.Rarity == Rarity.HQ).ToList().Count})**", embed));
            embeds.AddRange(GeneratePageText(nqpCards, $"**{DiscordEmoji.FromName(ctx.Client, ":NQP:")} NQP Cards ({nqpCards.Count}/{GachaTable.Instance.Cards.Where(c => c.Rarity == Rarity.NQP).ToList().Count})**", embed));
            embeds.AddRange(GeneratePageText(nqCards, $"**{DiscordEmoji.FromName(ctx.Client, ":NQ:")} NQ Cards ({nqCards.Count}/{GachaTable.Instance.Cards.Where(c => c.Rarity == Rarity.NQ).ToList().Count})**", embed));

            Page[] pages = new Page[embeds.Count];

            for (int i = 0; i < embeds.Count; i++)
            {
                pages[i] = new Page("", embeds[i]);
            }

            PaginationEmojis paginationEmojis = GetPaginationEmojis(ctx.Client);

            await interactivity.SendPaginatedMessageAsync(ctx.Channel, ctx.User, pages, paginationEmojis, PaginationBehaviour.WrapAround, PaginationDeletion.DeleteEmojis, TimeSpan.FromMinutes(1)).ConfigureAwait(false);
        }
Example #13
0
        public async Task Cards(CommandContext ctx)
        {
            var interactivity = ctx.Client.GetInteractivity();

            List <Card> cards = GachaTable.Instance.Cards;

            var embed = new DiscordEmbedBuilder
            {
                Title = $"Cards Database ({cards.Count} cards)",
                Color = DiscordColor.Gold
            };

            try
            {
                List <string> uqCards  = cards.Where(c => c.Rarity == Rarity.UQ).Select(c => $"{c.Id}: {c.Name}").ToList();
                List <string> hhqCards = cards.Where(c => c.Rarity == Rarity.HHQ).Select(c => $"{c.Id}: {c.Name}").ToList();
                List <string> hqCards  = cards.Where(c => c.Rarity == Rarity.HQ).Select(c => $"{c.Id}: {c.Name}").ToList();
                List <string> nqpCards = cards.Where(c => c.Rarity == Rarity.NQP).Select(c => $"{c.Id}: {c.Name}").ToList();
                List <string> nqCards  = cards.Where(c => c.Rarity == Rarity.NQ).Select(c => $"{c.Id}: {c.Name}").ToList();

                List <DiscordEmbedBuilder> embeds = new List <DiscordEmbedBuilder>();

                embeds.AddRange(GeneratePageText(uqCards, $"**{DiscordEmoji.FromName(ctx.Client, ":UQ:")} UQ Cards ({uqCards.Count})**", embed));
                embeds.AddRange(GeneratePageText(hhqCards, $"**{DiscordEmoji.FromName(ctx.Client, ":HHQ:")} HHQ Cards ({hhqCards.Count})**", embed));
                embeds.AddRange(GeneratePageText(hqCards, $"**{DiscordEmoji.FromName(ctx.Client, ":HQ:")} HQ Cards ({hqCards.Count})**", embed));
                embeds.AddRange(GeneratePageText(nqpCards, $"**{DiscordEmoji.FromName(ctx.Client, ":NQP:")} NQP Cards ({nqpCards.Count})**", embed));
                embeds.AddRange(GeneratePageText(nqCards, $"**{DiscordEmoji.FromName(ctx.Client, ":NQ:")} NQ Cards ({nqCards.Count})**", embed));

                PaginationEmojis paginationEmojis = GetPaginationEmojis(ctx.Client);

                Page[] pages = new Page[embeds.Count];

                for (int i = 0; i < embeds.Count; i++)
                {
                    pages[i] = new Page("", embeds[i]);
                }

                await interactivity.SendPaginatedMessageAsync(ctx.Channel, ctx.User, pages, paginationEmojis, PaginationBehaviour.WrapAround, PaginationDeletion.DeleteEmojis, TimeSpan.FromMinutes(1)).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex}");
            }
        }
Example #14
0
        public async Task edit(CommandContext ctx, [Description("O novo nome"), RemainingText] string nome)
        {
            List <EventoModel> eventos = new Evento().FindAll(_ => true);

            if (eventos.Count > 0)
            {
                List <Page> pages = new List <Page>();
                eventos.ForEach(async x => pages.Add(new Page("", new DiscordEmbedBuilder(await EmbedExtended.AsyncEventoEmbed(x)))));
                PaginationEmojis emojis = new PaginationEmojis
                {
                    Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                    Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
                    Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                    SkipLeft  = null,
                    SkipRight = null
                };
                var msg = await ctx.RespondAsync(embed : EmbedBase.InputEmbed($"Selecione o evento que deseja adicionar o membro. Depois clique em {emojis.Stop.ToString()} para confirmar."));

                await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis, PaginationBehaviour.WrapAround, PaginationDeletion.Default, TimeSpan.FromMinutes(30));

                var lastMsg = (await ctx.Channel.GetMessagesAfterAsync(msg.Id)).ToList().FirstOrDefault(x => x.Author == msg.Author && msg.Embeds.Count > 0);
                var id      = int.Parse(lastMsg.Embeds[0].Fields.ToList().Find(x => x.Name == "Id").Value);
                var evento  = eventos.Find(x => x.Id == id);
                await lastMsg.DeleteAsync();

                List <TimeModel> times = new Time().FindAll(x => x.EventoId == id && x.LiderId == ctx.Member.Id);
                if (times.Count > 0)
                {
                    var time = times[0];
                    time.Nome = nome;
                    new Time().Update(x => x.Id == time.Id, time);
                    await msg.ModifyAsync(embed : EmbedBase.OutputEmbed($"Nome alterado para {time.Nome} com sucesso!"));
                }
                else
                {
                    await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Você não é lider de nenhum time neste evento."));
                }
            }
            else
            {
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há eventos ativos no momento. Inscrição de times foi desativada."));
            }
        }
Example #15
0
        public async Task criar(CommandContext ctx,
                                [Description("O Líder do time (Id/Menção)")] DiscordMember lider,
                                [Description("O Nome do time."), RemainingText] string nome)
        {
            List <EventoModel> eventos = new Evento().FindAll(_ => true);

            if (eventos.Count > 0)
            {
                List <Page> pages = new List <Page>();
                eventos.ForEach(async e => pages.Add(new Page($"", new DiscordEmbedBuilder(await EmbedExtended.AsyncEventoEmbed(e)))));
                PaginationEmojis emojis = new PaginationEmojis
                {
                    Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                    Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
                    Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                    SkipLeft  = null,
                    SkipRight = null
                };
                var msg = await ctx.RespondAsync(embed : EmbedBase.InputEmbed($"Selecione o evento. Depois clique em {emojis.Stop.ToString()} para confirmar."));

                await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis, PaginationBehaviour.WrapAround, PaginationDeletion.Default, TimeSpan.FromMinutes(30));

                var lastMsg = (await ctx.Channel.GetMessagesAfterAsync(msg.Id)).ToList().FirstOrDefault(x => x.Author == msg.Author && msg.Embeds.Count > 0);
                var id      = int.Parse(lastMsg.Embeds[0].Fields.ToList().Find(x => x.Name == "Id").Value);
                var evento  = eventos.Find(x => x.Id == id);
                await lastMsg.DeleteAsync();

                TimeModel time = new TimeModel();
                time.EventoId  = evento.Id;
                time.Jogadores = new List <ulong> {
                    lider.Id
                };
                time.LiderId = lider.Id;
                time.Nome    = nome;
                new Time().Insert(time);
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Time criado com sucesso!"));
            }
            else
            {
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há nenhum evento ativo no momento. Considere criar um!"));
            }
        }
Example #16
0
        /// <summary>
        /// Creates a new Pagination request
        /// </summary>
        /// <param name="message">Message to paginate</param>
        /// <param name="user">User to allow control for</param>
        /// <param name="behaviour">Behaviour during pagination</param>
        /// <param name="deletion">Behavior on pagination end</param>
        /// <param name="emojis">Emojis for this pagination object</param>
        /// <param name="timeout">Timeout time</param>
        /// <param name="pages">Pagination pages</param>
        internal PaginationRequest(DiscordMessage message, DiscordUser user, PaginationBehaviour behaviour, PaginationDeletion deletion,
                                   PaginationEmojis emojis, TimeSpan timeout, params Page[] pages)
        {
            this._tcs = new TaskCompletionSource <bool>();
            this._ct  = new CancellationTokenSource(timeout);
            this._ct.Token.Register(() => _tcs.TrySetResult(true));
            this._timeout = timeout;

            this._message = message;
            this._user    = user;

            this._deletion  = deletion;
            this._behaviour = behaviour;
            this._emojis    = emojis;

            this._pages = new List <Page>();
            foreach (var p in pages)
            {
                this._pages.Add(p);
            }
        }
Example #17
0
        public async Task PagesAsync(CommandContext ctx)
        {
            var i     = ctx.Client.GetInteractivity();
            var pages = new List <Page>
            {
                new Page()
                {
                    Content = "meme1"
                },
                new Page()
                {
                    Content = "meme2"
                },
                new Page()
                {
                    Content = "meme3"
                },
                new Page()
                {
                    Content = "meme4"
                },
                new Page()
                {
                    Content = "meme5"
                },
                new Page()
                {
                    Content = "meme6"
                }
            };

            var emojis = new PaginationEmojis(ctx.Client)
            {
                Left = DiscordEmoji.FromName(ctx.Client, ":joy:")
            };

            await i.SendPaginatedMessage(ctx.Channel, ctx.User, pages, emojis : emojis);
        }
Example #18
0
        public async Task listar(CommandContext ctx)
        {
            List <EventoModel> eventos = new Evento().FindAll(_ => true);

            if (eventos.Count > 0)
            {
                List <Page> pages = new List <Page>();
                eventos.ForEach(async e => pages.Add(new Page($"Lista de eventos ativos", new DiscordEmbedBuilder(await EmbedExtended.AsyncEventoEmbed(e)))));
                PaginationEmojis emojis = new PaginationEmojis
                {
                    Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                    Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
                    Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                    SkipLeft  = null,
                    SkipRight = null
                };
                await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis, PaginationBehaviour.WrapAround, PaginationDeletion.Default, TimeSpan.FromMinutes(30));
            }
            else
            {
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não existem eventos ativos no momento."));
            }
        }
Example #19
0
        public async Task DetailedAsync(CommandContext ctx, [RemainingText, Description("String to analyze. Up to 32 codepoints.")] string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentNullException(nameof(text), "You need to supply a non-null string.");
            }

            var cps = text.ToCodepoints().ToArray();

            if (cps.Length > 32)
            {
                throw new ArgumentException("You can only specify up to 32 codepoints.", nameof(text));
            }

            var pgs = new List <DiscordEmbedBuilder>();

            for (var i = 0; i < cps.Length; i++)
            {
                var xcp   = cps[i];
                var embed = new DiscordEmbedBuilder
                {
                    Title = string.Concat("`U+", xcp.Codepoint, "` - ", xcp.Name),
                    Color = new DiscordColor(0xD091B2),
                    // they watermark
                    //ThumbnailUrl = string.Concat("http://www.fileformat.info/info/unicode/char/", xcp.Codepoint.ToLower(), "/", SeparatorReplacementRegex.Replace(xcp.Name, "_").ToLower(), ".png"),
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = string.Concat("Page ", (i + 1).ToString("#,##0"), " of ", cps.Length.ToString("#,##0"))
                    }
                };

                if (!string.IsNullOrWhiteSpace(xcp.CodepointString))
                {
                    embed.Description = xcp.CodepointString;
                }

                embed.AddField("Unicode Block", xcp.Block.Name)
                .AddField("Unicode Category", xcp.Category.ToDescription())
                .AddField("Combining Class", xcp.CombiningClass.ToDescription())
                .AddField("Bidirectionality Class", xcp.BidirectionalClass.ToDescription())
                .AddField("Bidirectional Mirrored?", xcp.BidirectionalMirrored ? "Yes" : "No");

                if (xcp.UnihanData.IsUnihan)
                {
                    embed.AddField("Unihan", string.Concat("This is a Unihan character\nDefinition: ", xcp.UnihanData.Definition));
                }

                if (!string.IsNullOrWhiteSpace(xcp.OldUnicodeName))
                {
                    embed.AddField("Unicode 1.0 Name", xcp.OldUnicodeName);
                }

                if (xcp.Decomposition.Codepoints.Any())
                {
                    var dcps = xcp.Decomposition.Codepoints.Select(xxcp => string.Concat("`U+", xxcp.Codepoint, "` (", xxcp.Name, ") = ", xxcp.CodepointString));
                    embed.AddField("Decomposition Type", xcp.Decomposition.Type.ToDescription())
                    .AddField("Decomposes Into", string.Join("\n", dcps));
                }

                if (xcp.NumericValue != null)
                {
                    var sb = new StringBuilder();
                    if (xcp.NumericValue?.Decimal != null)
                    {
                        sb.Append("Decimal: ").Append(xcp.NumericValue?.Decimal?.ToString("#,##0")).Append("\n");
                    }

                    if (xcp.NumericValue?.Digit != null)
                    {
                        sb.Append("Digit: ").Append(xcp.NumericValue?.Digit?.ToString("#,##0")).Append("\n");
                    }

                    if (xcp.NumericValue?.Numeric != null)
                    {
                        sb.Append("Numeric: ").Append(xcp.NumericValue?.Numeric).Append("\n");
                    }

                    if (sb.Length > 0)
                    {
                        embed.AddField("Numerical Values", sb.ToString());
                    }
                }

                if (xcp.SimpleUppercaseMapping.Codepoint != null)
                {
                    var ucm = xcp.SimpleUppercaseMapping;
                    embed.AddField("Uppercase Mapping", string.Concat("`U+", ucm.Codepoint, "` (", ucm.Name, ") = ", ucm.CodepointString));
                }

                if (xcp.SimpleLowercaseMapping.Codepoint != null)
                {
                    var lcm = xcp.SimpleLowercaseMapping;
                    embed.AddField("Lowercase Mapping", string.Concat("`U+", lcm.Codepoint, "` (", lcm.Name, ") = ", lcm.CodepointString));
                }

                if (xcp.SimpleTitlecaseMapping.Codepoint != null)
                {
                    var tcm = xcp.SimpleTitlecaseMapping;
                    if (tcm.Codepoint == xcp.SimpleUppercaseMapping.Codepoint)
                    {
                        embed.AddField("Titlecase Mapping", "Same as uppercase", false);
                    }
                    else
                    {
                        embed.AddField("Titlecase Mapping", string.Concat("`U+", tcm.Codepoint, "` (", tcm.Name, ") = ", tcm.CodepointString));
                    }
                }
                else if (xcp.SimpleUppercaseMapping.Codepoint != null)
                {
                    embed.AddField("Titlecase Mapping", "Same as uppercase");
                }

                pgs.Add(embed);
            }

            if (pgs.Count == 1)
            {
                await ctx.RespondAsync(embed : pgs.First());
            }
            else
            {
                var pga = pgs.Select(x => new Page(null, x)).ToArray();
                var ems = new PaginationEmojis
                {
                    SkipLeft  = null,
                    SkipRight = null,
                    Stop      = DiscordEmoji.FromUnicode("⏹"),
                    Left      = DiscordEmoji.FromUnicode("◀"),
                    Right     = DiscordEmoji.FromUnicode("▶")
                };

                var interact = ctx.Client.GetInteractivity();
                await interact.SendPaginatedMessageAsync(ctx.Channel, ctx.User, pga, ems, PaginationBehaviour.Ignore, PaginationDeletion.KeepEmojis);
            }
        }
Example #20
0
        public async Task Shop(CommandContext ctx)
        {
            //first one reads all text from json, second parses and turns it into a C# list class called WeaponCollection, which
            //will later be used inside a foreach to access each member of the list
            var weaponJson = File.ReadAllText(@"Z:\Self Study\Programming\C#\Discord Bots\Vinex Bot\Vinex Bot\Docs\Weapon.json");
            var weapons    = JsonConvert.DeserializeObject <WeaponCollection>(weaponJson);

            var armorJson = File.ReadAllText(@"Z:\Self Study\Programming\C#\Discord Bots\Vinex Bot\Vinex Bot\Docs\Armor.json");
            var armors    = JsonConvert.DeserializeObject <ArmorCollection>(armorJson);

            //embed for GUI
            var mainEmbed = new DiscordEmbedBuilder
            {
                Title       = "Shop",
                Color       = DiscordColor.Aquamarine,
                Description = "Please make this so that a user says v.buy weapons or v.buy items and this embed just shows the categories " +
                              "that the user can choose. Add choices for filtering (v.buy cost>500) oh also," +
                              " try adding a description to each item in the future. That'll make for some good lore! "
            };
            await ctx.Channel.SendMessageAsync(embed : mainEmbed);

            var weaponsEmbed = new DiscordEmbedBuilder
            {
                Title = "Weapons",
                Color = DiscordColor.Aquamarine
            };

            foreach (var weapon in weapons.Weapons)
            {
                weaponsEmbed.AddField(weapon.Name,
                                      "Damage: " + weapon.Damage + "\n" +
                                      "Durability: " + weapon.Durability + "\n" +
                                      "Cost: " + weapon.Cost + "𝕍", true);
            }

            var armorsEmbed = new DiscordEmbedBuilder
            {
                Title = "Armors",
                Color = DiscordColor.Aquamarine
            };

            foreach (var armor in armors.Armors)
            {
                armorsEmbed.AddField(armor.Name,
                                     "Defense: " + armor.Defense + "\n" +
                                     "Durability: " + armor.Durability + "\n" +
                                     "Cost: " + armor.Cost + "𝕍", true);
            }

            //This is basically how paginated messages work and i still don't know how they work
            PaginationEmojis emojis      = new PaginationEmojis();
            List <Page>      pages       = new List <Page>();
            Page             weaponsPage = new Page("", weaponsEmbed);
            Page             armorsPage  = new Page("", armorsEmbed);

            pages.Add(weaponsPage);
            pages.Add(armorsPage);


            await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis);
        }
Example #21
0
        public async Task apagar(CommandContext ctx)
        {
            List <EventoModel> eventos = new Evento().FindAll(_ => true);

            if (eventos.Count > 0)
            {
                List <Page> pages = new List <Page>();
                eventos.ForEach(async e => pages.Add(new Page($"", new DiscordEmbedBuilder(await EmbedExtended.AsyncEventoEmbed(e)))));
                PaginationEmojis emojis = new PaginationEmojis
                {
                    Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                    Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
                    Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                    SkipLeft  = null,
                    SkipRight = null
                };
                var msg = await ctx.RespondAsync(embed : EmbedBase.InputEmbed($"Selecione o evento. Depois clique em {emojis.Stop.ToString()} para confirmar."));

                await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis, PaginationBehaviour.WrapAround, PaginationDeletion.Default, TimeSpan.FromMinutes(30));

                var lastMsg = (await ctx.Channel.GetMessagesAfterAsync(msg.Id)).ToList().FirstOrDefault(x => x.Author == msg.Author && msg.Embeds.Count > 0);
                var id      = int.Parse(lastMsg.Embeds[0].Fields.ToList().Find(x => x.Name == "Id").Value);
                var evento  = eventos.Find(x => x.Id == id);
                await lastMsg.DeleteAsync();

                if (evento.Times == null)
                {
                    await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há nenhum time neste evento."));
                }
                else
                {
                    List <TimeModel> times    = new List <TimeModel>();
                    List <string>    nomes    = new List <string>();
                    Regex            getUlong = new Regex(@"(?<!\.)\d+(?!\.)");
                    evento.Times.ForEach(x => times.Add(new Time().Find(y => y.Id == x)));
                    times.ForEach(x => nomes.Add($"{x.Id} - {x.Nome}"));
                    await msg.ModifyAsync(embed : EmbedBase.InputEmbed("Time q será apagado [Número]"));

                    var list = await ctx.RespondAsync(embed : EmbedBase.OrderedListEmbed(nomes, $"Times em {evento.Nome}:"));

                    var responce = await ctx.Message.GetNextMessageAsync();

                    if (getUlong.IsMatch(responce.Result.Content))
                    {
                        int i = int.Parse(getUlong.Match(responce.Result.Content).ToString());
                        if (times.Any(x => x.Id == i))
                        {
                            new Time().Delete(x => x.Id == i);
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Time apagado com sucesso."));
                        }
                        else
                        {
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Número inválido. Comando Cancelado."));
                        }
                    }
                }
            }
            else
            {
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há nenhum evento ativo no momento. Considere criar um!"));
            }
        }
Example #22
0
        public async Task Gacha5(CommandContext ctx)
        {
            if (DBConnector.RemoveCurrency(ctx.User.Id.ToString(), 4000))
            {
                var interactivity = ctx.Client.GetInteractivity();

                var embed = new DiscordEmbedBuilder
                {
                    Title       = "Lunae TCG",
                    Description = $"**{ctx.User.Username}**, Add a gift reaction to open your Lunae TCG 6x Lootbox! (Valid for 2mins)",
                    Url         = ctx.Client.CurrentUser.AvatarUrl,
                    ImageUrl    = "https://i.pinimg.com/originals/fd/2c/1a/fd2c1a96b654e220d09525f006482477.gif",
                    Color       = DiscordColor.Green,
                    Footer      = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "Valid for 2mins, failure to open this lootbox within 2 mins of the msg being sent the lootbox is voided."
                    }
                };

                var msg = await ctx.Channel.SendMessageAsync(embed : embed).ConfigureAwait(false);

                await msg.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":gift:")).ConfigureAwait(false);

                var message = await interactivity
                              .WaitForReactionAsync(x =>
                                                    x.Channel == ctx.Channel &&
                                                    x.User == ctx.User &&
                                                    x.Emoji == DiscordEmoji.FromName(ctx.Client, ":gift:"))
                              .ConfigureAwait(false);

                await ctx.TriggerTypingAsync().ConfigureAwait(false);

                await msg.DeleteAsync().ConfigureAwait(false);

                Page[]      pages         = new Page[6];
                List <Card> cardsObtained = new List <Card>();

                //Pull 5 cards
                for (int i = 0; i < 5; i++)
                {
                    Card card = GachaTable.Instance.GetRandomCard();

                    DiscordColor color   = DiscordColor.Black;
                    string       hqIcons = "";
                    var          hqIcon  = DiscordEmoji.FromName(ctx.Client, ":highquality:");

                    switch (card.Rarity)
                    {
                    case Rarity.UQ:
                        color   = DiscordColor.Gold;
                        hqIcons = $"{hqIcon}{hqIcon}{hqIcon}{hqIcon}{hqIcon}";
                        break;

                    case Rarity.HHQ:
                        color   = DiscordColor.Orange;
                        hqIcons = $"{hqIcon}{hqIcon}{hqIcon}{hqIcon}";
                        break;

                    case Rarity.HQ:
                        color   = DiscordColor.Purple;
                        hqIcons = $"{hqIcon}{hqIcon}{hqIcon}";
                        break;

                    case Rarity.NQP:
                        color   = DiscordColor.Green;
                        hqIcons = $"{hqIcon}{hqIcon}";
                        DBConnector.AddCurrency(ctx.User.Id.ToString(), 150);
                        break;

                    case Rarity.NQ:
                        color   = DiscordColor.Gray;
                        hqIcons = $"{hqIcon}";
                        DBConnector.AddCurrency(ctx.User.Id.ToString(), 100);
                        break;
                    }

                    var cardEmbed = new DiscordEmbedBuilder
                    {
                        Title       = $"Card {i + 1}: {DiscordEmoji.FromName(ctx.Client, $":{card.Rarity}:")} {card.Name}",
                        Description = $"**{ctx.User.Username}**, you pulled a {DiscordEmoji.FromName(ctx.Client, $":{card.Rarity}:")} {hqIcons}",
                        ImageUrl    = $"{card.Filename}",
                        Color       = color
                    };

                    cardsObtained.Add(card);

                    DBConnector.AddCard(ctx.User.Id.ToString(), card.Id);

                    pages[i + 1] = new Page("", cardEmbed);
                }

                var summeryEmbed = new DiscordEmbedBuilder
                {
                    Title       = $"Cards obtained",
                    Description = $"**{ctx.User.Username}**, you pulled: \n{string.Join("\n", cardsObtained.Select(c =>  $"{DiscordEmoji.FromName(ctx.Client, $":{c.Rarity}:")} {c.Name}").ToList())}"
                };

                pages[0] = new Page("", summeryEmbed);

                PaginationEmojis paginationEmojis = GetPaginationEmojis(ctx.Client);

                await interactivity.SendPaginatedMessageAsync(ctx.Channel, ctx.User, pages, paginationEmojis, PaginationBehaviour.WrapAround, PaginationDeletion.DeleteMessage, TimeSpan.FromMinutes(2)).ConfigureAwait(false);

                await ctx.Channel.SendMessageAsync("", false, summeryEmbed).ConfigureAwait(false);
            }
            else
            {
                await ctx.Channel.SendMessageAsync($"{ctx.User.Username}, You require 4000 {DiscordEmoji.FromName(ctx.Client, ":cookie:")} to open a Lunae TCG Crate!").ConfigureAwait(false);
            }
        }
Example #23
0
        public async Task sair(CommandContext ctx)
        {
            List <EventoModel> eventos = new Evento().FindAll(_ => true);

            if (eventos.Count > 0)
            {
                List <Page> pages = new List <Page>();
                eventos.ForEach(async e => pages.Add(new Page($"", new DiscordEmbedBuilder(await EmbedExtended.AsyncEventoEmbed(e)))));
                PaginationEmojis emojis = new PaginationEmojis
                {
                    Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                    Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
                    Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                    SkipLeft  = null,
                    SkipRight = null
                };
                var msg = await ctx.RespondAsync(embed : EmbedBase.InputEmbed($"Selecione o evento que deseja participar. Depois clique em {emojis.Stop.ToString()} para confirmar."));

                await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis, PaginationBehaviour.WrapAround, PaginationDeletion.Default, TimeSpan.FromMinutes(30));

                var lastMsg = (await ctx.Channel.GetMessagesAfterAsync(msg.Id)).ToList().FirstOrDefault(x => x.Author == msg.Author && msg.Embeds.Count > 0);
                var id      = int.Parse(lastMsg.Embeds[0].Fields.ToList().Find(x => x.Name == "Id").Value);
                var evento  = eventos.Find(x => x.Id == id);
                if (new Time().Find(x => x.EventoId == id && (x.Jogadores.Any(y => y == ctx.Member.Id) || x.Reservas.Any(y => y == ctx.Member.Id))) != null)
                {
                    var time = new Time().Find(x => x.EventoId == id && (x.Jogadores.Any(y => y == ctx.Member.Id) || x.Reservas.Any(y => y == ctx.Member.Id)));
                    await lastMsg.DeleteAsync();

                    if (time.LiderId != ctx.Member.Id)
                    {
                        await msg.ModifyAsync(embed : EmbedBase.InputEmbed($"Você deseja sair de {time.Nome}?.[s/n]"));

                        var input = await ctx.Message.GetNextMessageAsync();

                        switch (input.Result.Content.ToLowerInvariant().Trim()[0])
                        {
                        case 'y':
                        case 's':
                            if (time.Jogadores.Contains(ctx.Member.Id))
                            {
                                time.Jogadores.Remove(ctx.Member.Id);
                            }
                            if (time.Reservas.Contains(ctx.Member.Id))
                            {
                                time.Reservas.Remove(ctx.Member.Id);
                            }
                            new Time().Update(x => x.Id == time.Id, time);
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Você saiu do time com sucesso!"));

                            break;

                        default:
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Comando cancelado."));

                            break;
                        }
                    }
                    else
                    {
                        await msg.ModifyAsync(embed : EmbedBase.InputEmbed($"Você deseja **apagar** {time.Nome}?.[s/n]"));

                        var input = await ctx.Message.GetNextMessageAsync();

                        switch (input.Result.Content.ToLowerInvariant().Trim()[0])
                        {
                        case 'y':
                        case 's':
                            new Time().Delete(time);
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Time apagado com sucesso!"));

                            break;

                        default:
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Comando cancelado."));

                            break;
                        }
                    }
                }
                else
                {
                    await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Você não participa de nenhum time neste evento."));
                }
            }
            else
            {
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há eventos ativos no momento. Inscrição de times foi desativada."));
            }
        }
 /// <summary>
 /// Sends a new paginated message.
 /// </summary>
 /// <param name="channel">Target channel.</param>
 /// <param name="user">The user that'll be able to control the pages.</param>
 /// <param name="pages">A collection of <see cref="Page"/> to display.</param>
 /// <param name="emojis"></param>
 /// <param name="behaviour"></param>
 /// <param name="deletion"></param>
 /// <param name="timeoutoverride"></param>
 /// <exception cref="InvalidOperationException">Thrown if interactivity is not enabled for the client associated with the channel.</exception>
 public static Task SendPaginatedMessageAsync(this DiscordChannel channel, DiscordUser user, IEnumerable <Page> pages, PaginationEmojis emojis = null, PaginationBehaviour?behaviour = default, PaginationDeletion?deletion = default, TimeSpan?timeoutoverride = null)
 => GetInteractivity(channel).SendPaginatedMessageAsync(channel, user, pages, emojis, behaviour, deletion, timeoutoverride);
Example #25
0
        public async Task edit(CommandContext ctx)
        {
            List <EventoModel> eventos = new Evento().FindAll(_ => true);

            if (eventos.Count > 0)
            {
                List <Page> pages = new List <Page>();
                eventos.ForEach(async e => pages.Add(new Page($"", new DiscordEmbedBuilder(await EmbedExtended.AsyncEventoEmbed(e)))));
                PaginationEmojis emojis = new PaginationEmojis
                {
                    Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                    Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
                    Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                    SkipLeft  = null,
                    SkipRight = null
                };
                var msg = await ctx.RespondAsync(embed : EmbedBase.InputEmbed($"Selecione o evento a ser apagado, Depois clique em {emojis.Stop.ToString()} para confirmar."));

                await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis, PaginationBehaviour.WrapAround, PaginationDeletion.Default, TimeSpan.FromMinutes(30));

                var           lastMsg = (await ctx.Channel.GetMessagesAfterAsync(msg.Id)).ToList().FirstOrDefault(x => x.Author == msg.Author && msg.Embeds.Count > 0);
                var           id      = int.Parse(lastMsg.Embeds[0].Fields.ToList().Find(x => x.Name == "Id").Value);
                var           evento  = eventos.Find(x => x.Id == id);
                List <string> options = new List <string> {
                    "Nome", "Limite de Jogadores/time", "Limite de reservas/time", "Quantidade max. de times"
                };
                await msg.ModifyAsync(embed : EmbedBase.InputEmbed($"Selecionado : {evento.Nome}"));

                await lastMsg.ModifyAsync(embed : EmbedBase.OrderedListEmbed(options, " Selecione o que deseja editar [Número]"));

                var input = await ctx.Message.GetNextMessageAsync();

                switch (input.Result.Content.ToLowerInvariant()[0])
                {
                case '0':
                    await msg.ModifyAsync(embed : EmbedBase.InputEmbed("O novo nome:"));

                    input = await input.Result.GetNextMessageAsync();

                    evento.Nome = input.Result.Content;
                    new Evento().Update(x => x.Id == evento.Id, evento);
                    await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Nome modificado com sucesso!"));

                    break;

                case '1':
                    await msg.ModifyAsync(embed : EmbedBase.InputEmbed("O novo limite (0 para remover):"));

                    input = await input.Result.GetNextMessageAsync();

                    evento.LimiteJogadores = int.Parse(input.Result.Content);
                    new Evento().Update(x => x.Id == evento.Id, evento);
                    await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Limite de jogadores modificado com sucesso!"));

                    break;

                case '2':
                    await msg.ModifyAsync(embed : EmbedBase.InputEmbed("O novo limite (0 para remover):"));

                    input = await input.Result.GetNextMessageAsync();

                    evento.LimiteReservas = int.Parse(input.Result.Content);
                    new Evento().Update(x => x.Id == evento.Id, evento);
                    await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Limite de reservas modificado com sucesso!"));

                    break;

                case '3':
                    await msg.ModifyAsync(embed : EmbedBase.InputEmbed("O novo limite (0 para remover):"));

                    input = await input.Result.GetNextMessageAsync();

                    evento.LimiteTimes = int.Parse(input.Result.Content);
                    new Evento().Update(x => x.Id == evento.Id, evento);
                    await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Limite de times modificado com sucesso!"));

                    break;

                default:
                    await lastMsg.DeleteAsync();

                    await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Comando cancelado. Valor inválido."));

                    break;
                }
                await lastMsg.ModifyAsync(embed : await EmbedExtended.AsyncEventoEmbed(evento));
            }
            else
            {
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há eventos cadastrados no sistema. Considere criar alguns!"));
            }
        }
Example #26
0
        /// <summary>
        /// Method for configuring <see cref="InteractivityExtension"/>, accessing each configuration individually.
        /// </summary>
        /// <param name="timeout">Sets the default interactivity action timeout. Defaults to 5 minutes.</param>
        /// <param name="pollBehaviour">What to do after the poll ends. Defaults to <see cref="PollBehaviour.DeleteEmojis"/>.</param>
        /// <param name="paginationEmojis">Emojis to use for pagination. Defaults to <see langword="null"/>.</param>
        /// <param name="paginationBehaviour">How to handle pagination. Defaults to <see cref="PaginationBehaviour.WrapAround"/>.</param>
        /// <param name="paginationDeletion">How to handle pagination deletion. Defaults to <see cref="PaginationDeletion.DeleteEmojis"/>.</param>
        public void InteractivitySetup(TimeSpan?timeout = null, PollBehaviour pollBehaviour = PollBehaviour.DeleteEmojis, PaginationEmojis paginationEmojis = null,
                                       PaginationBehaviour paginationBehaviour = PaginationBehaviour.WrapAround, PaginationDeletion paginationDeletion = PaginationDeletion.DeleteEmojis)
        {
            _discordClient.IsNotNull(this.MessageErrorDiscordClientIsNull);

            _interactivity = _discordClient.UseInteractivity(new InteractivityConfiguration
            {
                Timeout             = timeout ?? TimeSpan.FromMinutes(5),
                PollBehaviour       = pollBehaviour,
                PaginationEmojis    = paginationEmojis ?? new PaginationEmojis(),
                PaginationBehaviour = paginationBehaviour,
                PaginationDeletion  = paginationDeletion
            });
        }
Example #27
0
        public async Task add(CommandContext ctx, [Description("O Membro que será adicionado (Menção/ID) ")] DiscordMember membro)
        {
            List <EventoModel> eventos = new Evento().FindAll(_ => true);

            if (eventos.Count > 0)
            {
                List <Page> pages = new List <Page>();
                eventos.ForEach(async e => pages.Add(new Page($"", new DiscordEmbedBuilder(await EmbedExtended.AsyncEventoEmbed(e)))));
                PaginationEmojis emojis = new PaginationEmojis
                {
                    Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                    Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
                    Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                    SkipLeft  = null,
                    SkipRight = null
                };
                var msg = await ctx.RespondAsync(embed : EmbedBase.InputEmbed($"Selecione o evento que deseja adicionar o membro. Depois clique em {emojis.Stop.ToString()} para confirmar."));

                await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis, PaginationBehaviour.WrapAround, PaginationDeletion.Default, TimeSpan.FromMinutes(30));

                var lastMsg = (await ctx.Channel.GetMessagesAfterAsync(msg.Id)).ToList().FirstOrDefault(x => x.Author == msg.Author && msg.Embeds.Count > 0);
                var id      = int.Parse(lastMsg.Embeds[0].Fields.ToList().Find(x => x.Name == "Id").Value);
                var evento  = eventos.Find(x => x.Id == id);
                await lastMsg.DeleteAsync();

                if (new Time().Find(x => x.EventoId == id && (x.Jogadores.Any(y => y == membro.Id) || (x.Reservas != null && x.Reservas.Any(y => y == membro.Id)))) != null)
                {
                    await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Esse membro já foi adicionado à um time."));
                }
                else
                {
                    if (new Time().Find(x => x.LiderId == ctx.Member.Id) != null)
                    {
                        var time = new Time().Find(x => x.LiderId == ctx.Member.Id && x.EventoId == evento.Id);
                        if (evento.LimiteJogadores == 0 || time.Jogadores.Count < evento.LimiteJogadores)
                        {
                            time.Jogadores.Add(membro.Id);
                            new Time().Update(x => x.Id == time.Id, time);
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Membro adicionado com sucesso!"));
                        }
                        else if (evento.LimiteJogadores != 0 && time.Reservas != null && time.Reservas.Count < evento.LimiteReservas || time.Reservas == null && evento.LimiteReservas == 0 || time.Reservas == null)
                        {
                            if (!time.Jogadores.Any(x => x == membro.Id))
                            {
                                if (time.Reservas == null)
                                {
                                    time.Reservas = new List <ulong>();
                                }
                                time.Reservas.Add(membro.Id);
                                new Time().Update(x => x.Id == time.Id, time);
                                await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Reserva adicionado com sucesso!"));
                            }
                        }
                        else
                        {
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Limite de membros atingido."));
                        }
                    }
                    else
                    {
                        await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Você não é lider de nenhum time."));
                    }
                }
            }
            else
            {
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há eventos ativos no momento. Inscrição de times foi desativada."));
            }
        }