Ejemplo n.º 1
0
        /// <summary>
        ///     Gets list of users from a test server and displays it in channel.
        ///     You can then kick a user from the test server based on the list.
        /// </summary>
        /// <param name="serverAddress">Server address to get users from</param>
        /// <returns></returns>
        public async Task KickPlaytestUser(string serverAddress)
        {
            string description = null;

            //Get the raw status data
            var input = await _rconService.RconCommand(serverAddress, "status");

            //Format the raw data into an array and do some cleanup
            var players = input.Replace('\r', '\0').Split('\n').Where(x => x.StartsWith("#"))
                          .Select(y => y.Trim('#').Trim()).ToList();

            //Remove the first and last index and they are a header and footer
            players.RemoveAt(0);
            players.RemoveAt(players.Count - 1);

            foreach (var player in players)
            {
                //Parse out the data from each line.
                var userId  = player.Substring(0, player.IndexOf(' '));
                var name    = Regex.Match(player, "\"([^\"]*)\"").Value.Trim('"');
                var steamId = Regex.Match(player, @"(STEAM_[\d]:[\d]:\d+)").Value;

                if (string.IsNullOrEmpty(steamId))
                {
                    steamId = "BOT";
                }

                description += $"[{userId}] **{name}** - `{steamId}`\n";
            }

            var embed = new EmbedBuilder()
                        .WithAuthor("Type ID of player to kick, or exit to cancel")
                        .WithColor(new Color(165, 55, 55)).WithDescription(description);

            var display = await _context.Channel.SendMessageAsync(embed : embed.Build());

            var choice = await _interactive.NextMessageAsync(_context, timeout : TimeSpan.FromSeconds(20));

            if (choice != null && !choice.Content.Equals("exit"))
            {
                var kickMessage = await _rconService.RconCommand(serverAddress, $"kickid {choice.Content}");

                await choice.DeleteAsync();

                embed.WithColor(new Color(55, 165, 55)).WithAuthor(kickMessage).WithDescription("");

                await display.ModifyAsync(x => x.Embed = embed.Build());

                await _log.LogMessage($"`{_context.User.Username}` kicked a user from a playtest.```{kickMessage}```");

                return;
            }

            await display.DeleteAsync();

            await choice.DeleteAsync();
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     Entry point for moderation staff to work with playtest requests.
        /// </summary>
        /// <param name="display">The embed message to attach to for displaying updates</param>
        /// <returns></returns>
        public async Task SchedulePlaytestAsync(IUserMessage display)
        {
            var playtestRequests = DatabaseUtil.GetAllPlaytestRequests().ToList();

            _embedMessage = display;

            //If there are no requests, don't enter interactive mode. Just return
            if (playtestRequests.Count == 0)
            {
                return;
            }

            await _embedMessage.ModifyAsync(x => x.Content = "Type `exit` to abort at any time.");

            _instructionsMessage = await _context.Channel.SendMessageAsync("Type the ID of the playtest to schedule.");

            //Finds the correct playtest request to work with.
            var id = 0;

            while (true)
            {
                _userMessage = await _interactive.NextMessageAsync(_context);

                if (_userMessage == null ||
                    _userMessage.Content.Equals("exit", StringComparison.OrdinalIgnoreCase))
                {
                    await CancelRequest();

                    return;
                }

                if (int.TryParse(_userMessage.Content, out id) && id >= 0 && id < playtestRequests.Count)
                {
                    break;
                }

                await _userMessage.DeleteAsync();
            }

            //Set the request based on the chosen request.
            _testRequest = playtestRequests[id];

            await ConfirmSchedule();
        }
Ejemplo n.º 3
0
        public async Task Challenge([Remainder] string message)
        {
            SocketUser u1 = Context.Message.Author;
            Player     p1 = await database.FindPlayer(Context.Message.Author.Id);

            if (p1 == null)
            {
                await Context.Channel.SendMessageAsync("You are not a member of the Kipo's tamagotchi club.\n" +
                                                       "You can join by choosing your first pet, try +help starters");

                return;
            }

            SocketUser u2 = Helpers.extractUser(Context, message);
            Player     p2 = await database.FindPlayer(u2.Id);

            if (p2 == null)
            {
                await Context.Channel.SendMessageAsync("Your enemy is not a member of the Kipo's tamagotchi club.");

                return;
            }

            await Context.Channel.SendMessageAsync($"Hey, {u2.Mention}! Wanna fight with {Context.Message.Author.Mention}?\n" +
                                                   $"Type +accept in chat and let's see what happens! Remember you fight with your active pet.");

            SocketMessage response = await interaction.NextMessageAsync(Context, new EnsureFromUserCriterion(u2));

            if (response.Content == "+accept")
            {
                await Context.Channel.SendMessageAsync($"Friendly Pet vs Pet competition has started!\n" +
                                                       $"Tell your pet what to do when it's your turn by typing one of pet's abilities' name!\n" +
                                                       $"Your pets will be healed after the battle for free! We got vets ready to help so don't worry :3 " +
                                                       $"{p1.active.name} vs {p2.active.name}");

                await new PvPLogic(interaction).StartPvP(Context, p1, p2, u1, u2);
            }
            else
            {
                await Context.Channel.SendMessageAsync($"Challenge declined or ignored!");
            }
        }
Ejemplo n.º 4
0
        public async Task Marry(DiscordGuildUser user)
        {
            await ReplyEmbed(
                $"{Formatter.UsernameDiscrim(user.GuildUser)}, do you want to marry {Formatter.UsernameDiscrim(Context.User)}?",
                Purple, "💍");

            var criteria =
                InteractiveServiceExtensions.CreateEnsureFromUserInChannelCriteria(user.GuildUser.Id,
                                                                                   Context.Channel.Id);
            var resp = await _interactiveService.NextMessageAsync(Context, criteria, TimeSpan.FromSeconds(45)).ConfigureAwait(false);

            if (resp == null)
            {
                await ReplyFailureEmbed($"{Formatter.UsernameDiscrim(user.GuildUser)} didn't answer in time >.<");

                return;
            }

            if (!InteractiveServiceExtensions.StringContainsYes(resp.Content))
            {
                await ReplyFailureEmbed($"{Formatter.UsernameDiscrim(user.GuildUser)} didn't answer with a yes ˚‧º·(˚ ˃̣̣̥᷄⌓˂̣̣̥᷅ )‧º·˚");

                return;
            }

            var res = await _marriageRepo.TryAddMarriage(Context.User.Id, user.GuildUser.Id);

            if (!res)
            {
                await ReplyFailureEmbed(res.Err().Message);

                return;
            }
            var eb = new EmbedBuilder()
            {
                Color    = Purple,
                Title    = "💑 You are now married",
                ImageUrl = "https://media.giphy.com/media/iQ5rGja9wWB9K/giphy.gif"
            };

            await ReplyEmbed(eb);
        }
Ejemplo n.º 5
0
        public async Task <Ability> ChooseAbility(SocketCommandContext ctx, Pet pet, SocketUser u)
        {
            await ctx.Channel.SendMessageAsync($"It's {pet.name} turn | Choose ability");

            SocketMessage response = await interaction.NextMessageAsync(ctx, new EnsureFromUserCriterion(u));

            if (response == null)
            {
                await ctx.Channel.SendMessageAsync($"Ability not found or you were thinking too long! Your pet will decide on its own!");

                return(pet.abilities[new Random().Next(pet.abilities.Count)]);
            }

            Ability ability = await FindAbility(response.Content, pet);

            if (ability == null)
            {
                await ctx.Channel.SendMessageAsync($"Ability not found or you were thinking too long! Your pet will decide on its own!");

                return(pet.abilities[new Random().Next(pet.abilities.Count)]);
            }

            return(ability);
        }
Ejemplo n.º 6
0
        public async Task RemoveReminder()
        {
            var remsOption = await _remindRepo.GetUserReminders(Context.User.Id).ConfigureAwait(false);

            if (!remsOption)
            {
                await ReplyFailureEmbed("You don't have any reminders.");

                return;
            }

            var eb = new EmbedBuilder()
            {
                Color        = Purple,
                ThumbnailUrl = Context.User.GetAvatarUrl() ?? Context.User.GetDefaultAvatarUrl(),
                Title        = "⏰ Remove a Reminder",
                Description  = "Answer with a number indicating the ID of the reminder you'd like to remove.",
                Footer       = RequestedByMe()
            };

            var rems = ~remsOption;

            rems.Sort((r1, r2) => r1.DueDateUtc.CompareTo(r2.DueDateUtc));

            for (int i = 0; i < rems.Count; i++)
            {
                var rem      = rems[i];
                var remindIn = rem.DueDateUtc.Subtract(DateTime.UtcNow);
                int num      = i + 1;
                eb.AddField(x =>
                {
                    x.IsInline = false;
                    x.Name     =
                        $"**{num.ToString()}#** Due in {remindIn.Humanize(minUnit: TimeUnit.Second, maxUnit: TimeUnit.Year, precision: 4)}";
                    x.Value = $"{rem.Message}\n_On {rem.DueDateUtc.Date.ToString("dd/MM/yyyy")}_";
                });
            }

            await ReplyEmbed(eb);

            var criteria = InteractiveServiceExtensions.CreateEnsureFromUserInChannelCriteria(Context.User.Id, Context.Channel.Id);
            var resp     = await _interactiveService.NextMessageAsync(Context, criteria, TimeSpan.FromSeconds(45));

            if (resp == null)
            {
                await ReplyFailureEmbed("Failed to answer in time >.<");

                return;
            }

            if (!int.TryParse(resp.Content, out var removeId))
            {
                await ReplyFailureEmbed("Please respond with the ID of the reminder to remove e.g. `1` or `7`.");

                return;
            }
            removeId--;
            if (removeId < 0 || removeId >= rems.Count)
            {
                await ReplyFailureEmbed($"Not a valid ID! Please choose a reminder between 1 and {rems.Count.ToString()}");

                return;
            }

            await _remindRepo.RemoveReminder(rems[removeId].Id);

            await ReplySuccessEmbed("Successfully removed reminder.");
        }
Ejemplo n.º 7
0
        public async Task GetImdb(SocketCommandContext context, string target)
        {
            try
            {
                await context.Channel.TriggerTypingAsync();

                var movieSimple = await TheMovieDbProvider.FindMovie(target);
                
                if(movieSimple == null || movieSimple.Length < 1)
                {
                    await context.Channel.SendMessageAsync("", embed:Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Couldn't find movie/series"));
                    return;
                }

                int index;
                
                if (movieSimple.Length > 1)
                {
                    string choose = "";
                    var ebC = new EmbedBuilder()
                    {
                        Color = Utility.PurpleEmbed,
                        Title = "Enter the Index of the Movie you want more info about."
                    };
                    int count = 1;
                    foreach (var movie in movieSimple)
                    {   
                        choose += $"**{count}.** {movie.title} ({(movie.release_date.Length > 4 ?  movie.release_date.Remove(4) : (string.IsNullOrWhiteSpace(movie.release_date)? "NoDate": movie.release_date))})\n";
                        count++;
                    }
                    ebC.Description = choose;
                    var msg = await context.Channel.SendMessageAsync("", embed: ebC);
                    var response =
                        await _interactive.NextMessageAsync(context, true, true, TimeSpan.FromSeconds(45));
                    await msg.DeleteAsync();
                    if (response == null)
                    {
                        await context.Channel.SendMessageAsync("", embed:Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"{Utility.GiveUsernameDiscrimComb(context.User)} didn't answer in time (≧д≦ヾ)"));
                        return;
                    }
                    if (!Int32.TryParse(response.Content, out index))
                    {
                        await context.Channel.SendMessageAsync("", embed:
                            Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Only send the Index!"));
                        return;
                    }
                    if (index > (movieSimple.Length) || index < 1)
                    {
                        await context.Channel.SendMessageAsync("", embed:
                            Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Invalid Index!"));
                        return;
                    }
                }
                else
                {
                    index = 1;
                }                
                var finalMovie = TheMovieDbProvider.FindFinalMovie(movieSimple[index-1].id.ToString()).Result;
                
                

                var eb = finalMovie.GetEmbed();
                eb.WithFooter(Utility.RequestedBy(context.User));
                await context.Channel.SendMessageAsync("", embed: eb);

            }
            catch (Exception)
            {
                await context.Channel.SendMessageAsync("", embed:Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Couldn't find TheMovieDb entry."));
            }
        }
Ejemplo n.º 8
0
        public async Task Guess(int x)
        {
            await ReplyAsync("Kipo thinking of a number between 1 to " + x + " try to guess ");

            int    parseResult;
            Random rnd         = new Random();
            int    num         = rnd.Next(1, x + 1);
            int    playertries = 3;
            bool   end         = true;

            while (end == true)
            {
                playertries--;
                SocketMessage answer = await interaction.NextMessageAsync(Context);

                if (answer == null)
                {
                    await ReplyAsync("You didn't pick a number before the timeout");

                    return;
                }
                bool result = Int32.TryParse(answer.Content, out parseResult);

                if (result == false)
                {
                    await Context.Channel.SendMessageAsync("Your guess has to be a number");

                    return;
                }

                if (result == true)
                {
                    if (num > parseResult)
                    {
                        await Context.Channel.SendMessageAsync("Kipo is thinking of a higher number~");
                    }

                    else if (num < parseResult)
                    {
                        await Context.Channel.SendMessageAsync("Kipo is thinking of a lower number~");
                    }

                    else if (playertries == 0)
                    {
                        await Context.Channel.SendMessageAsync("You lost the game :c");

                        return;
                    }
                    else if (parseResult == num)
                    {
                        await Context.Channel.SendMessageAsync("You win! CONGRATS");

                        return;
                    }
                    else
                    {
                        await ReplyAsync("Kipo is thinking of a different number try again you have " + playertries + " attemts left");
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public async Task MakeTradeOffer(SocketCommandContext context, SocketGuildUser other, int wantId, int offerId)
        {
            using (var soraContext = new SoraContext())
            {
                // check if they have ANY waifus at all
                var userdb = Utility.OnlyGetUser(context.User.Id, soraContext);
                if (userdb == null || userdb.UserWaifus.Count == 0)
                {
                    await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(
                                                               Utility.RedFailiureEmbed,
                                                               Utility.SuccessLevelEmoji[2],
                                                               "You have no waifus to trade! Open some WaifuBoxes!"
                                                               ));

                    return;
                }

                var otherdb = Utility.OnlyGetUser(other.Id, soraContext);
                if (otherdb == null || otherdb.UserWaifus.Count == 0)
                {
                    await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(
                                                               Utility.RedFailiureEmbed,
                                                               Utility.SuccessLevelEmoji[2],
                                                               $"{other.Username} has no waifus to trade!"
                                                               ));

                    return;
                }
                // check if both have the offered waifus.
                // first other
                var otherWaifu = otherdb.UserWaifus.FirstOrDefault(x => x.WaifuId == wantId);
                if (otherWaifu == null)
                {
                    await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(
                                                               Utility.RedFailiureEmbed,
                                                               Utility.SuccessLevelEmoji[2],
                                                               $"{other.Username} doesn't have that waifu!"
                                                               ));

                    return;
                }
                // now us
                var userWaifu = userdb.UserWaifus.FirstOrDefault(x => x.WaifuId == offerId);
                if (userWaifu == null)
                {
                    await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(
                                                               Utility.RedFailiureEmbed,
                                                               Utility.SuccessLevelEmoji[2],
                                                               $"You don't have that waifu to offer!"
                                                               ));

                    return;
                }
                // now ask for the trade.
                var otherW = soraContext.Waifus.FirstOrDefault(x => x.Id == wantId);
                var userW  = soraContext.Waifus.FirstOrDefault(x => x.Id == offerId);
                var eb     = new EmbedBuilder()
                {
                    Title       = "Waifu Trade Request",
                    Description = $"{context.User.Username} has requested to trade with you.",
                    Color       = Utility.PurpleEmbed,
                    Footer      = Utility.RequestedBy(context.User),
                    ImageUrl    = userW.ImageUrl
                };

                eb.AddField(x =>
                {
                    x.IsInline = true;
                    x.Name     = "User offers";
                    x.Value    = $"{userW.Name}\n{GetRarityString(userW.Rarity)}\n*ID: {userW.Id}*";
                });

                eb.AddField(x =>
                {
                    x.IsInline = true;
                    x.Name     = "User Wants";
                    x.Value    = $"{otherW.Name}\n{GetRarityString(otherW.Rarity)}\n*ID: {otherW.Id}*";
                });

                eb.AddField(x =>
                {
                    x.IsInline = false;
                    x.Name     = "Accept?";
                    x.Value    = "You can accept this trade by writing `y` and decline by writing anything else.";
                });

                await context.Channel.SendMessageAsync("", embed : eb);

                Criteria <SocketMessage> criteria = new Criteria <SocketMessage>();
                criteria.AddCriterion(new EnsureFromUserInChannel(other.Id, context.Channel.Id));

                var response = await _interactive.NextMessageAsync(context, criteria, TimeSpan.FromSeconds(45));

                if (response == null)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  $"{other.Username} didn't answer in time >.<"));

                    return;
                }

                if (!response.Content.Equals("y", StringComparison.OrdinalIgnoreCase))
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  $"{other.Username} declined the trade offer!"));

                    return;
                }

                // accepted offer
                // add waifu
                GiveWaifuToId(userdb.UserId, otherW.Id, userdb);
                GiveWaifuToId(other.Id, userW.Id, otherdb);
                // remove waifu
                userWaifu.Count--;
                bool fav1 = false;
                bool fav2 = false;
                if (userWaifu.Count == 0)
                {
                    fav1 = RemoveWaifuFromUser(userdb, userWaifu);
                }

                otherWaifu.Count--;
                if (otherWaifu.Count == 0)
                {
                    fav2 = RemoveWaifuFromUser(otherdb, otherWaifu);
                }
                // completed trade
                await soraContext.SaveChangesAsync();

                string desc = "";
                if (fav1)
                {
                    desc +=
                        $"{context.User.Username}, you traded away your favorite Waifu. It has been removed from your profile.\n";
                }
                if (fav2)
                {
                    desc +=
                        $"{other.Username}, you traded away your favorite Waifu. It has been removed from your profile.";
                }
                var eb2 = Utility.ResultFeedback(
                    Utility.GreenSuccessEmbed,
                    Utility.SuccessLevelEmoji[0],
                    $"Successfully traded {userW.Name} for {otherW.Name}."
                    );
                if (!string.IsNullOrWhiteSpace(desc))
                {
                    eb2.WithDescription(desc);
                }
                await context.Channel.SendMessageAsync("", embed : eb2);
            }
        }
