예제 #1
0
        private Criteria <SocketMessage> GetCriteria(IMessageChannel channel)
        {
            var criteria = new Criteria <SocketMessage>();

            criteria.AddCriterion(new EnsureFromChannelCriterion(channel));
            criteria.AddCriterion(new EnsureFromUserCriterion(Context.User));
            return(criteria);
        }
예제 #2
0
        /// <summary>
        ///     Waits for the next Message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="fromSourceUser"></param>
        /// <param name="inSourceChannel"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public Task <SocketMessage> NextMessageAsync(SocketCommandContext context, bool fromSourceUser = true, bool inSourceChannel = true, TimeSpan?timeout = null)
        {
            var criterion = new Criteria <SocketMessage>();

            if (fromSourceUser)
            {
                criterion.AddCriterion(new EnsureSourceUserCriterion());
            }
            if (inSourceChannel)
            {
                criterion.AddCriterion(new EnsureSourceChannelCriterion());
            }
            return(NextMessageAsync(context, criterion, timeout));
        }
예제 #3
0
        async Task MessageUser(IUser user, IDMChannel dMChannel, ISocketMessageChannel channel, Card[] characters, Card[] attributes, Card randomAttribute)
        {
            var criterion = new Criteria <SocketMessage>();

            criterion.AddCriterion(new EnsureFromUserCriterion(user.Id));
            var response = await NextMessageAsync(criterion, TimeSpan.FromMinutes(10));

            if (response != null)
            {
                try
                {
                    string[] inputs = response.Content.Split(',');

                    Card character = characters[int.Parse(inputs[0]) - 1];
                    Card attribute = attributes[int.Parse(inputs[1]) - 1];

                    string       message = string.Format("{0} played **{1}** with attribute **{2}** and random attribute **{3}**", ((IGuildUser)user).Nickname, character, attribute, randomAttribute);
                    EmbedBuilder embed   = new EmbedBuilder();
                    embed.WithDescription(message);
                    await channel.SendMessageAsync("", false, embed.Build());
                }
                catch (Exception e)
                {
                    await dMChannel.SendMessageAsync("Invalid input");
                    await MessageUser(user, dMChannel, channel, characters, attributes, randomAttribute);
                }
            }
            else
            {
                await dMChannel.SendMessageAsync("Round has timed out");
            }
        }
        public static Criteria <SocketMessage> CreateEnsureFromUserInChannelCriteria(ulong userId, ulong channelId)
        {
            Criteria <SocketMessage> criteria = new Criteria <SocketMessage>();

            criteria.AddCriterion(new EnsureFromUserInChannel(userId, channelId));
            return(criteria);
        }
예제 #5
0
        /// <summary>
        ///     Waits for the next message in the contextual channel.
        ///     This is a long-running <see cref="Task"/>.
        /// </summary>
        /// <param name="context">The context to wait on.</param>
        /// <param name="fromSourceUser">Should the message only be from the source user.</param>
        /// <param name="inSourceChannel">Should the message only be from the source channel.</param>
        /// <param name="timeout">The timeout to abort the waiting after.</param>
        /// <param name="token">The cancellation token to observe.</param>
        /// <returns>The waited message; or null if no message was received.</returns>
        public ValueTask <SocketUserMessage> NextMessageAsync(VolteContext context,
                                                              bool fromSourceUser     = true,
                                                              bool inSourceChannel    = true,
                                                              TimeSpan?timeout        = null,
                                                              CancellationToken token = default)
        {
            var criterion = new Criteria <SocketUserMessage>();

            if (fromSourceUser)
            {
                criterion.AddCriterion(new EnsureSourceUserCriterion());
            }
            if (inSourceChannel)
            {
                criterion.AddCriterion(new EnsureSourceChannelCriterion());
            }
            return(NextMessageAsync(context, criterion, timeout, token));
        }
