Example #1
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 #2
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 #3
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);
     }
 }
        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 #5
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
            });
        }
 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 #7
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 #8
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 #9
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 #10
0
        private Task LogCommand(LogMessage message)
        {
            // Return an error message for async commands
            if (message.Exception is CommandException command)
            {
                // Don't risk blocking the logging task by awaiting a message send; ratelimits!?
                //var _ = command.Context.Channel.SendMessageAsync($"Error: {command.Message}");
                SentryService.SendMessage($"Error: {command.Message}");
            }

            _discordLogger.Log(
                LogLevelFromSeverity(message.Severity),
                0,
                message,
                message.Exception,
                (_1, _2) => message.ToString(prependTimestamp: false));
            return(Task.CompletedTask);
        }
 private async Task Client_JoinedGuild(SocketGuild guild)
 {
     try
     {
         bool send = true;
         foreach (var p in guild.DefaultChannel.PermissionOverwrites)
         {
             if (p.Permissions.SendMessages == PermValue.Deny)
             {
                 send = false;
             }
         }
         var eb = new EmbedBuilder()
         {
             Color  = new Color(4, 97, 247),
             Footer = new EmbedFooterBuilder()
             {
                 Text = $"Bot created by Serenity#0783"
             },
             Title       = $"Hello {guild.Name} :wave:",
             Description =
                 $"Thank you for inviting me. My name is Sora and I hope I can make your Guild a little bit better :)" +
                 $" Sora's functions are extensively documented so that you can use him to his full potential.\nFor the docs [click this link](http://git.argus.moe/serenity/SoraBot/wikis/sora-help)"
         };
         eb.AddField((x) =>
         {
             x.Name     = "Live Support and Feedback";
             x.IsInline = false;
             x.Value    =
                 "If you need live support or simply want to give me feedback / bug reports or issue a Feature request head to this guild:\n[Click to Join](https://discord.gg/Pah4yj5)";
         });
         if (!send)
         {
             SocketTextChannel channel = null;
             bool pes = true;
             foreach (var cha in guild.TextChannels)
             {
                 pes = true;
                 foreach (var per in cha.PermissionOverwrites)
                 {
                     if (per.Permissions.SendMessages == PermValue.Deny)
                     {
                         pes = false;
                         break;
                     }
                 }
                 if (pes == true)
                 {
                     channel = cha;
                     break;
                 }
             }
             eb.AddField((x) =>
             {
                 x.Name     = "Sorry :(";
                 x.IsInline = false;
                 x.Value    = "I could not send a message in the default channel of this guild and had to take another one. That is why this message may be in a random channel. Sorry!";
             });
             await channel.SendMessageAsync("", false, eb);
         }
         else
         {
             await guild.DefaultChannel.SendMessageAsync("", false, eb);
         }
         await SentryService.SendMessage($"Joined Guild {guild.Name} / {guild.Id} with {guild.MemberCount} members");
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e);
     }
 }
Example #12
0
        //// Disabled by Catherine Renelle - Memory Leak Fix
        ////private string _connectionString;
        #endregion

        public async Task MainAsync(string[] args)
        {
            Console.WriteLine(args.Join(", "));
            int shardId;

            if (!int.TryParse(args[0], out shardId))
            {
                throw new Exception("INVALID SHARD ARGUMENT");
            }

            _restClient = new DiscordRestClient();

            //Setup config
            ConfigService.InitializeLoader();
            ConfigService.LoadConfig();

            if (!int.TryParse(ConfigService.GetConfigData("shardCount"), out Utility.TOTAL_SHARDS))
            {
                throw new Exception("INVALID SHARD COUNT");
            }

            //setup discord client
            _client = new DiscordSocketClient(new DiscordSocketConfig()
            {
                LogLevel            = LogSeverity.Info,
                AlwaysDownloadUsers = false,
                MessageCacheSize    = 0,
                TotalShards         = Utility.TOTAL_SHARDS,
                ShardId             = shardId
            });

            Utility.SHARD_ID = shardId;

            _client.Log += Log;

            string token = "";

            ConfigService.GetConfig().TryGetValue("token2", out token);

            await _restClient.LoginAsync(TokenType.Bot, token);

            //setup DB

            Utility.SORA_VERSION = ConfigService.GetConfigData("version");

            // setup banservice
            _banService = new BanService();

            //Setup Services
            ProfileImageGeneration.Initialize();
            _interactive = new InteractiveService(_client);
            //Instantiate the dependency map and add our services and client to it
            var serviceProvider = ConfigureServices();

            // first setup weebservice
            await serviceProvider.GetRequiredService <WeebService>().InitializeAsync();

            //setup command handler
            await serviceProvider.GetRequiredService <CommandHandler>().InitializeAsync(serviceProvider);

            //SETUP other dependency injection services
            serviceProvider.GetRequiredService <ReminderService>().Initialize();
            serviceProvider.GetRequiredService <WaifuService>().Initialize();
            serviceProvider.GetRequiredService <ProfileService>().Initialize();
            serviceProvider.GetRequiredService <StarboardService>().Initialize();
            serviceProvider.GetRequiredService <SelfAssignableRolesService>().Initialize();
            serviceProvider.GetRequiredService <RatelimitingService>().SetTimer();


            //Set up an event handler to execute some state-reliant startup tasks
            _client.Ready += async() =>
            {
                SentryService.Install(_client);
            };


            //Connect to Discord
            await _client.LoginAsync(TokenType.Bot, token);

            await _client.StartAsync();

            // initialize Autoreconnect Feature
            _autoReconnectService = new AutoReconnectService(_client, LogPretty);

            // setup ban users
            _banService.FetchBannedUsers();

            //INITIALIZE CACHE
            CacheService.Initialize();

            //build webserver and inject service
            try
            {
                int port = int.Parse(ConfigService.GetConfigData("port"));
                var host = new WebHostBuilder()
                           .UseKestrel()                                               // MVC webserver is called Kestrel when self hosting
                           .UseUrls("http://*****:*****@"/web/") // Required to be set and exist. Create web folder in the folder the bot runs from. Folder can be empty.
                           .UseWebRoot(Directory.GetCurrentDirectory() + @"/web/")     // Same as above.
                           .UseStartup <Startup>()                                     // Use Startup class in Startup.cs
                           .ConfigureServices(services =>
                {
                    services.AddSingleton(_client);         // Injected Discord client
                    services.AddSingleton(_banService);     // Injected Discord client
                    services.AddCors(options =>
                    {
                        options.AddPolicy("AllowLocal", builder => builder.WithOrigins("localhost"));                                                             // Enable CORS to only allow calls from localhost
                    });
                    services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); // Fixes JSON Recursion issues in API response.
                })
                           .Build();                                                                                                                              // Actually creates the webhost
                Console.WriteLine($"WEB API STARTED ON PORT: {port+shardId}");
                await host.RunAsync();                                                                                                                            // Run in tandem to client
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendMessage(e.ToString());
            }

            //Hang indefinitely
            await Task.Delay(-1);
        }
Example #13
0
 public async Task SendSentryMessage([Remainder] string message)
 {
     await SentryService.SendMessage(message);
 }