Ejemplo n.º 10
0
        public async Task RemoveReminder(SocketCommandContext context)
        {
            using (var ethContext = new EthContext())
            {
                var userDb = Utility.OnlyGetUser(context.User.Id, ethContext);
                if (userDb == null || userDb.Reminders.Count == 0)
                {
                    await context.Channel.SendMessageAsync("",
                                                           embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                          "You have no reminders!"));

                    return;
                }

                var eb = new EmbedBuilder()
                {
                    Color        = Utility.PurpleEmbed,
                    Title        = "Enter index of reminder to remove",
                    ThumbnailUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar
                };
                var orderedReminders = ethContext.Reminders.Where(x => x.UserForeignId == context.User.Id).ToList();
                for (int i = 0; i < (orderedReminders.Count > 24 ? 24 : orderedReminders.Count); i++)
                {
                    eb.AddField(x =>
                    {
                        x.Name =
                            $"Reminder #{i + 1} in {ConvertTime(orderedReminders[i].Time.Subtract(DateTime.UtcNow).TotalSeconds)}";
                        x.IsInline = false;
                        x.Value    =
                            $"{(orderedReminders[i].Message.Length > 80 ? orderedReminders[i].Message.Remove(80) + "..." : orderedReminders[i].Message)}";
                    });
                }
                var msg = await context.Channel.SendMessageAsync("", embed : eb);

                //var response = await _interactive.WaitForMessage(context.User, context.Channel, TimeSpan.FromSeconds(45));

                var response = await _interactive.NextMessageAsync(context, true, true, TimeSpan.FromSeconds(45));//TODO test if this listens only to source user and source channel

                await msg.DeleteAsync();

                if (response == null)
                {
                    await context.Channel.SendMessageAsync("",
                                                           embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                          $"{Utility.GiveUsernameDiscrimComb(context.User)} didn't reply in time :<"));

                    return;
                }
                int index = 0;
                if (!Int32.TryParse(response.Content, out index))
                {
                    await context.Channel.SendMessageAsync("",
                                                           embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                          "Only add the Index!"));

                    return;
                }
                if (index > (orderedReminders.Count + 1) || index < 1)
                {
                    await context.Channel.SendMessageAsync("",
                                                           embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                          "Invalid Number"));

                    return;
                }
                index -= 1;
                ethContext.Reminders.Remove(orderedReminders[index]);
                await ethContext.SaveChangesAsync();

                ChangeToClosestInterval();
                await context.Channel.SendMessageAsync("",
                                                       embed : Utility.ResultFeedback(Utility.GreenSuccessEmbed, Utility.SuccessLevelEmoji[0],
                                                                                      "Successfully removed reminder"));
            }
        }