예제 #6
0
        public Task <IUserMessage> NewPagedReplyAsync(PaginatedMessage pager, bool fromSourceUser = true)
        {
            var criterion = new Criteria <SocketReaction>();

            if (fromSourceUser)
            {
                criterion.AddCriterion(new EnsureReactionFromSourceUserCriterion());
            }
            return(NewPagedReplyAsync(pager, criterion));
        }
예제 #7
0
        /// <summary>
        /// creates a new paginated message
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="fromSourceUser"></param>
        /// <param name="showall"></param>
        /// <param name="showindex"></param>
        /// <returns></returns>
        public Task <IUserMessage> PagedReplyAsync(PaginatedMessage pager, bool fromSourceUser = true, bool showall = false, bool showindex = false)
        {
            var criterion = new Criteria <SocketReaction>();

            if (fromSourceUser)
            {
                criterion.AddCriterion(new EnsureReactionFromSourceUserCriterion());
            }

            return(PagedReplyAsync(pager, criterion, showall, showindex));
        }
예제 #8
0
        /// <summary>
        /// Sends a message with reaction callback
        /// </summary>
        /// <param name="context"></param>
        /// <param name="callbacks"></param>
        /// <param name="fromSourceUser"></param>
        /// <returns></returns>
        public async Task <IUserMessage> SendMessageWithReactionCallbacksAsync(SocketCommandContext context, ReactionCallbackData callbacks, bool fromSourceUser = true)
        {
            var criterion = new Criteria <SocketReaction>();

            if (fromSourceUser)
            {
                criterion.AddCriterion(new EnsureReactionFromSourceUserCriterion());
            }
            var callback = new InlineReactionCallback(new InteractiveService(Discord.GetShardFor(context.Guild)), context, callbacks, criterion);
            await callback.DisplayAsync().ConfigureAwait(false);

            return(callback.Message);
        }
예제 #9
0
        public async Task <CommandResult> HistoryAsync(SocketGuildUser u, bool onlyActive = false, [IsntActionType(ActionType.None)] ActionType type = default)
        {
            try
            {
                var dbGuild = await _databaseService.GetOrCreateGuildAsync(Context.Guild);

                var history = type == default ? dbGuild.Cases.Where(x => x.TargetId == u.Id) : dbGuild.Cases.Where(x => x.TargetId == u.Id && x.ActionType == type);
                history = onlyActive ? history.Where(x => !x.Resolved) : history;

                Console.WriteLine("aaa");

                if (!history.Any())
                {
                    return(new QuiccbanFailResult(string.Format(_responseService.Get("history_no_cases"), u.ToString(), u.Mention, onlyActive ? "active " : "")));
                }


                Console.WriteLine("bbb");

                List <Embed> embeds          = new List <Embed>();
                var          historyGrouping = history.OrderByDescending(x => x.Id).Select((@case, index) => new { Case = @case, Index = index }).GroupBy(x => x.Index / 5, x => x.Case);

                foreach (var group in historyGrouping)
                {
                    embeds.Add(await _helperService.ConstructHistoryEmbedAsync(group, u));
                }

                if (embeds.Count > 1)
                {
                    var paginatedMessage = new PaginatedMessage {
                        Pages = embeds
                    };

                    var criterion = new Criteria <SocketReaction>();
                    criterion.AddCriterion(new EnsureReactionFromSourceUserCriterion());

                    await _interactiveService.SendPaginatedMessageAsync(Context, paginatedMessage, criterion);
                }
                else
                {
                    await ReplyAsync(embed : embeds.FirstOrDefault());
                }

                return(new QuiccbanSuccessResult());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(new QuiccbanSuccessResult());
            }
        }
예제 #10
0
        public async Task <IUserMessage> SendMessageWithReactionCallbacksAsync(SocketCommandContext context,
                                                                               ReactionCallbackData reactionCallbackData,
                                                                               bool fromSourceUser = true)
        {
            var criterion = new Criteria <SocketReaction>();

            if (fromSourceUser)
            {
                criterion.AddCriterion(new EnsureReactionFromSourceUserCriterion());
            }

            var callback = new InlineReactionCallback(this, context, reactionCallbackData, criterion);
            await callback.DisplayAsync().ConfigureAwait(false);

            return(callback.Message);
        }
예제 #11
0
        /// <summary>
        ///     Sends a Message with reaction callback
        /// </summary>
        /// <param name="context"></param>
        /// <param name="callbacks"></param>
        /// <param name="fromSourceUser"></param>
        /// <returns></returns>
        public async Task <IUserMessage> SendMessageWithReactionCallbacksAsync(SocketCommandContext context, ReactionCallbackData callbacks, bool fromSourceUser = true)
        {
            if (callbacks.Text == null)
            {
                throw new Exception("Input text must not be null. Use an empty string instead.");
            }

            var criterion = new Criteria <SocketReaction>();

            if (fromSourceUser)
            {
                criterion.AddCriterion(new EnsureReactionFromSourceUserCriterion());
            }
            var callback = new InlineReactionCallback(new InteractiveService(Discord.GetShardFor(context.Guild)), context, callbacks, criterion);

            await callback.DisplayAsync().ConfigureAwait(false);

            return(callback.Message);
        }
예제 #12
0
        private async void TestEF6C1C2()
        {
            Class1 c1 = new Class1();
            EntityGenerator <Class1> generatorClass1 = new EntityGenerator <Class1>();

            c1 = generatorClass1.GenerateItem();

            EntityGenerator <Class2> generatorClass2 = new EntityGenerator <Class2>();

            for (int i = 0; i < 10; i++)
            {
                c1.Addresses.Add(generatorClass2.GenerateItem());
            }

            MySQLManager <Class1> managerClass1 = new MySQLManager <Class1>(DataConnectionResource.LOCALMYSQL);

            c1 = await managerClass1.Insert(c1);

            Class1 c11 = await managerClass1.Get(c1.Id);

            //Class1 client = managerClass1.DbSetT.SqlQuery("SELECT * FROM " + Class1Schema.TABLE + " WHERE id = 1",new object[] { }).ToListAsync().Result[0];
            //Class1 client = managerClass1.DbSetT.SqlQuery("@param1, @param2, @param3",
            //    new SqlParameter("param1", "SELECT * FROM "),
            //    new SqlParameter("param2", Class1Schema.TABLE),
            //    new SqlParameter("param3", " WHERE id = 1")).FirstAsync().Result;
            //var result = await managerClass1.DbSetT.SqlQuery("SELECT " + Class1Schema.ID + ", " + Class1Schema.NAME + ", " + Class1Schema.SURNAME + ", " + Class1Schema.ADDRESS_ID +" FROM " + Class1Schema.TABLE).ToListAsync();

            //Func<Class1, Boolean> testFunction = new Func<Class1, bool>((x, y) =>
            //{
            //    if (true)
            //    {

            //        return true;
            //    }
            //    else
            //    {

            //        return false;
            //    }
            //});

            //var result1 = managerClass1.DbSetT.SqlQuery("SELECT * FROM "+ Class1Schema.TABLE + ";").AllAsync(testFunction);

            String queryString = string.Format("SELECT * FROM {0} {1} {2} {3} {4};", Class1Schema.TABLE, "WHERE", Class1Schema.NAME, "LIKE", "'%s'");

            queryString = string.Format("SELECT * FROM {0};", Class1Schema.TABLE);

            var result = await managerClass1.DbSetT.SqlQuery(queryString).ToListAsync();

            Criteria criteria = new Criteria(DbAction.SELECT, EnumString.GetStringValue(DbSelector.ALL));

            criteria.AddDbLink(Class1Schema.TABLE, DbLinks.FROM);
            criteria.AddDbLink(Class2Schema.TABLE, DbLinks.INNERJOIN, new LinkCondition(Class1Schema.PREFIX_ADDRESS_ID, Class2Schema.PREFIX_ID));
            criteria.AddCriterion(new Criterion(DbVerb.EMPTY, Class1Schema.NAME, DbOperator.LIKE, "'%s'"));
            criteria.AddCriterion(new Criterion(DbVerb.OR, Class1Schema.SURNAME, DbOperator.IN, "('RebeckaGotts', 'JesseAguas')"));

            String value   = criteria.MySQLCompute();
            var    result1 = await managerClass1.CustomQuery(criteria);


            //MySQLManager<Class2> managerClass2 = new MySQLManager<Class2>(DataConnectionResource.LOCALMYSQL);

            //Criteria criteria1 = new Criteria(DbAction.DELETE, Class1Schema.ALL_TABLE_ELEMENT + ", " + Class2Schema.ALL_TABLE_ELEMENT);
            //criteria1.AddDbLink(Class2Schema.TABLE, DbLinks.FROM);
            //criteria1.AddDbLink(Class1Schema.TABLE, DbLinks.INNERJOIN, new LinkCondition(Class2Schema.PREFIX_CLASS1_ID, Class1Schema.PREFIX_ID));
            //criteria1.AddCriterion(new Criterion(DbVerb.EMPTY, Class2Schema.PREFIX_CLASS1_ID, DbOperator.SUPERIOREQUAL, "4"));

            //String value1 = criteria1.MySQLCompute();
            //await managerClass2.CustomQuery(criteria1);
        }
예제 #13
0
        public async Task SearchPlaylistByTags(SocketCommandContext context, string tags)
        {
            string[] seperatedTags;
            if (tags.IndexOf(";", StringComparison.Ordinal) < 1)
            {
                seperatedTags = new[] { tags };
            }
            else
            {
                seperatedTags = tags.Split(";");
            }
            using (var soraContext = new SoraContext())
            {
                List <SearchStruct> searchResult = new List <SearchStruct>();
                foreach (var playlist in soraContext.ShareCentrals.Where(x => x.IsPrivate == false))
                {
                    int      matches      = 0;
                    string[] playlistTags = playlist.Tags.Split(";");
                    foreach (var tag in seperatedTags)
                    {
                        foreach (var playlistTag in playlistTags)
                        {
                            if (tag.Trim().Equals(playlistTag.Trim(), StringComparison.OrdinalIgnoreCase))
                            {
                                matches++;
                            }
                        }
                    }
                    if (matches > 0)
                    {
                        searchResult.Add(new SearchStruct()
                        {
                            Matches        = matches,
                            SharedPlaylist = playlist
                        });
                    }
                }

                if (searchResult.Count == 0)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Nothing found with entered tags"));

                    return;
                }

                var           orderedList     = searchResult.OrderByDescending(x => x.Matches).ThenByDescending(x => (x.SharedPlaylist.Upvotes - x.SharedPlaylist.Downvotes)).ToList();
                List <string> playlistsString = new List <string>();
                int           pageAmount      = (int)Math.Ceiling(orderedList.Count / 7.0);
                int           addToJ          = 0;
                int           amountLeft      = orderedList.Count;
                for (int i = 0; i < pageAmount; i++)
                {
                    string addToList = "";
                    for (int j = 0; j < (amountLeft > 7 ? 7 : amountLeft); j++)
                    {
                        var sharedPlaylist = orderedList[j + addToJ].SharedPlaylist;
                        addToList += $"**[{sharedPlaylist.Titel}]({sharedPlaylist.ShareLink})**\nVotes: {sharedPlaylist.Upvotes} / {sharedPlaylist.Downvotes}  \tTags: {sharedPlaylist.Tags.Replace(";", " - ")}\n\n";
                    }
                    playlistsString.Add(addToList);
                    amountLeft -= 7;
                    addToJ     += 7;
                }
                if (pageAmount > 1)
                {
                    var pmsg = new PaginatedMessage()
                    {
                        Author = new EmbedAuthorBuilder()
                        {
                            IconUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar,
                            Name    = context.User.Username
                        },
                        Color   = Utility.PurpleEmbed,
                        Title   = $"🔍 Search Results",
                        Options = new PaginatedAppearanceOptions()
                        {
                            DisplayInformationIcon = false,
                            Timeout     = TimeSpan.FromSeconds(30),
                            InfoTimeout = TimeSpan.FromSeconds(30)
                        },
                        Content = "Only the invoker may switch pages, ⏹ to stop the pagination",
                        Pages   = playlistsString
                    };

                    Criteria <SocketReaction> criteria = new Criteria <SocketReaction>();
                    criteria.AddCriterion(new EnsureReactionFromSourceUserCriterionMod());

                    await _interactive.SendPaginatedMessageAsync(context, pmsg, criteria);
                }
                else
                {
                    var eb = new EmbedBuilder()
                    {
                        Author = new EmbedAuthorBuilder()
                        {
                            IconUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar,
                            Name    = context.User.Username
                        },
                        Color       = Utility.PurpleEmbed,
                        Title       = $"Search Results",
                        Description = playlistsString[0],
                        Footer      = new EmbedFooterBuilder()
                        {
                            Text = "Page 1/1"
                        }
                    };
                    await context.Channel.SendMessageAsync("", embed : eb);
                }
            }
        }
예제 #14
0
        private async Task PaginateResult(SocketCommandContext context, string title, List <ShareCentral> orderedList)
        {
            List <string> playlistsString = new List <string>();
            int           pageAmount      = (int)Math.Ceiling(orderedList.Count / 7.0);
            int           addToJ          = 0;
            int           amountLeft      = orderedList.Count;

            for (int i = 0; i < pageAmount; i++)
            {
                string addToList = "";
                for (int j = 0; j < (amountLeft > 7 ? 7 : amountLeft); j++)
                {
                    var sharedPlaylist = orderedList[j + addToJ];
                    addToList += $"{(sharedPlaylist.IsPrivate ? "[P] " : "")}**[{sharedPlaylist.Titel}]({sharedPlaylist.ShareLink})**\nVotes: {sharedPlaylist.Upvotes} / {sharedPlaylist.Downvotes}  \tTags: {sharedPlaylist.Tags.Replace(";", " - ")}\n\n";
                }
                playlistsString.Add(addToList);
                amountLeft -= 7;
                addToJ     += 7;
            }
            if (pageAmount > 1)
            {
                var pmsg = new PaginatedMessage()
                {
                    Author = new EmbedAuthorBuilder()
                    {
                        IconUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar,
                        Name    = context.User.Username
                    },
                    Color   = Utility.PurpleEmbed,
                    Title   = title,
                    Options = new PaginatedAppearanceOptions()
                    {
                        DisplayInformationIcon = false,
                        Timeout     = TimeSpan.FromSeconds(60),
                        InfoTimeout = TimeSpan.FromSeconds(60)
                    },
                    Content = "Only the invoker may switch pages, ⏹ to stop the pagination",
                    Pages   = playlistsString
                };

                Criteria <SocketReaction> criteria = new Criteria <SocketReaction>();
                criteria.AddCriterion(new EnsureReactionFromSourceUserCriterionMod());

                await _interactive.SendPaginatedMessageAsync(context, pmsg, criteria);
            }
            else
            {
                var eb = new EmbedBuilder()
                {
                    Author = new EmbedAuthorBuilder()
                    {
                        IconUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar,
                        Name    = context.User.Username
                    },
                    Color       = Utility.PurpleEmbed,
                    Title       = title,
                    Description = playlistsString[0],
                    Footer      = new EmbedFooterBuilder()
                    {
                        Text = "Page 1/1"
                    }
                };
                await context.Channel.SendMessageAsync("", embed : eb);
            }
        }
예제 #15
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);
            }
        }
예제 #16
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"));
        }
예제 #17
0
        public async Task ListSars(SocketCommandContext context)
        {
            using (SoraContext soraContext = new SoraContext())
            {
                var guildDb = Utility.GetOrCreateGuild(context.Guild.Id, soraContext);

                int roleCount = guildDb.SelfAssignableRoles.Count;
                if (roleCount == 0)
                {
                    await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(
                                                               Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                               "Guild has no self-assignable roles!"));

                    return;
                }
                if (roleCount < 24)
                {
                    var eb = new EmbedBuilder()
                    {
                        Color        = Utility.PurpleEmbed,
                        Title        = $"Self-Assignable roles in {context.Guild.Name}",
                        ThumbnailUrl = context.Guild.IconUrl ?? Utility.StandardDiscordAvatar,
                        Footer       = Utility.RequestedBy(context.User)
                    };

                    List <Role> roleList = new List <Role>(guildDb.SelfAssignableRoles);
                    foreach (var role in roleList)
                    {
                        //check if role still exists otherwise remove it
                        var roleInfo = context.Guild.GetRole(role.RoleId);
                        if (roleInfo == null)
                        {
                            guildDb.SelfAssignableRoles.Remove(role);
                            continue;
                        }

                        eb.AddField(x =>
                        {
                            x.IsInline = true;
                            x.Name     = roleInfo.Name;
                            x.Value    =
                                $"Cost: {role.Cost}{(role.CanExpire ? $"\nDuration: {role.Duration.Humanize(2, maxUnit: TimeUnit.Day, minUnit: TimeUnit.Second, countEmptyUnits:true)}" : "")}";
                        });
                        //eb.Description += $"• {roleInfo.Name}\n";
                    }
                    await context.Channel.SendMessageAsync("", embed : eb);
                }
                else
                {
                    List <Role>   roleList   = new List <Role>(guildDb.SelfAssignableRoles);
                    List <string> sars       = new List <string>();
                    int           pageAmount = (int)Math.Ceiling(roleCount / 7.0);
                    int           addToJ     = 0;
                    int           amountLeft = roleCount;
                    for (int i = 0; i < pageAmount; i++)
                    {
                        string addToList = "";
                        for (int j = 0; j < (amountLeft > 7 ? 7 : amountLeft); j++)
                        {
                            var role     = roleList[j + addToJ];
                            var roleInfo = context.Guild.GetRole(role.RoleId);
                            if (roleInfo == null)
                            {
                                guildDb.SelfAssignableRoles.Remove(role);
                                continue;
                            }
                            addToList += $"**{roleInfo.Name}**\nCost: {role.Cost}{(role.CanExpire ? $" \t \tDuration: {role.Duration.Humanize(2, maxUnit: TimeUnit.Day, minUnit: TimeUnit.Second, countEmptyUnits:true)} days" : "")}";
                        }
                        sars.Add(addToList);
                        amountLeft -= 7;
                        addToJ     += 7;
                    }
                    var pmsg = new PaginatedMessage()
                    {
                        Author = new EmbedAuthorBuilder()
                        {
                            IconUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar,
                            Name    = context.User.Username
                        },
                        Color   = Utility.PurpleEmbed,
                        Title   = $"Self-Assignable roles in {context.Guild.Name}",
                        Options = new PaginatedAppearanceOptions()
                        {
                            DisplayInformationIcon = false,
                            Timeout     = TimeSpan.FromSeconds(60),
                            InfoTimeout = TimeSpan.FromSeconds(60)
                        },
                        Content = "Only the invoker may switch pages, ⏹ to stop the pagination",
                        Pages   = sars
                    };

                    Criteria <SocketReaction> criteria = new Criteria <SocketReaction>();
                    criteria.AddCriterion(new EnsureReactionFromSourceUserCriterionMod());

                    await _interactive.SendPaginatedMessageAsync(context, pmsg, criteria);
                }
                await soraContext.SaveChangesAsync();
            }
        }