Example #1
0
 private async Task SubstractFromBucket(SocketUser user)
 {
     try
     {
         BucketData data = new BucketData();
         if (!_bucketDict.TryGetValue(user.Id, out data))
         {
             return;
         }
         data.bucketSize -= BUCKET_DRAIN_SIZE;
         if (data.bucketSize < 0)
         {
             //RATELIMIT
             data.rateLimitedTill = DateTime.UtcNow.AddSeconds(BUCKET_RATELIMITER);
             await(await user.GetOrCreateDMChannelAsync()).SendMessageAsync("" +
                                                                            $"**You have been ratelimited for {BUCKET_RATELIMITER} seconds. Please do not spam commands or stars! If you continue doing so your lockout will increase in time!**\n" +
                                                                            "If this was by mistake and you did not spam. join https://discord.gg/Pah4yj5 and @ me");
             await SentryService.SendMessage($"**Rate limit occured:**\n" +
                                             $"User: {user.Username}#{user.Discriminator} \t{user.Id}");
         }
         _bucketDict.TryUpdate(user.Id, data);
         //TODO SAVE DATABASE
     }
     catch (Exception e)
     {
         await SentryService.SendError(e);
     }
 }
Example #2
0
 public bool CheckIfRatelimited(SocketUser user)
 {
     try
     {
         BucketData data = new BucketData();
         if (!_bucketDict.TryGetValue(user.Id, out data))
         {
             return(false);
         }
         if (data.rateLimitedTill.CompareTo(DateTime.UtcNow) >= 0)
         {
             return(true);
         }
         if (data.bucketSize <= 0)
         {
             return(true);
         }
         // if (data.combo >= COMBO_MAX)
         //      return true;
         return(false);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         SentryService.SendError(e);
     }
     return(false);
 }
Example #3
0
        private async Task HandleErrorAsync(IResult result, SocketCommandContext context, CommandException exception = null)
        {
            switch (result.Error)
            {
            case CommandError.Exception:
                if (exception != null)
                {
                    await SentryService.SendMessage(
                        $"**Exception**\n{exception.InnerException.Message}\n```\n{exception.InnerException}```");
                }
                break;

            case CommandError.BadArgCount:
                await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], result.ErrorReason));

                break;

            case CommandError.UnknownCommand:
                break;

            case CommandError.ParseFailed:
                await context.Channel.SendMessageAsync($"", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"Couldn't parse entered value! Make sure you enter the requested data type").WithDescription("If a whole number is asked then please provide one etc."));

                break;

            default:
                await context.Channel.SendMessageAsync($"", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"{result.ErrorReason}"));

                break;
            }
        }
Example #4
0
        private async Task InitializeBucketRefillTimer()
        {
            try
            {
                _timer = new Timer(_ =>
                {////await (await Context.User.GetOrCreateDMChannelAsync()).SendMessageAsync("",false,eb);
                    var temp = _bucketDict.ToArray();
                    foreach (var bucket in temp)
                    {
                        if (bucket.Value.bucketSize < BUCKET_MAX_FILL)
                        {
                            bucket.Value.bucketSize += BUCKET_DROP_SIZE;
                        }
                        _bucketDict.TryUpdate(bucket.Key, bucket.Value);
                    }
                    //SAVE DB
                },
                                   null,
                                   TimeSpan.FromSeconds(BUCKET_DROP_INTERVAL),  // Time that message should fire after bot has started
                                   TimeSpan.FromSeconds(BUCKET_DROP_INTERVAL)); //time after which message should repeat (timout.infinite for no repeat)

                Console.WriteLine("BUCKET REFILL INITIALIZED");
            }
            catch (Exception e)
            {
                await SentryService.SendError(e);
            }
        }