Ejemplo n.º 11
0
        public async Task GetInfo(SocketCommandContext context, string searchStr, AnimeType type)
        {
            await CheckAndUpdateAuth();

            var    search = System.Net.WebUtility.UrlEncode(searchStr);
            string link   = "";

            switch (type)
            {
            case AnimeType.Anime:
                link = $"{APIURL}anime/";
                break;

            case AnimeType.Char:
                link = $"{APIURL}character/";
                break;

            case AnimeType.Manga:
                link = $"{APIURL}manga/";
                break;
            }
            try
            {
                using (var http = new HttpClient())
                {
                    var resultString = await http.GetStringAsync($"{link}search/{Uri.EscapeUriString(search)}?access_token={_anilistToken}").ConfigureAwait(false);

                    var results = JArray.Parse(resultString);
                    if (!results.HasValues || results.Count == 0)
                    {
                        await context.Channel.SendMessageAsync("",
                                                               embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "I couldn't find anything. Sorry"));

                        return;
                    }
                    int index;
                    if (results.Count > 1)
                    {
                        string choose = "";
                        var    ebC    = new EmbedBuilder()
                        {
                            Color  = Utility.PurpleEmbed,
                            Title  = "Just enter the index for more info",
                            Author = new EmbedAuthorBuilder()
                            {
                                IconUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar,
                                Name    = Utility.GiveUsernameDiscrimComb(context.User)
                            }
                        };
                        for (int i = 0; i < results.Count; i++)
                        {
                            choose += $"**{i + 1}.** {((type == AnimeType.Anime || type == AnimeType.Manga) ? results[i]["title_english"] : $"{results[i]["name_first"]} {results[i]["name_last"]}")}\n";
                        }
                        ebC.Description = choose;
                        var msg = await context.Channel.SendMessageAsync("", embed : ebC);

                        var response =
                            await _interactive.NextMessageAsync(context, true, true, TimeSpan.FromSeconds(45));

                        await msg.DeleteAsync();

                        if (response == null)
                        {
                            await context.Channel.SendMessageAsync("",
                                                                   embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"{Utility.GiveUsernameDiscrimComb(context.User)} did not reply :/"));

                            return;
                        }

                        if (!Int32.TryParse(response.Content, out index))
                        {
                            await context.Channel.SendMessageAsync("",
                                                                   embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"Only send the Index!"));

                            return;
                        }
                        if (index > (results.Count) || index < 1)
                        {
                            await context.Channel.SendMessageAsync("",
                                                                   embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"Invalid Index!"));

                            return;
                        }
                    }
                    else
                    {
                        index = 1;
                    }
                    var tempObj = results[index - 1];
                    var aniData = await http.GetStringAsync($"{link}{tempObj["id"]}?access_token={_anilistToken}")
                                  .ConfigureAwait(false);

                    switch (type)
                    {
                    case AnimeType.Anime:
                        var animeData = JsonConvert.DeserializeObject <AnimeResult>(aniData);
                        await context.Channel.SendMessageAsync("",
                                                               embed : animeData.GetEmbed().WithFooter(Utility.RequestedBy(context.User)));

                        break;

                    case AnimeType.Char:
                        var charData = JsonConvert.DeserializeObject <CharacterResult>(aniData);
                        await context.Channel.SendMessageAsync("",
                                                               embed : charData.GetEmbed().WithFooter(Utility.RequestedBy(context.User)));

                        break;

                    case AnimeType.Manga:
                        var mangaData = JsonConvert.DeserializeObject <MangaResult>(aniData);
                        await context.Channel.SendMessageAsync("",
                                                               embed : mangaData.GetEmbed().WithFooter(Utility.RequestedBy(context.User)));

                        break;
                    }
                }
Ejemplo n.º 12
0
        public async Task Marry(SocketCommandContext context, SocketUser user)
        {
            //Check if its urself
            if (user.Id == context.User.Id)
            {
                await context.Channel.SendMessageAsync("", embed :
                                                       Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                              $"You can't and shouldn't marry yourself ;_;"));

                return;
            }
            using (var soraContext = new SoraContext())
            {
                var requestorDb = Utility.GetOrCreateUser(context.User.Id, soraContext);
                var askedDb     = Utility.GetOrCreateUser(user.Id, soraContext);
                int allowedMarriagesRequestor =
                    ((int)(Math.Floor((double)(ExpService.CalculateLevel(requestorDb.Exp) / 10)))) + 1;
                int allowedMarriagesAsked =
                    ((int)(Math.Floor((double)(ExpService.CalculateLevel(askedDb.Exp) / 10)))) + 1;
                //check both limits
                if (requestorDb.Marriages.Count >= allowedMarriagesRequestor)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  $"{Utility.GiveUsernameDiscrimComb(context.User)}, you already reached your marriage limit. Level up to increase it"));

                    return;
                }
                if (askedDb.Marriages.Count >= allowedMarriagesAsked)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  $"{Utility.GiveUsernameDiscrimComb(user)} already reached their marriage limit. They must level up to increase the limit")); //TODO this sounds like shit. change it

                    return;
                }
                //Check for duplicate
                if (requestorDb.Marriages.Any(x => x.PartnerId == user.Id) ||
                    askedDb.Marriages.Any(x => x.PartnerId == context.User.Id))
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  $"You cannot marry someone twice!"));

                    return;
                }
                //Proceed to ask for marriage
                var msg = await context.Channel.SendMessageAsync("",
                                                                 embed : Utility.ResultFeedback(Utility.PurpleEmbed, Utility.SuccessLevelEmoji[4],
                                                                                                $"{Utility.GiveUsernameDiscrimComb(user)}, do you want to marry {Utility.GiveUsernameDiscrimComb(context.User)}? 💍"));

                Criteria <SocketMessage> criteria = new Criteria <SocketMessage>();
                criteria.AddCriterion(new EnsureFromUserInChannel(user.Id, context.Channel.Id));

                var response = await _interactive.NextMessageAsync(context, criteria, TimeSpan.FromSeconds(45));

                if (response == null)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  $"{Utility.GiveUsernameDiscrimComb(user)} didn't answer in time >.<"));

                    return;
                }
                if ((!response.Content.Contains(" yes ", StringComparison.OrdinalIgnoreCase) &&
                     !response.Content.Contains(" yes,", StringComparison.OrdinalIgnoreCase) &&
                     !response.Content.Contains("yes ", StringComparison.OrdinalIgnoreCase) &&
                     !response.Content.Contains("yes,", StringComparison.OrdinalIgnoreCase)) &&
                    !response.Content.Equals("yes", StringComparison.OrdinalIgnoreCase))
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  $"{Utility.GiveUsernameDiscrimComb(user)} didn't answer with a yes ˚‧º·(˚ ˃̣̣̥᷄⌓˂̣̣̥᷅ )‧º·˚"));

                    return;
                }
                //Answer contains a yes
                requestorDb.Marriages.Add(new Marriage()
                {
                    PartnerId = user.Id,
                    Since     = DateTime.UtcNow
                });
                //_soraContext.SaveChangesThreadSafe();
                askedDb.Marriages.Add(new Marriage()
                {
                    PartnerId = context.User.Id,
                    Since     = DateTime.UtcNow
                });
                await soraContext.SaveChangesAsync();
            }
            await context.Channel.SendMessageAsync("", embed :
                                                   Utility.ResultFeedback(Utility.PurpleEmbed, Utility.SuccessLevelEmoji[4],
                                                                          $"You are now married 💑").WithImageUrl("https://media.giphy.com/media/iQ5rGja9wWB9K/giphy.gif"));
        }
Ejemplo n.º 13
0
        public async Task UpdateEntry(SocketCommandContext context, string shareUrl, string title, string tags)
        {
            using (var soraContext = new SoraContext())
            {
                var userDb = Utility.OnlyGetUser(context.User.Id, soraContext);
                if (userDb == null || userDb.ShareCentrals.Count == 0)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "You have no playlists"));

                    return;
                }
                var shareResult = userDb.ShareCentrals.FirstOrDefault(x => x.ShareLink == shareUrl);
                if (shareResult == null)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "No playlist found with that URL!"));

                    return;
                }

                string[] seperatedTags;
                if (tags.IndexOf(";", StringComparison.Ordinal) < 1)
                {
                    seperatedTags = new[] { tags };
                }
                else
                {
                    seperatedTags = tags.Split(";");
                }
                List <string> betterTags = new List <string>();
                foreach (var tag in seperatedTags)
                {
                    string finalTag = tag;
                    if (finalTag.Contains(";"))
                    {
                        finalTag = finalTag.Replace(";", "");
                    }
                    if (!string.IsNullOrWhiteSpace(finalTag))
                    {
                        betterTags.Add(finalTag.Trim());
                    }
                }
                if (betterTags.Count < 1)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  "Add at least one Tag!").WithDescription("Tags must be added like this: `trap;edm;chill music;other`"));

                    return;
                }
                if (betterTags.Count > 10)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  "Please dont exceed 10 tags!"));

                    return;
                }

                string joinedTags = String.Join(";", betterTags);

                var eb = new EmbedBuilder()
                {
                    Color       = Utility.BlueInfoEmbed,
                    Title       = $"{Utility.SuccessLevelEmoji[3]} Are you sure you want Update this? y/n",
                    Description = $"{shareUrl}",
                    Author      = new EmbedAuthorBuilder()
                    {
                        IconUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar,
                        Name    = Utility.GiveUsernameDiscrimComb(context.User)
                    }
                };
                eb.AddField(x =>
                {
                    x.IsInline = false;
                    x.Name     = "Title";
                    x.Value    = title;
                });
                eb.AddField(x =>
                {
                    x.IsInline = true;
                    x.Name     = "Tags";
                    x.Value    = joinedTags.Replace(";", " - ");
                });
                var msg = await context.Channel.SendMessageAsync("", embed : eb);

                var response = await _interactive.NextMessageAsync(context, true, true, TimeSpan.FromSeconds(45));

                await msg.DeleteAsync();

                if (response == null)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Didn't answer in time ;_;"));

                    return;
                }

                if (response.Content.Equals("y", StringComparison.OrdinalIgnoreCase) ||
                    response.Content.Equals("yes", StringComparison.OrdinalIgnoreCase))
                {
                    shareResult.Tags  = joinedTags;
                    shareResult.Titel = title;
                    await soraContext.SaveChangesAsync();

                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.GreenSuccessEmbed, Utility.SuccessLevelEmoji[0], $"Successfully updated playlist (ノ◕ヮ◕)ノ*:・゚✧"));
                }
                else
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Didn't answer with y or yes! Discarded changes"));
                }
            }
        }
        /// <summary>
        /// Interactively builds an embed by prompting the user.
        /// <para>
        /// Shows an embed layout guide, a preview of the embed being built, and instructions for the current prompt. The user is
        /// first prompted for an action. Then, if applicable, the user is prompted again to enter a value for the action. The
        /// builder is cancelled if it times out before an initial response is received. Otherwise, it listens indefinitely for
        /// a response.
        /// </para>
        /// <para>See <see cref="_Instructions"/> and <see cref="BuilderAction.Actions"/> for supported actions.</para>
        /// </summary>
        /// <returns>The built embed.</returns>
        public async Task <Discord.Embed> BuildAsync()
        {
            await InitAsync();

            while (true)
            {
                SocketMessage input = await _interactive.NextMessageAsync(_context);

                if (input == null)
                {
                    await _context.Channel.SendMessageAsync("```The announcement builder has timed out after 120 seconds.```");
                    await RemoveAsync();

                    return(null);
                }

                if (BuilderAction.Actions.TryGetValue(input.Content, out BuilderAction action))
                {
                    await input.DeleteAsync();

                    await _instructionsMsg.ModifyAsync(m => m.Content = action.Instructions);

                    input = await _interactive.NextMessageAsync(_context);

                    if (input == null)
                    {
                        continue;
                    }

                    // Displays an error if the callback failed and the action has an error message.
                    if (!action.Callback(input.Content, _embed) && !string.IsNullOrWhiteSpace(action.Error))
                    {
                        await _interactive.ReplyAndDeleteAsync(
                            _context,
                            $"```Input: {input.Content}\nError: {action.Error}```",
                            timeout : TimeSpan.FromSeconds(5));
                    }

                    await input.DeleteAsync();
                }
                else if (input.Content.Equals("field", StringComparison.OrdinalIgnoreCase))
                {
                    await input.DeleteAsync();
                    await HandleFieldAsync();
                }
                else if (input.Content.Equals("submit", StringComparison.OrdinalIgnoreCase))
                {
                    await input.DeleteAsync();
                    await RemoveAsync();

                    return(_embed.Build());
                }
                else if (input.Content.Equals("cancel", StringComparison.OrdinalIgnoreCase))
                {
                    await input.DeleteAsync();
                    await RemoveAsync();

                    return(null);
                }
                else
                {
                    await input.DeleteAsync();

                    await _interactive.ReplyAndDeleteAsync(
                        _context,
                        $"```Unknown action '{input.Content}'.```",
                        timeout : TimeSpan.FromSeconds(5));

                    continue;
                }

                await _previewMsg.ModifyAsync(m => m.Embed = _embed.Build());

                await _instructionsMsg.ModifyAsync(m => m.Content = _Instructions);
            }
        }