コード例 #1
0
ファイル: TumblrBot.cs プロジェクト: lasteur/Sabrina
        private async Task UpdateDatabase()
        {
            var context = new DiscordContext();

            DateTime?lastUpdate = DateTime.Now;

            try
            {
                lastUpdate = context.SabrinaSettings.First().LastTumblrUpdate;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            var minDate = DateTime.Now - TimeSpan.FromDays(3);

            if (lastUpdate != null && lastUpdate > minDate)
            {
                return;
            }

            int offset         = 0;
            var totalPostCount = GetPostCount();

            context.TumblrPosts.RemoveRange(context.TumblrPosts);

            await context.SaveChangesAsync();

            while (offset < totalPostCount)
            {
                Console.WriteLine($"Indexing at Position {offset} from {totalPostCount}]");
                var posts = await GetTumblrPostsByOffset(offset);

                if (posts.Response.TotalPosts != totalPostCount)
                {
                    totalPostCount = Convert.ToInt32(posts.Response.TotalPosts);
                }

                foreach (var post in posts.Response.Posts)
                {
                    if (!context.TumblrPosts.Any(tPost => tPost.TumblrId == post.Id))
                    {
                        await context.TumblrPosts.AddAsync(new TumblrPosts()
                        {
                            TumblrId   = post.Id,
                            IsLoli     = -1,
                            LastPosted = null
                        });
                    }
                }

                offset += posts.Response.Posts.Length;
            }

            context.SabrinaSettings.First().LastTumblrUpdate = DateTime.Now;
            await context.SaveChangesAsync();
        }
コード例 #2
0
ファイル: Edges.cs プロジェクト: Damitrix/Sabrina
        public async Task AssignEdgesAsync(CommandContext ctx, int edges)
        {
            if (edges < 1)
            {
                await ctx.RespondAsync("You cannot assign yourself less than 1 Edge. For obvious reasons");
            }

            var user = await UserExtension.GetUser(Convert.ToInt64(Convert.ToInt64(ctx.Message.Author.Id)));

            user.WalletEdges += edges;
            await _context.SaveChangesAsync();

            await ctx.RespondAsync(
                $"I've assigned you {edges} edges. Your balance is now {user.WalletEdges} edges.");
        }
コード例 #3
0
        /// <summary>
        /// Call when client Message is created. Logs all Messages to Database.
        /// </summary>
        /// <param name="e">
        /// The Message Event Args.
        /// </param>
        /// <returns>
        /// A <see cref="Task"/>.
        /// </returns>
        private async Task ClientMessageCreated(MessageCreateEventArgs e)
        {
            var msg = new Messages()
            {
                AuthorId     = Convert.ToInt64(e.Author.Id),
                MessageText  = e.Message.Content,
                ChannelId    = Convert.ToInt64(e.Message.Channel.Id),
                CreationDate = e.Message.CreationTimestamp.DateTime
            };

            try
            {
                var user = await _context.Users.FindAsync(Convert.ToInt64(e.Message.Author.Id));

                if (user == null)
                {
                    user = new Users
                    {
                        UserId = Convert.ToInt64(e.Author.Id)
                    };

                    _context.Users.Add(user);
                }

                await _context.Messages.AddAsync(msg);

                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error trying to enter Message into Database");
                Console.WriteLine(ex.Message);
            }
        }
コード例 #4
0
ファイル: TumblrBot.cs プロジェクト: lasteur/Sabrina
        public async Task CheckLoli(MessageReactionAddEventArgs e)
        {
            var name = e.Emoji.GetDiscordName();

            if (name != Config.Emojis.Underage)
            {
                return;
            }

            var msg = await e.Client.Guilds.First(g => g.Key == e.Message.Channel.GuildId).Value.GetChannel(e.Message.ChannelId)
                      .GetMessageAsync(e.Message.Id);

            if (msg.Embeds.Count != 1)
            {
                return;
            }

            bool isParceville = ulong.TryParse(msg.Embeds[0].Footer.Text, out ulong id);

            if (!isParceville)
            {
                return;
            }

            DiscordContext context = new DiscordContext();

            var post = await context.TumblrPosts.FindAsync(Convert.ToInt64(id));

            post.IsLoli = 1;
            await context.SaveChangesAsync();

            await msg.DeleteAsync(":underage:");
        }
コード例 #5
0
        /// <summary>
        /// Call when client Message is created. Logs all Messages to Database.
        /// </summary>
        /// <param name="e">The Message Event Args.</param>
        /// <returns>A <see cref="Task"/>.</returns>
        private async Task ClientMessageCreated(MessageCreateEventArgs e)
        {
            var context = new DiscordContext();

            if (context.Messages.Any(msg => msg.MessageId == Convert.ToInt64(e.Message.Id)))
            {
                return;
            }

            var user = await UserExtension.GetUser(e.Message.Author.Id, context);

            var cMsg = new Messages()
            {
                AuthorId     = Convert.ToInt64(user.UserId),
                MessageText  = e.Message.Content,
                ChannelId    = Convert.ToInt64(e.Message.Channel.Id),
                CreationDate = e.Message.CreationTimestamp.DateTime,
                MessageId    = Convert.ToInt64(e.Message.Id)
            };

            try
            {
                user = await UserExtension.GetUser(e.Message.Author.Id, context);

                await _context.Messages.AddAsync(cMsg);

                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error trying to enter Message into Database");
                Console.WriteLine(ex.Message);
            }
        }
コード例 #6
0
ファイル: TumblrBot.cs プロジェクト: lasteur/Sabrina
        public static async Task PostRandom(DiscordContext context, IEnumerable <DiscordChannel> channels)
        {
            Random rnd = new Random();

            foreach (var channel in channels)
            {
                var post = await GetRandomTumblrPost();

                if (post == null)
                {
                    // Can't reach tumblr rn
                    return;
                }

                TumblrPosts dbPost = await context.TumblrPosts.FindAsync(post.Response.Posts[0].Id);

                var builder = new DiscordEmbedBuilder()
                {
                    Author = new DiscordEmbedBuilder.EmbedAuthor()
                    {
                        Name = "YourAnimeAddiction"
                    },
                    Color    = DiscordColor.Orange,
                    ImageUrl = post.Response.Posts[0].Photos.First().AltSizes.OrderByDescending(size => size.Height).First().Url,
                    Title    = context.Puns.Skip(new Random().Next(context.Puns.Count() - 1)).First().Text
                };

                dbPost.LastPosted = DateTime.Now;
                dbPost.TumblrId   = post.Response.Posts[0].Id;

                await context.SaveChangesAsync();

                await channel.SendMessageAsync(embed : builder.Build());
            }
        }
コード例 #7
0
        private async Task <bool> CheckLocked(CommandContext ctx, Users user, DiscordContext context)
        {
            if (user.LockTime != null && user.LockTime > DateTime.Now)
            {
                TimeSpan?timeUntilFree = user.LockTime - DateTime.Now;

                TimeSpan newTimeUntilFree =
                    TimeSpan.FromTicks(timeUntilFree.Value.Ticks * Helpers.RandomGenerator.RandomInt(1, 3));

                if (newTimeUntilFree > TimeSpan.FromDays(365))
                {
                    _ = ctx.RespondAsync("F**k off");
                    return(false);
                }

                var responseText = "Oho, it seems like I told you to stay away from spinning the wheel...\n" +
                                   $"That means you get some more extra time of no spinning {DiscordEmoji.FromName(ctx.Client, Config.Emojis.Blush)}";

                if (int.TryParse(user.LockReason, out int reasonInt))
                {
                    var reason = (UserSetting.LockReason)reasonInt;

                    switch (reason)
                    {
                    case UserSetting.LockReason.Cooldown:
                        responseText =
                            "Oho, it seems like I told you to stay away from spinning the wheel...\n" +
                            $"That means you get some more extra time of no spinning {DiscordEmoji.FromName(ctx.Client, Config.Emojis.Blush)}";
                        user.LockTime += newTimeUntilFree;
                        break;

                    case UserSetting.LockReason.Extension:
                        responseText =
                            "Hey! I already told you, that you'd get a longer lock on the Wheel! You still want more? Sure!";
                        user.LockTime += newTimeUntilFree / 2;
                        break;

                    case UserSetting.LockReason.Task:
                        responseText = "Haha, there's no way you were able to finish your Task so quickly. Do your Task, " +
                                       "and then I'll give you another minute to think about your Actions.";
                        user.LockTime += TimeSpan.FromMinutes(1);
                        break;
                    }
                }

                user.LockReason = ((int)UserSetting.LockReason.Extension).ToString();

                await ctx.RespondAsync(responseText);

                await context.SaveChangesAsync();

                return(false);
            }
            else
            {
                return(true);
            }
        }
コード例 #8
0
        private async Task AnnounceVersion()
        {
            var context = new DiscordContext();

            var latestVersion = await context.SabrinaVersion.OrderByDescending(v => v.VersionNumber).FirstOrDefaultAsync();

            if (latestVersion == null || latestVersion.WasAnnounced == 1)
            {
                return;
            }

            foreach (var setting in context.SabrinaSettings)
            {
                long channelId = 0;

                if (setting.WheelChannel != null)
                {
                    channelId = setting.WheelChannel.Value;
                }
                else if (setting.ContentChannel != null)
                {
                    channelId = setting.ContentChannel.Value;
                }
                else if (setting.FeetChannel != null)
                {
                    channelId = setting.FeetChannel.Value;
                }

                if (channelId == 0)
                {
                    continue;
                }

                try
                {
                    var channel = await _client.GetChannelAsync(Convert.ToUInt64(channelId));

                    DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
                    {
                        Title       = $"I've received an upgrade! (v{latestVersion.VersionNumber})",
                        Description = latestVersion.Description.Replace("\\n", Environment.NewLine),
                        Color       = new DiscordColor(70, 254, 31)
                    };

                    await channel.SendMessageAsync(embed : builder.Build());
                }
                catch (Exception)
                {
                }
            }

            latestVersion.WasAnnounced = 1;

            await context.SaveChangesAsync();
        }
コード例 #9
0
ファイル: Feet.cs プロジェクト: Damitrix/Sabrina
        public async Task BoostFeetPics(CommandContext ctx)
        {
            using var context = new DiscordContext();

            var minTime = DateTime.Now - TimeSpan.FromHours(6);
            var boosts  = context.Boost.Where(b => b.Date > minTime && b.Channel == Convert.ToInt64(ctx.Channel.Id));

            if (await boosts.CountAsync() > 4)
            {
                await ctx.RespondAsync($"You have to wait before boosting again. Next one is available in {(TimeSpan.FromHours(6) - (DateTime.Now - boosts.Last().Date)).TotalMinutes} minutes.");

                return;
            }

            var sabrinaSettings = await context.SabrinaSettings.FindAsync(Convert.ToInt64(ctx.Guild.Id));

            if (sabrinaSettings.FeetChannel == null)
            {
                sabrinaSettings.FeetChannel = Convert.ToInt64(ctx.Channel.Id);
            }

            var channel = await ctx.Client.GetChannelAsync(Convert.ToUInt64(sabrinaSettings.FeetChannel));

            if (sabrinaSettings.FeetChannel.Value != Convert.ToInt64(ctx.Channel.Id))
            {
                await ctx.RespondAsync($"You cannot issue this command from this Channel. Please use {channel.Mention}");

                return;
            }

            var picsToPost = Helpers.RandomGenerator.RandomInt(2, 5);

            new Thread(async() =>
            {
                for (int i = 0; i < picsToPost; i++)
                {
                    if (i % 2 == 0)
                    {
                        await _sankakuBot.PostRandom(channel, i);
                    }
                    else
                    {
                        await _waifujoiBot.PostRandom(channel, new CancellationToken());
                    }
                }
            }).Start();

            context.Boost.Add(new Boost()
            {
                Amount  = picsToPost,
                Date    = DateTime.Now,
                Channel = Convert.ToInt64(ctx.Channel.Id)
            });
            await context.SaveChangesAsync();
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: Damitrix/Sabrina
        /// <summary>
        /// Call when client Message is created. Logs all Messages to Database.
        /// </summary>
        /// <param name="e">The Message Event Args.</param>
        /// <returns>A <see cref="Task"/>.</returns>
        private async Task ClientMessageCreated(MessageCreateEventArgs e)
        {
            var ohMatch = Regex.Match(e.Message.Content, "oh([.,!,?]?)", RegexOptions.IgnoreCase);

            if (ohMatch.Success && e.Message.Content.Length < 4 && _lastHiMark < DateTime.Now - TimeSpan.FromMinutes(60))
            {
                string himark = e.Message.Content.StartsWith("OH") ? "HI MARK" : "Hi Mark";
                string mark   = ohMatch.Groups.Count > 0 && ohMatch.Groups[1].Value.Contains('.', '?', '!') ? ohMatch.Groups[1].Value : "";
                await e.Channel.SendMessageAsync($"{himark}{mark}");

                _lastHiMark = DateTime.Now;
            }

            if (e.Author.Id == 503662068050952192 && e.Message.Content.Contains("horny", StringComparison.InvariantCultureIgnoreCase) && _lastCheeseHorny < DateTime.Now - TimeSpan.FromMinutes(60))
            {
                await e.Channel.SendMessageAsync("Yes Cheese, we know you're horny");

                _lastCheeseHorny = DateTime.Now;
            }

            using var context = new DiscordContext();

            if (context.Messages.Any(msg => msg.MessageId == Convert.ToInt64(e.Message.Id)))
            {
                return;
            }

            var user = await UserExtension.GetUser(e.Message.Author.Id, context);

            var cMsg = new Messages()
            {
                AuthorId     = Convert.ToInt64(user.UserId),
                MessageText  = e.Message.Content,
                ChannelId    = Convert.ToInt64(e.Message.Channel.Id),
                CreationDate = e.Message.CreationTimestamp.DateTime,
                MessageId    = Convert.ToInt64(e.Message.Id)
            };

            try
            {
                user = await UserExtension.GetUser(e.Message.Author.Id, context);

                await _context.Messages.AddAsync(cMsg);

                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error trying to enter Message into Database");
                Console.WriteLine(ex.Message);
            }
        }
コード例 #11
0
        /// <summary>
        /// </summary>
        /// <returns>true, if checks are passed</returns>
        private async Task <bool> DoInitialCheck(CommandContext ctx)
        {
            using DiscordContext context = new DiscordContext();
            Users user = await UserExtension.GetUser(Convert.ToInt64(ctx.Message.Author.Id), context);

            SabrinaSettings sabrinaSettings = await context.SabrinaSettings.FindAsync(Convert.ToInt64(ctx.Guild.Id));

            if (sabrinaSettings == null)
            {
                sabrinaSettings = new SabrinaSettings
                {
                    GuildId      = Convert.ToInt64(ctx.Guild.Id),
                    WheelChannel = Convert.ToInt64(ctx.Channel.Id)
                };

                await context.SabrinaSettings.AddAsync(sabrinaSettings);

                await context.SaveChangesAsync();
            }

            if (sabrinaSettings.WheelChannel == null)
            {
                sabrinaSettings.WheelChannel = Convert.ToInt64(ctx.Channel.Id);
                await context.SaveChangesAsync();
            }

            if (Convert.ToInt64(ctx.Channel.Id) != sabrinaSettings.WheelChannel.Value)
            {
                DiscordChannel channel =
                    await ctx.Client.GetChannelAsync(Convert.ToUInt64(sabrinaSettings.WheelChannel));

                await ctx.RespondAsync(
                    $"You cannot issue this command from this Channel. Please use {channel.Mention}");

                return(false);
            }

            return(true);
        }
コード例 #12
0
        public async Task RemoveProfileAsync(CommandContext ctx,
                                             [Description("Mention the user here")] DiscordUser dcUser)
        {
            DiscordContext context = new DiscordContext();
            Users          user    = await context.Users.FindAsync(Convert.ToInt64(ctx.Message.Author.Id));

            user.DenialTime  = null;
            user.BanTime     = null;
            user.LockTime    = null;
            user.SpecialTime = null;
            user.RuinTime    = null;

            await context.SaveChangesAsync();

            await ctx.RespondAsync($"I've reset the Profile of {dcUser.Mention}.");
        }
コード例 #13
0
        public async Task ResetProfileAsync(CommandContext ctx,
                                            [Description("Mention the user here")] DiscordUser dcUser)
        {
            using DiscordContext context = new DiscordContext();
            Users user = await UserExtension.GetUser(Convert.ToInt64(dcUser.Id), context);

            user.DenialTime  = DateTime.Now;
            user.BanTime     = DateTime.Now;
            user.LockTime    = DateTime.Now;
            user.SpecialTime = DateTime.Now;
            user.RuinTime    = DateTime.Now;

            await context.SaveChangesAsync();

            await ctx.RespondAsync($"I've reset the Profile of {dcUser.Mention}.");
        }
コード例 #14
0
        private async void _postTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var context = new DiscordContext();

            var lastPost = context.SabrinaSettings.First().LastTumblrPost;

            if (lastPost != null && lastPost > DateTime.Now - TimeSpan.FromHours(2))
            {
                return;
            }

            await PostRandom();

            context.SabrinaSettings.First().LastTumblrPost = DateTime.Now;
            await context.SaveChangesAsync();
        }
コード例 #15
0
        public async Task PostRandom(DiscordChannel channel, CancellationToken cancellationToken)
        {
            Console.WriteLine($"Waifubot: PostRandom {channel.Id}");
            using DiscordContext context = new DiscordContext();

            var channelId = Convert.ToInt64(channel.Id);

            var imageToPost = await GetRandomPicture(channelId, cancellationToken);

            if (imageToPost == null)
            {
                return;
            }

            HttpClient client = new HttpClient();

            using var response = await client.GetAsync(GetCreatorUrl (imageToPost.CreatorId), cancellationToken);

            using var stream = await response.Content.ReadAsStreamAsync();

            var creator = await MessagePack.MessagePackSerializer.DeserializeAsync <WaifuJoi.Shared.Features.User.GetUserResponse>(stream);

            DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
            {
                Author = new DiscordEmbedBuilder.EmbedAuthor()
                {
                    Name    = creator.User.Name,
                    IconUrl = BaseAddress + "api/thumbnail/" + creator.User.Avatar,
                    Url     = BaseAddress + "/profile/" + creator.User.Id
                },
                Color = new DiscordColor("#cf5ed4"),
                Title = context.Puns.Skip(Helpers.RandomGenerator.RandomInt(0, context.Puns.Count() - 1)).First()
                        .Text,
                ImageUrl = GetImageUrl(imageToPost.Id)
            };

            Console.WriteLine("WaifuBot: Sending embed");
            _ = channel.SendMessageAsync(embed: builder.Build());
            Console.WriteLine("Waifubot: Sending embed finished");
            context.WaifuJoiContentPost.Add(new WaifuJoiContentPost()
            {
                ContentId = imageToPost.Id,
                Time      = DateTime.Now
            });

            await context.SaveChangesAsync();
        }
コード例 #16
0
        public static async Task PostRandom(DiscordClient client, DiscordContext context, DiscordChannel[] channels)
        {
            TumblrPosts post  = null;
            int         cDays = 30;
            Random      rnd   = new Random();

            while (post == null)
            {
                var minDateTime = DateTime.Now - TimeSpan.FromDays(cDays);
                var validPosts  = context.TumblrPosts.Where(tPost => (tPost.LastPosted == null || tPost.LastPosted < minDateTime) && tPost.IsLoli < 1);
                var count       = validPosts.Count();

                if (count == 0)
                {
                    cDays--;
                    continue;
                }
                foreach (var channel in channels)
                {
                    var rndInt = rnd.Next(count);
                    post = validPosts.Skip(rndInt).First();

                    var builder = new DiscordEmbedBuilder()
                    {
                        Author = new DiscordEmbedBuilder.EmbedAuthor()
                        {
                            Name = "YourAnimeAddiction"
                        },
                        Color  = DiscordColor.Orange,
                        Footer = new DiscordEmbedBuilder.EmbedFooter()
                        {
                            Text = post.TumblrId.ToString()
                        },
                        ImageUrl = GetTumblrPostById(post.TumblrId).Response.Posts[0].Photos.First().AltSizes.OrderByDescending(size => size.Height).First().Url,
                        Title    = context.Puns.Skip(new Random().Next(context.Puns.Count() - 1)).First().Text
                    };

                    post.LastPosted = DateTime.Now;

                    await context.SaveChangesAsync();

                    await channel.SendMessageAsync(embed : builder.Build());
                }
            }
        }
コード例 #17
0
        private async Task Client_MessageReactionAdded(DSharpPlus.EventArgs.MessageReactionAddEventArgs e)
        {
            var context = new DiscordContext();

            var message = await context.SankakuPost.FirstOrDefaultAsync(post => post.MessageId == Convert.ToInt64(e.Message.Id));

            if (message != null)
            {
                SankakuImageVote vote = null;

                vote = new SankakuImageVote()
                {
                    ImageId   = message.ImageId,
                    UserId    = Convert.ToInt64(e.User.Id),
                    VoteValue = 0
                };

                string discordName = e.Emoji.GetDiscordName();

                if (Config.Emojis.Confirms.Contains(discordName))
                {
                    vote.VoteValue = 1;
                }
                else if (Config.Emojis.Love.Contains(discordName))
                {
                    vote.VoteValue = 3;
                }
                else if (Config.Emojis.Declines.Contains(discordName))
                {
                    vote.VoteValue = -1;
                }
                else if (Config.Emojis.Hate.Contains(discordName))
                {
                    vote.VoteValue = -3;
                }

                if (vote.VoteValue != 0)
                {
                    await context.SankakuImageVote.AddAsync(vote);
                }

                await context.SaveChangesAsync();
            }
        }
コード例 #18
0
ファイル: Feet.cs プロジェクト: Damitrix/Sabrina_DotNet47
        public async Task BoostFeetPics(CommandContext ctx)
        {
            var context = new DiscordContext();

            var minTime = DateTime.Now - TimeSpan.FromHours(6);
            var boosts  = context.Boost.Where(b => b.Date > minTime && (b.Channel == null || b.Channel == Convert.ToInt64(ctx.Channel.Id)));

            if (await boosts.CountAsync() > 4)
            {
                await ctx.RespondAsync($"You have to wait before boosting again. Next one is available in {(TimeSpan.FromHours(6) - (DateTime.Now - boosts.Last().Date)).TotalMinutes} minutes.");

                return;
            }

            var sabrinaSettings = await context.SabrinaSettings.FindAsync(Convert.ToInt64(ctx.Guild.Id));

            if (sabrinaSettings.FeetChannel == null)
            {
                sabrinaSettings.FeetChannel = Convert.ToInt64(ctx.Channel.Id);
            }

            var channel = await ctx.Client.GetChannelAsync(Convert.ToUInt64(sabrinaSettings.FeetChannel));

            if (sabrinaSettings.FeetChannel.Value != Convert.ToInt64(ctx.Channel.Id))
            {
                await ctx.RespondAsync($"You cannot issue this command from this Channel. Please use {channel.Mention}");

                return;
            }

            var picsToPost = Helpers.RandomGenerator.RandomInt(2, 5);

            for (int i = 0; i < picsToPost; i++)
            {
                await TumblrBot.PostRandom(ctx.Client, context, new DiscordChannel[] { channel });
            }

            context.Boost.Add(new Boost()
            {
                Amount = picsToPost,
                Date   = DateTime.Now
            });
            await context.SaveChangesAsync();
        }
コード例 #19
0
        private async Task Client_MessageReactionRemoved(DSharpPlus.EventArgs.MessageReactionRemoveEventArgs e)
        {
            var context = new DiscordContext();

            var message = await context.SankakuPost.FirstOrDefaultAsync(post => post.MessageId == Convert.ToInt64(e.Message.Id));

            if (message != null)
            {
                int VoteValue = 0;

                string discordName = e.Emoji.GetDiscordName();

                if (Config.Emojis.Confirms.Contains(discordName))
                {
                    VoteValue = 1;
                }
                else if (Config.Emojis.Love.Contains(discordName))
                {
                    VoteValue = 3;
                }
                else if (Config.Emojis.Declines.Contains(discordName))
                {
                    VoteValue = -1;
                }
                else if (Config.Emojis.Hate.Contains(discordName))
                {
                    VoteValue = -3;
                }

                var vote = await context.SankakuImageVote.FirstOrDefaultAsync(sankakuVote => sankakuVote.ImageId == message.ImageId &&
                                                                              sankakuVote.UserId == Convert.ToInt64(e.User.Id) &&
                                                                              sankakuVote.VoteValue == VoteValue);

                if (vote != null)
                {
                    context.SankakuImageVote.Remove(vote);
                }

                await context.SaveChangesAsync();
            }
        }
コード例 #20
0
ファイル: TumblrBot.cs プロジェクト: lasteur/Sabrina
        private async void PostTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                var context = new DiscordContext();

                var lastPost = context.SabrinaSettings.First().LastTumblrPost;
                if (lastPost != null && lastPost > DateTime.Now - TimeSpan.FromHours(2))
                {
                    return;
                }

                await PostRandom();

                context.SabrinaSettings.First().LastTumblrPost = DateTime.Now;
                await context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                await Console.Error.WriteLineAsync("Error in TumblrBot").ConfigureAwait(false);

                await Console.Error.WriteLineAsync(ex.Message).ConfigureAwait(false);
            }
        }
コード例 #21
0
        public async Task <bool> PostRandom(DiscordChannel channel, int skip = 0)
        {
            using var discordContext = new DiscordContext();

            (Entities.Sankaku.Image Information, byte[] Data)? image = null;

            try
            {
                image = await GetImage(channel, skip);
            }
            catch (Exception)
            {
                return(false);
            }

            string extension = ".jpeg";

            switch (image.Value.Information.FileType)
            {
            case Entities.Sankaku.FileType.ImageGif:
                extension = ".gif";
                break;

            case Entities.Sankaku.FileType.ImageJpeg:
                extension = ".jpeg";
                break;

            case Entities.Sankaku.FileType.ImagePng:
                extension = ".png";
                break;
            }

            DiscordMessage msg = null;

            var outStream = new MemoryStream(image.Value.Data);

            DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
            {
                Color = DiscordColor.SpringGreen,
                Title = discordContext.Puns.Skip(Helpers.RandomGenerator.RandomInt(0, discordContext.Puns.Count() - 1)).First().Text
            };

            try
            {
                if (outStream == null)
                {
                    Console.WriteLine("SankakuBot: Outstream was null");
                }

                Console.WriteLine($"SankakuBot: Sending File {Helpers.GetSafeFilename(builder.Title + extension)} to channel \"{channel.Name}\"");
                var msgTask = channel.SendFileAsync(Helpers.GetSafeFilename(builder.Title + extension), outStream, embed: builder.Build());

                int index = 0;
                while (!msgTask.IsCompleted && !msgTask.IsFaulted && index < 6000)
                {
                    await Task.Delay(5);
                }

                if (msgTask.IsCompleted)
                {
                    msg = await msgTask;
                }
                else
                {
                    Console.WriteLine($"SankakuBot: Couldn't send File with name {Helpers.GetSafeFilename(builder.Title + extension)}");
                    outStream.Close();
                    await _client.ReconnectAsync(true);
                }

                Console.WriteLine("SankakuBot: Finished Sending File");
            }
            catch (Exception ex)
            {
                Console.WriteLine("SankakuBot: Something went wrong while trying to send file");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.InnerException);
            }
            finally
            {
                try
                {
                    var taskContext = new DiscordContext();

                    taskContext.SankakuPost.Add(new SankakuPost()
                    {
                        Date      = DateTime.Now,
                        ImageId   = image.Value.Information.Id,
                        MessageId = Convert.ToInt64(msg.Id)
                    });

                    await taskContext.SaveChangesAsync();

                    _postedImages.Add(image.Value.Information.Id);

                    outStream.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

            return(true);
        }
コード例 #22
0
 private async Task OnLUserLeave(SocketGuildUser leavingUser)
 {
     await using var ctx = new DiscordContext();
     ctx.Users.Remove(await ctx.Users.FindAsync(leavingUser.Id));
     await ctx.SaveChangesAsync();
 }
コード例 #23
0
        public static async Task PostRandom(DiscordChannel channel, int skip = 0)
        {
            var context = new DiscordContext();

            SankakuImage imgToPost = null;

            Random rnd = new Random(skip);

            var channelIDLong = Convert.ToInt64(channel.Id);

            var blacklistedTags =
                await context.SankakuTagBlacklist.Where(blackTag => blackTag.ChannelId == channelIDLong).Select(tag => tag.TagId).ToListAsync();

            var startDate = DateTime.Now - TimeSpan.FromDays(90);

            var viableImages = context.SankakuImage.Where(si => si.SankakuPost.Count == 0 && si.Score > 4 && si.RatingCount > 6);

            while (imgToPost == null)
            {
                var firstNotPostedPicture = viableImages.Where(si => !si.SankakuImageTag.Any(tag => blacklistedTags.Contains(tag.TagId)))
                                            .Skip(skip).First();

                if (firstNotPostedPicture == null)
                {
                    var oldestPostedPicture = viableImages.Where(si =>
                                                                 si.SankakuPost.OrderByDescending(post => post.Date).First().Date < startDate)
                                              .Skip(skip);
                }
                else
                {
                    imgToPost = firstNotPostedPicture;
                }

                if (imgToPost == null)
                {
                    await ScrapeNewest();
                }
            }

            DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
            {
                Color = DiscordColor.SpringGreen,
                Title = context.Puns.Skip(rnd.Next(context.Puns.Count() - 1)).First().Text
            };

            var link = HttpUtility.HtmlDecode(await GetOriginalImageLink(imgToPost.Id));

            var request = Helpers.CreateRequestWithHeaders(link);

            var response = request.GetResponse();

            SKImage img = SKImage.FromEncodedData(response.GetResponseStream());

            if (img.ColorType == SKColorType.Bgra8888)
            {
                //Bgra8888 needs an indexed Colortable, so convert it to Rgba8888 first
                var bitmap = new SKBitmap(new SKImageInfo(img.Width, img.Height, SKColorType.Rgba8888));
                var canvas = new SKCanvas(bitmap);
                canvas.DrawImage(img, 0, 0, null);
                canvas.Flush();
                img = SKImage.FromBitmap(bitmap);
            }

            var imageData = img.Encode(SKEncodedImageFormat.Webp, 70);

            using (var outStream = imageData.AsStream())
            {
                var msg = await channel.SendFileAsync(outStream, builder.Title + ".webp",
                                                      embed : builder.Build());

                context.SankakuPost.Add(new Models.SankakuPost()
                {
                    Date      = DateTime.Now,
                    Image     = imgToPost,
                    MessageId = Convert.ToInt64(msg.Id)
                });

                await context.SaveChangesAsync();
            }
        }
コード例 #24
0
ファイル: Settings.cs プロジェクト: Damitrix/Sabrina
        public async Task SetupAsync(CommandContext ctx)
        {
            await ctx.RespondAsync("You got Mail! *AOL chime plays*");

            using var context = new DiscordContext();

            var dm = await ctx.Member.CreateDmChannelAsync();

            var userId = Convert.ToInt64(ctx.User.Id);

            string userName         = ctx.Message.Author.Username;
            string readableUserName = RemoveSpecialCharacters(userName);

            if (readableUserName.Length > 4)
            {
                userName = readableUserName;
            }

            await dm.TriggerTypingAsync();

            await Task.Delay(1000);

            await dm.SendMessageAsync($"Hey there {userName}.");

            await Task.Delay(1000);

            bool isFirstChange = true;

            var settings = UserSetting.GetAllSettings(userId, context);

            if (settings == null || settings.Count() == 0)
            {
                // *** First time setup ***

                if (!await Introduction(dm, ctx))
                {
                    return;
                }

                await dm.TriggerTypingAsync();

                await Task.Delay(1000);

                await dm.SendMessageAsync($"Splendid! Now that you know how this works, let's start with the Settings!");

                if (!await new WheelDifficultyModule(context, dm, ctx, userId).Execute())
                {
                    return;
                }

                if (!await new WheelTaskPreferenceModule(context, dm, ctx, userId).Execute())
                {
                    return;
                }

                isFirstChange = false;
            }

            // *** User has come back to change settings ***

            bool exit = false;

            while (!exit)
            {
                await dm.SendMessageAsync($"What{(isFirstChange ? "" : " else")} would you like to change?");

                isFirstChange = false;

                var m = await ctx.Client.GetInteractivity().WaitForMessageAsync(
                    x => x.Channel.Id == dm.Id && x.Author.Id == ctx.Member.Id,
                    TimeSpan.FromSeconds(240));

                if (m.TimedOut)
                {
                    // *** User didn't enter anything ***
                    return;
                }

                var text = m.Result.Content;

                var modules = ReflectiveEnumerator.GetEnumerableOfType <SettingsModule>(context, dm, ctx, userId).OrderByDescending(module => module.GetScore(text)).ToList();

                int  suggestion = 0;
                bool isMatch    = false;

                while (suggestion < 2 && !isMatch)
                {
                    await dm.TriggerTypingAsync();

                    await Task.Delay(1000);

                    await dm.SendMessageAsync($"Do you want to change your {modules[suggestion].FriendlyName} settings? (Y/N)");

                    var suggestionReply = await ctx.Client.GetInteractivity().WaitForMessageAsync(
                        x => x.Channel.Id == dm.Id && x.Author.Id == ctx.Member.Id,
                        TimeSpan.FromSeconds(240));

                    if (suggestionReply.TimedOut)
                    {
                        return;
                    }

                    if (Regex.Match(suggestionReply.Result.Content, YesRegex).Success)
                    {
                        isMatch = true;
                        exit    = !await modules[suggestion].Execute();
                    }
                    else
                    {
                        suggestion++;
                    }
                }

                if (suggestion >= 2)
                {
                    DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
                    {
                        Title = "These are your options"
                    };

                    foreach (var module in modules)
                    {
                        builder.AddField(module.FriendlyName, "--------", false);
                    }

                    await dm.TriggerTypingAsync();

                    await Task.Delay(2000);

                    await dm.SendMessageAsync(embed : builder.Build());

                    await dm.TriggerTypingAsync();

                    await Task.Delay(1000);

                    await dm.SendMessageAsync("Would you like to change something else? (Y/N)");

                    var moreChangesResponse = await ctx.Client.GetInteractivity().WaitForMessageAsync(
                        x => x.Channel.Id == dm.Id && x.Author.Id == ctx.Member.Id,
                        TimeSpan.FromSeconds(240));

                    if (moreChangesResponse.TimedOut)
                    {
                        return;
                    }

                    if (Regex.Match(moreChangesResponse.Result.Content, YesRegex).Success)
                    {
                        exit = false;
                    }
                    else
                    {
                        exit = true;
                    }

                    suggestion = 0;
                }
            }

            await dm.TriggerTypingAsync();

            await Task.Delay(1000);

            await dm.SendMessageAsync($"Alrighty! I'll try to remember that");

            await Task.Delay(2000);

            await dm.TriggerTypingAsync();

            await Task.Delay(500);

            await dm.SendMessageAsync($"..... I'll better write it down...");

            await dm.TriggerTypingAsync();

            try
            {
                await context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                await dm.SendMessageAsync($"**Uhh... something seems to have gone badly wrong...{Environment.NewLine}" +
                                          $"If you see Salem around here somewhere, tell him the following:**");

                await dm.TriggerTypingAsync();

                await Task.Delay(5000);

                string msgToSend = $"```{ex.Message}```";
                while (msgToSend.Length > 1999)
                {
                    await dm.SendMessageAsync(msgToSend.Substring(0, 1999));

                    await dm.TriggerTypingAsync();

                    await Task.Delay(2000);

                    msgToSend = msgToSend.Substring(1999);
                }

                await dm.SendMessageAsync(msgToSend);

                return;
            }

            await dm.SendMessageAsync($"Done!");

            await dm.TriggerTypingAsync();

            await Task.Delay(1000);

            await dm.SendMessageAsync($"Nice. You can now start using the Wheel with your brand new set of settings \\*-\\*{Environment.NewLine}" +
                                      $"These might get more over time. I will remind you to revisit them, when i feel fit.");
        }
コード例 #25
0
        public static async Task PostPrediction(long userId, DiscordChannel channel)
        {
            var context = new DiscordContext();

            SankakuImage imgToPost = null;

            Random rnd = new Random();

            var channelIDLong = Convert.ToInt64(channel.Id);

            var blacklistedTags =
                await context.SankakuTagBlacklist.Where(blackTag => blackTag.ChannelId == channelIDLong).Select(tag => tag.TagId).ToListAsync();

            var startDate = DateTime.Now - TimeSpan.FromDays(90);

            var trainedModel = Train(userId);

            int skip = 0;

            while (imgToPost == null)
            {
                //imgToPost = context.SankakuImage.Where(si => si.SankakuPost.Count == 0).Skip(skip).First();

                imgToPost = context.SankakuImage.Find(88415l);

                if (imgToPost == null)
                {
                    await ScrapeNewest();
                }

                List <MLSankakuPost> posts = new List <MLSankakuPost>();

                MLSankakuPost mlPost = new MLSankakuPost()
                {
                    //imgRating = imgToPost.Rating,
                    //score = Convert.ToSingle(imgToPost.Score),
                    //Tags = context.SankakuImageTag.Where(imageTag => imageTag.ImageId == imgToPost.Id).Select(tag => Convert.ToSingle(tag.TagId)).ToArray(),
                    Tags = 1,
                };

                posts.Add(mlPost);

                var prediction = trainedModel.Predict(posts, true);

                if (prediction.First().Score < 1)
                {
                    skip++;
                    imgToPost = null;
                }
            }

            DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
            {
                Color = DiscordColor.Orange,
                Title = context.Puns.Skip(new Random().Next(context.Puns.Count() - 1)).First().Text
            };

            var link = HttpUtility.HtmlDecode(await GetOriginalImageLink(imgToPost.Id));

            var request = Helpers.CreateRequestWithHeaders(link);

            var response = request.GetResponse();

            SKImage img = SKImage.FromEncodedData(response.GetResponseStream());

            if (img.ColorType == SKColorType.Bgra8888)
            {
                //Bgra8888 needs an indexed Colortable, so convert it to Rgba8888 first
                var bitmap = new SKBitmap(new SKImageInfo(img.Width, img.Height, SKColorType.Rgba8888));
                var canvas = new SKCanvas(bitmap);
                canvas.DrawImage(img, 0, 0, null);
                canvas.Flush();
                img = SKImage.FromBitmap(bitmap);
            }

            var imageData = img.Encode(SKEncodedImageFormat.Jpeg, 75); //Encode in Jpeg instead of Webp because of IOS

            using (var outStream = imageData.AsStream())
            {
                var msg = await channel.SendFileAsync(outStream, builder.Title + ".jpeg",
                                                      embed : builder.Build());

                context.SankakuPost.Add(new Models.SankakuPost()
                {
                    Date      = DateTime.Now,
                    Image     = imgToPost,
                    MessageId = Convert.ToInt64(msg.Id)
                });

                await context.SaveChangesAsync();
            }
        }
コード例 #26
0
        private async Task MainThread()
        {
            while (!Exit)
            {
                var context = new DiscordContext();
                foreach (var platform in context.Joiplatform)
                {
                    foreach (var link in context.CreatorPlatformLink)
                    {
                        Video newestVideo = null;

                        switch (platform.BaseUrl)
                        {
                        case "https://www.pornhub.com":
                            newestVideo = await GetNewestPornhubVideo(link.Identification);

                            break;
                        }

                        if (newestVideo == null || context.IndexedVideo.Any(iv => iv.Identification == newestVideo.ID))
                        {
                            await Task.Delay(3000);

                            continue;
                        }

                        var creator = await context.Creator.FindAsync(link.CreatorId);

                        var discordUser = client.GetUserAsync(Convert.ToUInt64(creator.DiscordUserId.Value));

                        IndexedVideo indexedVideo = new IndexedVideo()
                        {
                            CreationDate   = DateTime.Now,
                            CreatorId      = creator.Id,
                            Identification = newestVideo.ID,
                            Link           = newestVideo.Url,
                            PlatformId     = platform.Id
                        };

                        await context.IndexedVideo.AddAsync(indexedVideo);

                        DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
                        {
                            Color        = DiscordColor.Gold,
                            Title        = $"{newestVideo.Creator} has uploaded a new video!",
                            Url          = newestVideo.Url,
                            ThumbnailUrl = newestVideo.ImageUrl
                        };

                        builder.AddField("Title", newestVideo.Title);
                        if (creator.DiscordUserId != null)
                        {
                            builder.AddField("Creator", (await discordUser).Mention);
                        }

                        var embed = builder.Build();

                        await context.SaveChangesAsync();

                        foreach (var updateChannelId in context.SabrinaSettings.Where(ss => ss.ContentChannel != null).Select(ss => ss.ContentChannel))
                        {
                            var updateChannel = await client.GetChannelAsync(Convert.ToUInt64(updateChannelId));

                            await client.SendMessageAsync(updateChannel, embed : embed);
                        }
                    }
                }
                await Task.Delay(120000);
            }
        }
コード例 #27
0
        public async Task ContinueLength(CommandContext ctx, string length)
        {
            DungeonSession session =
                _context.DungeonSession.FirstOrDefault(ds => ds.UserId == Convert.ToInt64(ctx.User.Id));

            DungeonLogic.Dungeon dungeon = null;
            Room room = null;

            DungeonLogic.Dungeon.DungeonDifficulty dungeonDifficulty = DungeonLogic.Dungeon.DungeonDifficulty.Medium;
            var difficulty = _context.UserSetting.Where(setting => setting.UserId == Convert.ToInt64(ctx.User.Id)).FirstOrDefault(setting => setting.SettingId == (int)UserSetting.SettingID.DungeonDifficulty);

            if (difficulty == null)
            {
                dungeonDifficulty = DungeonLogic.Dungeon.DungeonDifficulty.Medium;
            }

            if (difficulty != null)
            {
                dungeonDifficulty = (DungeonLogic.Dungeon.DungeonDifficulty)Int32.Parse(difficulty.Value);
            }

            if (session != null)
            {
                // Pre-Existing Session found
                dungeon = JsonConvert.DeserializeObject <DungeonLogic.Dungeon>(session.DungeonData);
                room    = dungeon.Rooms.First(r => r.RoomID == Guid.Parse(session.RoomGuid));
            }
            else
            {
                DungeonLogic.Dungeon.DungeonLength dungeonLength =
                    (DungeonLogic.Dungeon.DungeonLength)Enum.Parse(typeof(DungeonLogic.Dungeon.DungeonLength), length);

                // Start new Session
                dungeon = new DungeonLogic.Dungeon(1, dungeonLength, dungeonDifficulty);
                room    = dungeon.Rooms.First();

                try
                {
                    var dungeonJson = JsonConvert.SerializeObject(dungeon, new JsonSerializerSettings
                    {
                        TypeNameHandling = TypeNameHandling.Auto
                    });

                    session = new DungeonSession
                    {
                        DungeonData = dungeonJson,
                        UserId      = Convert.ToInt64(ctx.User.Id),
                        RoomGuid    = room.RoomID.ToString()
                    };

                    await _context.DungeonSession.AddAsync(session);

                    await _context.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    throw ex;
                }
            }

            room.SetDifficulty(dungeonDifficulty);

            //Enter Room Message
            DiscordEmbedBuilder builder = new DiscordEmbedBuilder
            {
                Color       = DiscordColor.Grayple,
                Description = room.GetText(DungeonTextExtension.TextType.RoomEnter)
            };

            await ctx.RespondAsync(embed : builder.Build());

            await ctx.TriggerTypingAsync();

            await Task.Delay(room.WaitAfterMessage);

            if (room.Type == DungeonTextExtension.RoomType.LesserMob || room.Type == DungeonTextExtension.RoomType.Boss)
            {
                //Greeting Message
                builder = new DiscordEmbedBuilder
                {
                    Color       = DiscordColor.Chartreuse,
                    Description = room.GetText(DungeonTextExtension.TextType.Greeting)
                };

                await ctx.RespondAsync(embed : builder.Build());

                await ctx.TriggerTypingAsync();

                await Task.Delay(room.WaitAfterMessage);
            }

            // Main Message (Task or Chest opening f.e.)
            builder = new DiscordEmbedBuilder
            {
                Color       = DiscordColor.Blue,
                Description = room.GetText(DungeonTextExtension.TextType.Main)
            };

            await ctx.RespondAsync(embed : builder.Build());

            await Task.Delay(room.WaitAfterMessage);

            if (room.Type == DungeonTextExtension.RoomType.Loot)
            {
                // TODO: Save Loot
                builder = new DiscordEmbedBuilder
                {
                    Color       = DiscordColor.Chartreuse,
                    Description = "The Items have been placed into your current Inventory."
                };

                await ctx.RespondAsync(embed : builder.Build());

                await ctx.TriggerTypingAsync();

                await Task.Delay(room.WaitAfterMessage);
            }
            else if (room.Type == DungeonTextExtension.RoomType.LesserMob)
            {
                await ctx.RespondAsync("Did you finish my Task?");

                var m = await ctx.Client.GetInteractivity().WaitForMessageAsync(
                    x => x.Channel.Id == ctx.Channel.Id && x.Author.Id == ctx.Member.Id &&
                    Helpers.RegexHelper.ConfirmRegex.IsMatch(x.Content),
                    TimeSpan.FromMilliseconds(room.WaitAfterMessage / 4));

                if (!m.TimedOut)
                {
                    await ctx.RespondAsync("Well, time\'s up.");

                    // TODO: On Loose

                    // Loose Message
                    builder = new DiscordEmbedBuilder
                    {
                        Color       = DiscordColor.Red,
                        Description = room.GetText(DungeonTextExtension.TextType.Failure)
                    };

                    await ctx.RespondAsync(embed : builder.Build());

                    await ctx.TriggerTypingAsync();

                    await Task.Delay(room.WaitAfterMessage);
                }

                // If Task Successful
                if (Helpers.RegexHelper.YesRegex.IsMatch(m.Result.Content))
                {
                    // Win Message
                    builder = new DiscordEmbedBuilder
                    {
                        Color       = DiscordColor.Chartreuse,
                        Description = room.GetText(DungeonTextExtension.TextType.Success)
                    };

                    await ctx.RespondAsync(embed : builder.Build());

                    await ctx.TriggerTypingAsync();

                    await Task.Delay(room.WaitAfterMessage);
                }

                // If Task failed
                else if (Helpers.RegexHelper.NoRegex.IsMatch(m.Result.Content))
                {
                    // TODO: On Loose Loose Message
                    builder = new DiscordEmbedBuilder
                    {
                        Color       = DiscordColor.Red,
                        Description = room.GetText(DungeonTextExtension.TextType.Failure)
                    };

                    await ctx.RespondAsync(embed : builder.Build());

                    await ctx.TriggerTypingAsync();

                    await Task.Delay(room.WaitAfterMessage);
                }
            }

            if (room.AdjacentRooms == null || room.AdjacentRooms.Length == 0)
            {
                // TODO: Last Room. End Dungeon
            }

            await _context.SaveChangesAsync();
        }
コード例 #28
0
ファイル: HelpBot.cs プロジェクト: Damitrix/Sabrina_DotNet47
        private async Task OnTimerElapse()
        {
            var context = new DiscordContext();
            var now     = DateTime.Now;

            foreach (var setting in context.SabrinaSettings)
            {
                if (setting.WheelChannel != null && setting.LastWheelHelpPost == null || setting.LastWheelHelpPost < now - TimeSpan.FromDays(1))
                {
                    var channel = await _client.GetChannelAsync(Convert.ToUInt64(setting.WheelChannel.Value));

                    DiscordEmbedBuilder builder = new DiscordEmbedBuilder
                    {
                        Author = new DiscordEmbedBuilder.EmbedAuthor
                        {
                            IconUrl =
                                "https://cdn.discordapp.com/avatars/450771319479599114/d7dd3e2ec296542f170e84c264de78ce.png",
                            Name = "Sabrina"
                        },
                        Color       = DiscordColor.VeryDarkGray,
                        Description =
                            "Hey Guys and Gals, i'm Sabrina. Since Mistress can't tend to every single one of your pathetic little needs, i'm here to help her out." +
                            Environment.NewLine +
                            "I've got a bunch of neat little Commands to ~~torture~~ help you. You'll probably only ever need 3 though." +
                            Environment.NewLine + Environment.NewLine +
                            "``//orgasmwheel``" + Environment.NewLine +
                            "Use this, to spin the \"Wheel of Misfortune\". It contains fun little Tasks and \"Rewards\", that Mistress Aki herself has created. " +
                            "(That means, if you're unhappy with your outcome, you know where to complain.... if you dare to.)" +
                            Environment.NewLine + Environment.NewLine +
                            "``//denialtime``" + Environment.NewLine +
                            "This will show you, when exactly " + Environment.NewLine +
                            "    a) You are able to spin again" + Environment.NewLine +
                            "    b) You are not denied anymore" + Environment.NewLine +
                            "Which means, that you may spin the wheel while denied. But that also means, that you can also not be denied, while being excluded from the wheel." +
                            Environment.NewLine + Environment.NewLine +
                            "``//settings setup``" +
                            Environment.NewLine +
                            "When you issue this command, i will assist you with setting up the difficulty of the wheel and other stuffs. Just wait for my dm.",
                        Title  = "Introduction",
                        Footer = new DiscordEmbedBuilder.EmbedFooter()
                        {
                            IconUrl = "https://cdn.discordapp.com/avatars/249216025931939841/a_94cf2ac609424257706d6a611f5dd7aa.gif",
                            Text    = "If something doesn't seem right, please complain to Salem :)"
                        }
                    };

                    await channel.SendMessageAsync(embed : builder.Build());

                    setting.LastWheelHelpPost = DateTime.Now;
                }

                if (setting.FeetChannel != null && setting.LastDeepLearningPost == null || setting.LastDeepLearningPost < now - TimeSpan.FromDays(1))
                {
                    var channel = await _client.GetChannelAsync(Convert.ToUInt64(setting.FeetChannel.Value));

                    DiscordEmbedBuilder builder = new DiscordEmbedBuilder
                    {
                        Author = new DiscordEmbedBuilder.EmbedAuthor
                        {
                            IconUrl =
                                "https://cdn.discordapp.com/avatars/450771319479599114/d7dd3e2ec296542f170e84c264de78ce.png",
                            Name = "Sabrina"
                        },
                        Color       = DiscordColor.VeryDarkGray,
                        Description =
                            "Heyo, it's me! Your beloved Sabrina!" + Environment.NewLine +
                            "For the slow ones of you: I'm posting a neat little Picture here every now and then." + Environment.NewLine + Environment.NewLine +
                            "Since i can't read minds, i'd love for you, to upvote the pictures you like." + Environment.NewLine +
                            "Why?" + Environment.NewLine +
                            "Well, smartypants, if i feel confident enough about your preferences, i'll start posting pictures specifically chosen for you! <3"
                            + Environment.NewLine + Environment.NewLine
                            //+ "You can also get your fix a little earlier, by using the command ``//boostDL``"
                        ,
                        Title  = "Introduction",
                        Footer = new DiscordEmbedBuilder.EmbedFooter()
                        {
                            IconUrl = "https://cdn.discordapp.com/avatars/249216025931939841/a_94cf2ac609424257706d6a611f5dd7aa.gif",
                            Text    = "If something doesn't seem right, please complain to Salem :)"
                        }
                    };

                    await channel.SendMessageAsync(embed : builder.Build());

                    setting.LastDeepLearningPost = DateTime.Now;
                }
            }

            await context.SaveChangesAsync();
        }
コード例 #29
0
        public async Task ReportAsync(
            CommandContext ctx,
            [Description("Your outcome (denial/ruin/o****m)")]
            string outcome = null,
            [Description("How many edges it took")]
            int edges = 0,
            [Description("How long it took (5m = 5 minutes | 5m12s = 5 minutes, 12 seconds)")]
            string time = null)
        {
            // TODO: Check for Channel

            if (outcome == null || time == null)
            {
                await ctx.RespondAsync("Please supply information about your report (``//report denial 5 12m5s`` to report denial after 5 edges and 12 minutes and 5 seconds)");

                return;
            }

            outcome = outcome.ToUpperInvariant();

            IQueryable <Slavereports> slaveReports =
                from report in _context.Slavereports.Where(report => report.TimeOfReport > DateTime.Now.AddHours(-16))
                where report.UserId == Convert.ToInt64(ctx.User.Id)
                select report;

            var lastReport = slaveReports.FirstOrDefault();

            if (lastReport != null)
            {
                await ctx.RespondAsync(
                    $"You can only report once every 20 hours. You can report again in {TimeResolver.TimeToString(lastReport.TimeOfReport.AddHours(20) - DateTime.Now)}");

                var dm = await(await ctx.Guild.GetMemberAsync(Config.Users.Aki)).CreateDmChannelAsync();
                await dm.SendMessageAsync(
                    $"{ctx.Message.Author} has reported {TimeResolver.TimeToString(lastReport.TimeOfReport.AddHours(20) - DateTime.Now)} too early.");

                return;
            }

            if (Enum.TryParse(outcome, true, out UserSetting.Outcome result))
            {
                TimeSpan span;
                try
                {
                    var user = await UserExtension.GetUser(ctx.Message.Author.Id);

                    span = TimeResolver.GetTimeSpan(time);

                    await Task.Run(
                        async() =>
                    {
                        var report = new Slavereports()
                        {
                            TimeOfReport   = DateTime.Now,
                            UserId         = user.UserId,
                            Edges          = edges,
                            TimeSpan       = span.Ticks,
                            SessionOutcome = outcome
                        };

                        _context.Slavereports.Add(report);

                        await _context.SaveChangesAsync();
                    });
                }
                catch
                {
                    var builder = new DiscordEmbedBuilder
                    {
                        Title       = "Error",
                        Description =
                            "That's not how this works, you can enter your time in one of the following formats:",
                        Footer = new DiscordEmbedBuilder.EmbedFooter {
                            Text = "You get the Idea..."
                        }
                    };

                    builder.AddField("1h5m12s", "1 hour, 5 minutes, 12 seconds");
                    builder.AddField("5m", "5 minutes");
                    builder.AddField("2h", "2 hours");
                    builder.AddField("1200s", "1200 seconds");

                    await ctx.RespondAsync(embed : builder.Build());

                    return;
                }
            }
            else
            {
                var builder = new DiscordEmbedBuilder
                {
                    Title       = "Error",
                    Description = "That's not how this works, you gotta use one of the following:"
                };

                foreach (string possibleOutcome in Enum.GetNames(typeof(UserSetting.Outcome)))
                {
                    builder.AddField(possibleOutcome, $"``//report {possibleOutcome} {edges} {time}``");
                }

                await ctx.RespondAsync(embed : builder.Build());

                return;
            }

            var    formatText    = "{0}{1}{2}";
            var    prefix        = "Hey, ";
            var    postfix       = ". Thanks for reporting your task.";
            string name          = ctx.User.Mention;
            var    parsedOutcome = Enum.Parse <UserSetting.Outcome>(outcome, true);

            var responseColor = DiscordColor.Green;

            if (parsedOutcome == UserSetting.Outcome.Denial)
            {
                Tuple <string, string>[] templates =
                {
                    new Tuple <string,                                                        string>("Hehe, looks like that's it for you for today, ", " ^^"),
                    new Tuple <string,                                                        string>(
                        "That's what i like to see, ",
                        ". Now, can you do me a favor and report that again next time?~"),
                    new Tuple <string,                                                        string>(
                        "Ohh, is little ",
                        " denied? Well, too bad, you'll have to wait for your next chance~"),
                    new Tuple <string,                                                        string>(
                        "1, 2, 3, 4, ",
                        " is denied! ...Were you expecting a rhyme? Sucks being you, then.")
                };

                Tuple <string, string> template = templates[Helpers.RandomGenerator.RandomInt(0, templates.Length)];
                prefix  = template.Item1;
                postfix = template.Item2;

                responseColor = DiscordColor.Red;
            }

            if (parsedOutcome == UserSetting.Outcome.Ruin)
            {
                Tuple <string, string>[] templates =
                {
                    new Tuple <string,                                                                                             string>(
                        "Hmm, better than nothing, right, ",
                        "? Did it feel good?~ haha, of course not."),
                    new Tuple <string,                                                                                             string>(
                        "Oh ",
                        ", I don't know what i like more, denial or ruin... Do you think you get to deny yourself next time? :3"),
                    new Tuple <string,                                                                                             string>(
                        "It's not even a full o****m, but our ",
                        " still followed Orders. I bet you'll be even more obedient with your next chance..."),
                    new Tuple <string,                                                                                             string>("Another ruined one for ", " . Check.")
                };

                Tuple <string, string> template = templates[Helpers.RandomGenerator.RandomInt(0, templates.Length)];
                prefix  = template.Item1;
                postfix = template.Item2;

                responseColor = DiscordColor.Yellow;
            }

            if (parsedOutcome == UserSetting.Outcome.O****m)
            {
                Tuple <string, string>[] templates =
                {
                    new Tuple <string,                                                              string>(
                        "Meh, ",
                        " got a full O****m. How boring. It hope you get a ruined one next time."),
                    new Tuple <string,                                                              string>(
                        "And Mistress allowed that? You got lucky, ",
                        ". But i think i should ask Mistress to ruin your next one."),
                    new Tuple <string,                                                              string>("... ",                                 " ..."),
                    new Tuple <string,                                                              string>("Are you sure, you did it correctly, ", " ?")
                };

                Tuple <string, string> template = templates[Helpers.RandomGenerator.RandomInt(0, templates.Length)];
                prefix  = template.Item1;
                postfix = template.Item2;

                responseColor = DiscordColor.Green;
            }

            var responseBuilder = new DiscordEmbedBuilder
            {
                Author = new DiscordEmbedBuilder.EmbedAuthor
                {
                    Name    = ctx.User.Username,
                    IconUrl = ctx.User.AvatarUrl
                },
                Color       = responseColor,
                Description = string.Format(formatText, prefix, name, postfix),
                Footer      = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = "You can report back in 16 hours"
                }
            };

            await ctx.RespondAsync(embed : responseBuilder.Build());
        }
コード例 #30
0
        private async Task AnnounceNewestContent()
        {
            WaifuJoi.Shared.Features.Content.SearchContentResponse search = null;

            try
            {
                using var response = await _httpClient.GetAsync(BaseAddress + WaifuJoi.Shared.Features.Content.SearchContentRequest.Route, _cancellationTokenSource.Token);

                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Cannot get newest Content from WaifuJoi");
                    return;
                }

                search = await MessagePack.MessagePackSerializer.DeserializeAsync <WaifuJoi.Shared.Features.Content.SearchContentResponse>(await response.Content.ReadAsStreamAsync());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Cannot get newest Content from WaifuJoi");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            using DiscordContext context = new DiscordContext();

            var channelIDs = context.SabrinaSettings.Where(ss => ss.ContentChannel != null).Select(ss => ss.ContentChannel.Value).ToArray();
            List <DiscordChannel> channelsToPostTo = new List <DiscordChannel>();

            foreach (var channelId in channelIDs)
            {
                if (!_client.Guilds.Any())
                {
                    try
                    {
                        channelsToPostTo.Add(await _client.GetChannelAsync(Convert.ToUInt64(channelId)));
                    }
                    catch (Exception) { }
                }
                else if (_client.Guilds.Any(g => g.Value.Channels.Any(c => c.Key == Convert.ToUInt64(channelId))))
                {
                    channelsToPostTo.Add(await _client.GetChannelAsync(Convert.ToUInt64(channelId)));
                }
            }

            foreach (var channel in channelsToPostTo)
            {
                var channelIdLong = Convert.ToInt64(channel.Id);

                var settings = context.SabrinaSettings.First(ss => ss.ContentChannel == channelIdLong);

                var newContent = search.Content.Where(c => settings.LastWaifuJoiUpdate == null || c.CreationDate > settings.LastWaifuJoiUpdate);

                foreach (var content in newContent)
                {
                    DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
                    {
                        Color       = new DiscordColor(184, 86, 185),
                        ImageUrl    = BaseAddress + "api/thumbnail/" + content.Id.Trim(),
                        Title       = content.Title,
                        Description = content.Description,
                        Url         = BaseAddress + "show/" + content.Id.Trim(),
                        Timestamp   = content.CreationDate,
                        Footer      = new DiscordEmbedBuilder.EmbedFooter()
                        {
                            IconUrl = BaseAddress + "favicon.ico", Text = $"Hosted with <3 by Waifujoi"
                        }
                    };

                    if (content.Creator.DiscordId != null)
                    {
                        try
                        {
                            var creator = await _client.GetUserAsync(Convert.ToUInt64(content.Creator.DiscordId.Value));

                            builder.AddField("Creator", creator.Mention);
                        }
                        catch (Exception)
                        { }
                    }
                    else
                    {
                        builder.AddField("Creator", content.Creator.Name);
                    }

                    await channel.SendMessageAsync(embed : builder).ConfigureAwait(false);
                }

                settings.LastWaifuJoiUpdate = DateTime.Now;
            }

            await context.SaveChangesAsync(_cancellationTokenSource.Token);
        }