Example #5
0
        public async Task getRolesInGuild()
        {
            try
            {
                var eb = new EmbedBuilder()
                {
                    Color  = new Color(4, 97, 247),
                    Title  = $"Roles in {Context.Guild.Name}",
                    Footer = new EmbedFooterBuilder()
                    {
                        Text    = $"Requested by {Context.User.Username}#{Context.User.Discriminator}",
                        IconUrl = (Context.User.GetAvatarUrl())
                    },
                    Description = ""
                };

                foreach (var r in Context.Guild.Roles.OrderByDescending(r => r.Position))
                {
                    eb.Description += $"{r.Position}. {r.Name}\n";
                }
                await Context.Channel.SendMessageAsync("", false, eb);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
 private async Task Client_GuildAvailable(SocketGuild guild)
 {
     if (guild.Id == 180818466847064065)
     {
         SentryService.Install();
     }
 }
Example #7
0
        public async Task SearchTagAndSend(string tag, SocketCommandContext Context)
        {
            try
            {
                List <TagStruct> tagStruct = new List <TagStruct>();
                if (tagDict.ContainsKey(Context.Guild.Id))
                {
                    tagDict.TryGetValue(Context.Guild.Id, out tagStruct);
                    foreach (var t in tagStruct)
                    {
                        if (t.tag.Equals(tag.Trim().ToLower()))
                        {
                            await Context.Channel.SendMessageAsync(t.value);

                            return;
                        }
                    }
                    await Context.Channel.SendMessageAsync($":no_entry_sign: Tag `{tag}` was not found!");
                }
                else
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: There are no tags in this guild!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Example #8
0
        public async Task IncreaseEP(SocketMessage msg)
        {
            //Don't process the comand if it was a system message
            var message = msg as SocketUserMessage;
            if (message == null) return;


            //Create a command Context
            var context = new SocketCommandContext(client, message);
            if (context.IsPrivate)
                return;
            if (context.User.IsBot)
                return;
            try
            {
                userStruct user = new userStruct();
                if (userEPDict.ContainsKey(context.User.Id))
                {
                    userEPDict.TryGetValue(context.User.Id, out user);

                    if (user.CanGainAgain == default(DateTime))
                        user.CanGainAgain = DateTime.UtcNow;

                    if (user.CanGainAgain.CompareTo(DateTime.UtcNow) > 0)
                        return;

                    user.CanGainAgain = DateTime.UtcNow.AddSeconds(10);
                    

                    int previousLvl = user.level;
                    user.ep += CalculateEP(context);
                    user.level = (int) Math.Round(0.15F * Math.Sqrt(user.ep));
                    if (previousLvl != user.level)
                    {
                        if (lvlSubsriberList.Contains(context.User.Id))
                        {
                            await (await context.User.GetOrCreateDMChannelAsync()).SendMessageAsync(
                                $":trophy: You leveled up! You are now level **{user.level}** \\ (•◡•) /");
                        }
                    }
                    userEPDict.TryUpdate(context.User.Id, user);
                }
                else
                {
                    user.ep += CalculateEP(context);
                    user.level = (int) Math.Round(0.15F * Math.Sqrt(user.ep));
                    userEPDict.TryAdd(context.User.Id, user);
                }
                if (Environment.TickCount >= timeToUpdate)
                {
                    timeToUpdate = Environment.TickCount + 30000;
                    SaveDatabase();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, context);
            }
        }
Example #9
0
 private void LoadDatabase()
 {
     try
     {
         if (File.Exists("StarBoard.json"))
         {
             using (StreamReader sr = File.OpenText(@"StarBoard.json"))
             {
                 using (JsonReader reader = new JsonTextReader(sr))
                 {
                     var temp =
                         jSerializer.Deserialize <ConcurrentDictionary <ulong, ulong> >(reader);
                     if (temp != null)
                     {
                         starChannelDict = temp;
                     }
                 }
             }
         }
         else
         {
             File.Create("StarBoard.json").Dispose();
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         SentryService.SendError(e);
     }
 }
Example #10
0
        public async Task Ship(SocketUser user1, SocketUser user2 = null)
        {
            try
            {
                user2 = user2 ?? Context.User;
                await GetAvatar(user1);
                await GetAvatar(user2);

                ProfileImageGeneration.GenerateShipping($"Shipping/{user1.Id}Avatar.png",
                                                        $"Shipping/{user2.Id}Avatar.png", $"Shipping/ship{user1.Id}{user2.Id}.png");

                int distance = LevenshteinDistance.Compute(Utility.GiveUsernameDiscrimComb(user1),
                                                           Utility.GiveUsernameDiscrimComb(user2));

                await Context.Channel.SendFileAsync($"Shipping/ship{user1.Id}{user2.Id}.png", $"💕 Probability: {Math.Round(Math.Min(100, distance*multiplier),2)}%");
            }
            catch (Exception e)
            {
                await SentryService.SendMessage(e.ToString());
            }
            if (File.Exists($"Shipping/{user1.Id}Avatar.png"))
            {
                File.Delete($"Shipping/{user1.Id}Avatar.png");
            }
            if (File.Exists($"Shipping/{user2.Id}Avatar.png"))
            {
                File.Delete($"Shipping/{user2.Id}Avatar.png");
            }
            if (File.Exists($"Shipping/ship{user1.Id}{user2.Id}.png"))
            {
                File.Delete($"Shipping/ship{user1.Id}{user2.Id}.png");
            }
        }
Example #11
0
        private async Task <bool> ModIsAllowed(SocketGuildUser mod, SocketGuildUser user, SocketCommandContext Context)
        {
            try
            {
                if (!mod.GuildPermissions.Has(GuildPermission.Administrator))
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: You are not an Administrator :frowning:");

                    return(false);
                }
                var modHighestRole = mod.Roles.OrderByDescending(r => r.Position).First();
                //var user = userT as SocketGuildUser;
                var usersHighestRole = user.Roles.OrderByDescending(r => r.Position).First();

                if (usersHighestRole.Position > modHighestRole.Position)
                {
                    await Context.Channel.SendMessageAsync(
                        ":no_entry_sign: You can't Blacklist someone above you in the role hierarchy!");

                    return(false);
                }
                return(true);
            }
            catch (Exception e)
            {
                await SentryService.SendError(e, Context);
            }

            return(false);
        }
        private async Task CommandsOnLog(LogMessage logMessage)
        {
            await SentryService.SendMessage($"Severity: {logMessage.Severity}\n" +
                                            $"Source: {logMessage.Source}");

            await SentryService.SendMessage($"Exception: {logMessage.Exception}\n" +
                                            $"Message: {logMessage.Message}\n");
        }
Example #13
0
        public async Task ShowProfile(SocketCommandContext Context, IUser user)
        {
            try
            {
                if (Context.User.Id != 192750776005689344 && userCooldown.ContainsKey(Context.User.Id))
                {
                    DateTime timeToTriggerAgain;
                    userCooldown.TryGetValue(Context.User.Id, out timeToTriggerAgain);
                    if (timeToTriggerAgain.CompareTo(DateTime.UtcNow) < 0)
                    {
                        timeToTriggerAgain = DateTime.UtcNow.AddSeconds(30);
                        userCooldown.TryUpdate(Context.User.Id, timeToTriggerAgain);
                    }
                    else
                    {
                        var time          = timeToTriggerAgain.Subtract(DateTime.UtcNow.TimeOfDay);
                        int remainingTime = time.Second;
                        await Context.Channel.SendMessageAsync(
                            $":no_entry_sign: You are still on cooldown! Wait another {remainingTime} seconds!");

                        return;
                    }
                }
                else
                {
                    DateTime timeToTriggerAgain = DateTime.UtcNow.AddSeconds(30);
                    userCooldown.TryAdd(Context.User.Id, timeToTriggerAgain);
                }
                if (userBG.ContainsKey(user.Id))
                {
                    //await DrawText(user.GetAvatarUrl(), user, Context);
                    await DrawProfileWithBG(user.GetAvatarUrl(), user, Context);
                }
                else
                {
                    //await DrawText2(user.GetAvatarUrl(), user, Context);
                    await DrawProfile(user.GetAvatarUrl(), user, Context);
                }
                //await Context.Channel.SendMessageAsync($"Image \n{img}");
                if (File.Exists($"{user.Id}.png"))
                {
                    await Context.Channel.SendFileAsync($"{user.Id}.png", null, false, null);

                    File.Delete($"{user.Id}.png");
                    File.Delete($"{user.Id}Avatar.png");
                    File.Delete($"{user.Id}AvatarF.png");
                }
                else
                {
                    await Context.Channel.SendMessageAsync("Failed to create Image! This may be due to the Image you linked is damaged or unsupported. Try a new Custom Pic or use the default Image (p setbg with no parameter sets it to the default image)");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Example #14
0
        public async Task RemoveTag(string tag, SocketCommandContext Context)
        {
            try
            {
                List <TagStruct> tagStruct = new List <TagStruct>();
                if (tagDict.ContainsKey(Context.Guild.Id))
                {
                    tagDict.TryGetValue(Context.Guild.Id, out tagStruct);
                    foreach (var t in tagStruct)
                    {
                        if (t.tag.Equals(tag.Trim().ToLower()))
                        {
                            GuildPermission permiss = GuildPermission.Connect;
                            if (tagRestrictDict.ContainsKey(Context.Guild.Id))
                            {
                                tagRestrictDict.TryGetValue(Context.Guild.Id, out permiss);
                            }
                            if (Context.User.Id == t.creatorID ||
                                ((permiss == GuildPermission.Connect)
                                    ? ((SocketGuildUser)Context.User).GuildPermissions.Has(
                                     GuildPermission.ManageChannels)
                                    : ((SocketGuildUser)Context.User).GuildPermissions.Has(permiss)))
                            {
                                tagStruct.Remove(t);
                                if (tagDict.TryUpdate(Context.Guild.Id, tagStruct))
                                {
                                    SaveDatabase();
                                    await Context.Channel.SendMessageAsync(
                                        $":white_check_mark: Successfully removed the Tag `{t.tag}`");
                                }
                                else
                                {
                                    await Context.Channel.SendMessageAsync("Something went wrong :(");
                                }
                            }
                            else
                            {
                                await Context.Channel.SendMessageAsync(
                                    ":no_entry_sign: You are neither the Creator of the tag nor have the permissions to delete it!");
                            }

                            return;
                        }
                    }
                    await Context.Channel.SendMessageAsync($":no_entry_sign: Tag `{tag}` was not found!");
                }
                else
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: There are no tags in this guild!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Example #15
0
        private async Task ClientOnJoinedGuild(SocketGuild socketGuild)
        {
            Task.Run(async() => {
                //Notify discordbots that we joined a new guild :P
                try
                {
                    await _guildCount.UpdateCount(_client.Guilds.Count);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
                using (var soraContext = new SoraContext())
                {
                    var guild = Utility.GetOrCreateGuild(socketGuild.Id, soraContext);

                    //AUTO CREATE SORA ADMIN ROLE
                    //var created = await Utility.CreateSoraRoleOnJoinAsync(socketGuild, _client, soraContext).ConfigureAwait(false);

                    /*
                     * if (created)
                     * {
                     *  guild.RestrictTags = socketGuild.MemberCount > 100;
                     * }*/
                    await soraContext.SaveChangesAsync();
                    try
                    {
                        string prefix = Utility.GetGuildPrefix(socketGuild, soraContext);
                        await(await socketGuild.Owner.GetOrCreateDMChannelAsync()).SendMessageAsync("", embed: Utility.ResultFeedback(Utility.BlueInfoEmbed, Utility.SuccessLevelEmoji[3], $"Hello there (≧∇≦)/")
                                                                                                    .WithDescription($"I'm glad you invited me over :)\n" +
                                                                                                                     $"You can find the [list of commands and help here](http://git.argus.moe/serenity/SoraBot-v2/wikis/home)\n" +
                                                                                                                     $"To restrict tag creation and Sora's mod functions you must create\n" +
                                                                                                                     $"a {Utility.SORA_ADMIN_ROLE_NAME} Role so that only the ones carrying it can create\n" +
                                                                                                                     $"tags or use Sora's mod functionality. You can make him create one with: " +
                                                                                                                     $"`{prefix}createAdmin`\n" +
                                                                                                                     $"You can leave tag creation unrestricted if you want but its not\n" +
                                                                                                                     $"recommended on larger servers as it will be spammed.\n" +
                                                                                                                     $"**Sora now has a Dashboard**\n" +
                                                                                                                     $"You can [find the dashboard here](http://argonaut.pw/Sora/) by clicking the login\n" +
                                                                                                                     $"button in the top right. It's still in pre-alpha but allows you to\n" +
                                                                                                                     $"customize levels and level rewards as well as other settings. It is required\n" +
                                                                                                                     $"for proper setup of leveling.\n" +
                                                                                                                     $"PS: Standard Prefix is `$` but you can change it with:\n" +
                                                                                                                     $"`@Sora prefix yourPrefix`\n").WithThumbnailUrl(socketGuild.IconUrl ?? Utility.StandardDiscordAvatar).AddField("Support", $"You can find the [support guild here]({Utility.DISCORD_INVITE})"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }

                //inform me of joining
                await SentryService.SendMessage($"**JOINED GUILD**\nName: {socketGuild.Name}\nID: {socketGuild.Id}\nUsers: {socketGuild.MemberCount}\nOwner: {Utility.GiveUsernameDiscrimComb(socketGuild.Owner)}");
                //TODO WELCOME MESSAGE
            });
        }
Example #16
0
        public async Task ShowBlackListedUsers(SocketCommandContext Context)
        {
            try
            {
                var mod = Context.User as SocketGuildUser;
                if (!mod.GuildPermissions.Has(GuildPermission.Administrator))
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: You are not an Administrator :frowning:");

                    return;
                }

                List <ulong> userList = new List <ulong>();
                if (!_guildBlackListDict.ContainsKey(Context.Guild.Id))
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: There are no Blacklisted users in this guild!");

                    return;
                }
                _guildBlackListDict.TryGetValue(Context.Guild.Id, out userList);
                if (userList == null || userList.Count < 1)
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: There are no Blacklisted users in this guild!");

                    return;
                }

                var eb = new EmbedBuilder()
                {
                    Color  = new Color(4, 97, 247),
                    Title  = $"Blacklisted Users in {Context.Guild.Name}",
                    Footer = new EmbedFooterBuilder
                    {
                        IconUrl = (Context.User.GetAvatarUrl()),
                        Text    = $"Requested by {Context.User.Username}#{Context.User.Discriminator}"
                    }
                };


                foreach (var userId in userList)
                {
                    var user = Context.Guild.GetUser(userId);
                    if (!user.Discriminator.Equals("0000"))
                    {
                        eb.Description += $"{user.Username}#{user.Discriminator}\n";
                    }
                }

                await Context.Channel.SendMessageAsync("", embed : eb);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Example #17
0
 public async Task BanUser(IUser user)
 {
     try
     {
         await Context.Guild.AddBanAsync(user, 0, null);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e, Context);
     }
 }
Example #18
0
 public async Task RestrictManageChannels(SocketCommandContext context, string perms)
 {
     try
     {
         if (((SocketGuildUser)context.User).GuildPermissions.Has(GuildPermission.Administrator))
         {
             if (tagRestrictDict.ContainsKey(context.Guild.Id) && perms == null)
             {
                 GuildPermission ignore;
                 tagRestrictDict.TryRemove(context.Guild.Id, out ignore);
                 SaveDatabaseRestrict();
                 await context.Channel.SendMessageAsync(":white_check_mark: Restriction removed!");
             }
             else if (perms != null)
             {
                 if (permissionsDict.ContainsKey(perms))
                 {
                     GuildPermission permiss;
                     permissionsDict.TryGetValue(perms, out permiss);
                     if (tagRestrictDict.ContainsKey(context.Guild.Id))
                     {
                         tagRestrictDict.TryUpdate(context.Guild.Id, permiss);
                     }
                     else
                     {
                         tagRestrictDict.TryAdd(context.Guild.Id, permiss);
                     }
                     SaveDatabaseRestrict();
                     await context.Channel.SendMessageAsync(
                         $":white_check_mark: Successfully restricted tags to `{perms}`!");
                 }
                 else
                 {
                     await context.Channel.SendMessageAsync(":no_entry_sign: Permission does not exist!");
                 }
             }
             else
             {
                 await context.Channel.SendMessageAsync(":no_entry_sign: No restrictions set as of yet!");
             }
         }
         else
         {
             await context.Channel.SendMessageAsync(
                 ":no_entry_sign: You have to have the `Administrator` Permission to restrict tags!");
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e, context);
     }
 }
 private async Task Client_LeftGuild(SocketGuild arg)
 {
     try
     {
         await SentryService.SendMessage($"Left Guild {arg.Name} / {arg.Id} with {arg.MemberCount} members");
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e);
     }
 }
Example #20
0
 public async Task KickUser(IUser user)
 {
     try
     {
         await(user as IGuildUser).KickAsync(null);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e, Context);
     }
 }
Example #21
0
 public async Task CreateException()
 {
     try
     {
         int i2 = 0;
         int i  = 10 / i2;
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e, Context);
     }
 }
Example #22
0
 public async Task LeaveGuild(ulong id)
 {
     try
     {
         var client = Context.Client as DiscordSocketClient;
         await client.GetGuild(id).LeaveAsync();
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e, Context);
     }
 }
Example #23
0
 private async Task ClientOnLeftGuild(SocketGuild socketGuild)
 {
     //notify discordbots
     try
     {
         await _guildCount.UpdateCount(_client.Guilds.Count);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
     await SentryService.SendMessage($"**LEFT GUILD**\nName: {socketGuild.Name}\nID: {socketGuild.Id}\nUsers: {socketGuild.MemberCount}\nOwner: {Utility.GiveUsernameDiscrimComb(socketGuild.Owner)}");
 }
Example #24
0
        public async Task ChangeAffinity(affinityType type, IUser user, SocketCommandContext Context)
        {
            try
            {
                AffinityStats stats = new AffinityStats();
                if (affinityDict.ContainsKey(user.Id))
                {
                    affinityDict.TryGetValue(user.Id, out stats);
                }
                switch (type)
                {
                case (affinityType.pat):
                    stats.pats++;
                    break;

                case (affinityType.hug):
                    stats.hugs++;
                    break;

                case (affinityType.kiss):
                    stats.kisses++;
                    break;

                case (affinityType.poke):
                    stats.pokes++;
                    break;

                case (affinityType.slap):
                    stats.slaps++;
                    break;

                default:
                    await Context.Channel.SendMessageAsync(":no_entry_sign: Something went horribly wrong :eyes:");

                    await SentryService.SendMessage("AFFINITY FAILED IN SWITCH");

                    break;
                }

                affinityDict.AddOrUpdate(
                    user.Id,
                    stats,
                    (key, oldValue) => stats);
                SaveDatabase();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Example #25
0
        public async Task GetYTResults(SocketCommandContext Context, string query)
        {
            try
            {
                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    ApiKey          = ytApiKey,
                    ApplicationName = "SoraBot" //this.GetType().ToString()
                });

                var searchListRequest = youtubeService.Search.List("snippet");
                var search            = System.Net.WebUtility.UrlEncode(query);
                searchListRequest.Q          = search;
                searchListRequest.MaxResults = 10;

                var searchListResponse = await searchListRequest.ExecuteAsync();

                List <string> videos    = new List <string>();
                List <string> channels  = new List <string>();
                List <string> playlists = new List <string>();

                foreach (var searchResult in searchListResponse.Items)
                {
                    switch (searchResult.Id.Kind)
                    {
                    case "youtube#video":
                        videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
                        break;

                    case "youtube#channel":
                        channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
                        break;

                    case "youtube#playlist":
                        playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
                        break;
                    }
                }

                await Context.Channel.SendMessageAsync(String.Format("Videos: \n{0}\n", String.Join("\n", videos)));

                await Context.Channel.SendMessageAsync(String.Format("Channels: \n{0}\n", String.Join("\n", channels)));

                await Context.Channel.SendMessageAsync(String.Format("Playlists: \n{0}\n", String.Join("\n", playlists)));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Example #26
0
 public async Task CreateInvite(ulong id)
 {
     try
     {
         var             RequestedGuild = Context.Client.GetGuild(id);
         IInviteMetadata GuildDefault   =
             await(RequestedGuild.GetChannel(RequestedGuild.DefaultChannel.Id) as IGuildChannel)
             .CreateInviteAsync();
         await Context.Channel.SendMessageAsync("Invite link: " + GuildDefault.Url);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e, Context);
     }
 }
Example #27
0
 public async Task RateLimitMain(SocketUser user)
 {
     try
     {
         CreateBucketIfNotExistant(user);
         if (!CheckComboAndAdd(user).Result)
         {
             return;
         }
         await SubstractFromBucket(user);
     }
     catch (Exception e)
     {
         await SentryService.SendError(e);
     }
 }
Example #28
0
        public async Task SetReminder(SocketCommandContext Context, string message)
        {
            try
            {
                var time = GetTimeInterval(message);
                if (time == 0)
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: Your time format was incorrect!");

                    return;
                }
                if (!CheckTimeInterval(Context.User, time))
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: You cannot have 2 Reminders that are within 60 seconds of each other");

                    return;
                }

                List <RemindData> dataList = new List <RemindData>();
                if (_remindDict.ContainsKey(Context.User.Id))
                {
                    _remindDict.TryGetValue(Context.User.Id, out dataList);
                }
                message = message.Replace("mins", "m");
                message = message.Replace("minutes", "m");
                message = message.Replace("minute", "m");
                message = message.Replace("min", "m");

                var        msg  = message.Substring(0, message.LastIndexOf("in"));
                RemindData data = new RemindData
                {
                    TimeToRemind = DateTime.UtcNow.AddSeconds(time),
                    message      = msg
                };
                dataList.Add(data); //_punishLogs.AddOrUpdate(Context.Guild.Id, str, (key, oldValue) => str);
                _remindDict.AddOrUpdate(Context.User.Id, dataList,
                                        (key, oldValue) => dataList);
                ChangeToClosestInterval();
                ReminderDB.SaveReminders(_remindDict);
                await Context.Channel.SendMessageAsync($":white_check_mark: Successfully set Reminder. I will remind you to `{data.message}` in `{message.Substring(message.LastIndexOf("in")+2)}`!");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Example #29
0
        private async Task <bool> CheckComboAndAdd(SocketUser user)
        {
            try
            {
                BucketData data = new BucketData();
                if (!_bucketDict.TryGetValue(user.Id, out data))
                {
                    return(false);
                }
                //Check if still in combo time
                if (DateTime.UtcNow.Subtract(data.lastCommand).TotalSeconds <= COMBO_TIME_INTERVALL)
                {
                    //COMBO BREAKER IF NEEDED
                    data.combo      += 1;
                    data.lastCommand = DateTime.UtcNow;
                    if (data.combo >= COMBO_MAX)
                    {
                        data.rateLimitedTill = DateTime.UtcNow.AddSeconds(COMBO_RATELIMITER);
                        await(await user.GetOrCreateDMChannelAsync()).SendMessageAsync("" +
                                                                                       $"**You have been ratelimited for {COMBO_RATELIMITER} seconds. Your ratelimit was triggered by the combo breaker and thus your time is higher than normal! Please do not spam commands or stars! If you continue doing so your lockout will increase in time!**\n" +
                                                                                       "If this was by mistake and you did not spam. join https://discord.gg/Pah4yj5 and @ me");
                        await SentryService.SendMessage($"**Rate limit occured:**\n" +
                                                        $"User: {user.Username}#{user.Discriminator} \t{user.Id}");

                        data.bucketSize -= COMBO_PENALTY;
                        _bucketDict.TryUpdate(user.Id, data);
                        //TODO SAVE DATABASE
                        return(false);
                    }
                    _bucketDict.TryUpdate(user.Id, data);
                    //TODO SAVE DATABASE
                    return(true);
                }
                //Reset combo
                data.lastCommand = DateTime.UtcNow;
                data.combo       = 1;
                _bucketDict.TryUpdate(user.Id, data);
                //TODO SAVE DATABASE
                return(true);
            }
            catch (Exception e)
            {
                await SentryService.SendError(e);
            }
            return(false);
        }
Example #30
0
        public async Task GetReminders(SocketCommandContext Context)
        {
            try
            {
                if (!_remindDict.ContainsKey(Context.User.Id))
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: You have no Reminders!");

                    return;
                }
                List <RemindData> data = new List <RemindData>();
                _remindDict.TryGetValue(Context.User.Id, out data);

                if (data.Count < 1)
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: You have no Reminders!");

                    return;
                }

                var orderedList = data.OrderBy(x => x.TimeToRemind).ToList();

                var eb = new EmbedBuilder()
                {
                    Color        = new Color(4, 97, 247),
                    ThumbnailUrl = (Context.User.GetAvatarUrl()),
                    Title        = $"{Context.User.Username}, your Reminders are"
                };
                for (int i = 0; i < orderedList.Count && i < 10; i++)
                {
                    eb.AddField((x) =>
                    {
                        x.Name     = $"Reminder #{i + 1} in {ConvertTime(orderedList[i].TimeToRemind.Subtract(DateTime.UtcNow).TotalSeconds)}";
                        x.IsInline = false;
                        x.Value    = $"{orderedList[i].message}";
                    });
                }

                await Context.Channel.SendMessageAsync("", embed : eb);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }