Example #1
0
        public async Task SendVerificationCode(string name, string email, uint packageId)
        {
            Console.WriteLine("mail");
            byte[] random = new byte[9];
            RandomNumberGenerator rand = RandomNumberGenerator.Create();

            rand.GetBytes(random);

            string code = Convert.ToBase64String(random);

            _verificationCodes.Add(packageId, code);
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("Unity Developer Hub", SettingsHandler.LoadValueString("gmail", JsonFile.Settings)));
            message.To.Add(new MailboxAddress(name, email));
            message.Subject = "Unity Developer Hub Package Validation";
            message.Body    = new TextPart("plain")
            {
                Text = @"Here's your validation code : " + code
            };

            using (var client = new SmtpClient())
            {
                await client.ConnectAsync("smtp.gmail.com", 587);

                client.AuthenticationMechanisms.Remove("XOAUTH2");
                await client.AuthenticateAsync("unitydeveloperhub", SettingsHandler.LoadValueString("gmailPassword", JsonFile.Settings));

                await client.SendAsync(message);

                await client.DisconnectAsync(true);
            }

            //TODO: Delete code after 30min
        }
Example #2
0
        public async Task MainAsync()
        {
            _token = SettingsHandler.LoadValueString("token", JsonFile.Settings);

            _client = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel            = LogSeverity.Verbose,
                AlwaysDownloadUsers = true,
                MessageCacheSize    = 50
            });

            _commandService = new CommandService(new CommandServiceConfig()
            {
                CaseSensitiveCommands = false,
                DefaultRunMode        = RunMode.Async
            });
            _loggingService   = new LoggingService(_client);
            _databaseService  = new DatabaseService(_loggingService);
            _publisherService = new PublisherService(_client, _databaseService);
            _animeService     = new AnimeService(_client, _loggingService);
            _updateService    = new UpdateService(_client, _loggingService, _publisherService, _databaseService, _animeService);
            _userService      = new UserService(_databaseService, _loggingService, _updateService);
            _workService      = new WorkService();

            _audioService      = new AudioService(_loggingService, _client);
            _casinoService     = new CasinoService(_loggingService, _updateService, _databaseService);
            _serviceCollection = new ServiceCollection();
            _serviceCollection.AddSingleton(_loggingService);
            _serviceCollection.AddSingleton(_databaseService);
            _serviceCollection.AddSingleton(_userService);
            //_serviceCollection.AddSingleton(_work);
            //TODO: rework work service
            _serviceCollection.AddSingleton(_publisherService);
            _serviceCollection.AddSingleton(_updateService);
            _serviceCollection.AddSingleton(_audioService);
            _serviceCollection.AddSingleton(_animeService);
            _serviceCollection.AddSingleton(_casinoService);
            _services = _serviceCollection.BuildServiceProvider();


            await InstallCommands();

            _client.Log += Logger;

            // await InitCommands();

            await _client.LoginAsync(TokenType.Bot, _token);

            await _client.StartAsync();

            _client.Ready += () =>
            {
                Console.WriteLine("Bot is connected");
                //_audio.Music();
                return(Task.CompletedTask);
            };

            await Task.Delay(-1);
        }
Example #3
0
        public async Task LogAction(string action, bool logToFile = true, bool logToChannel = true, Embed embed = null)
        {
            if (logToChannel)
            {
                var channel = _client.GetChannel(Settings.GetBotAnnouncementChannel()) as ISocketMessageChannel;
                await channel.SendMessageAsync(action, false, embed);
            }

            if (logToFile)
            {
                File.AppendAllText(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) + @"/log.txt",
                                   $"[{DateTime.Now:d/M/yy HH:mm:ss}] {action} {Environment.NewLine}");
            }
        }
Example #4
0
 public DatabaseService(LoggingService logging)
 {
     _connection = SettingsHandler.LoadValueString("dbConnectionString", JsonFile.Settings);
     _logging    = logging;
 }
Example #5
0
 public async Task LogXp(string channel, string user, float baseXp, float bonusXp, float xpReduce, int totalXp)
 {
     File.AppendAllText(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) + @"/logXP.txt",
                        $"[{DateTime.Now:d/M/yy HH:mm:ss}] - {user} gained {totalXp}xp (base: {baseXp}, bonus : {bonusXp}, reduce : {xpReduce}) in channel {channel} {Environment.NewLine}");
 }
Example #6
0
 public static string GetServerRootPath()
 {
     return(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings));
 }
Example #7
0
        //TODO: Add custom commands for user after (30karma ?/limited to 3 ?)

        public UserService(DatabaseService databaseService, LoggingService loggingService, UpdateService updateService)
        {
            rand                    = new Random();
            _databaseService        = databaseService;
            _loggingService         = loggingService;
            _updateService          = updateService;
            _mutedUsers             = new Dictionary <ulong, DateTime>();
            _xpCooldown             = new Dictionary <ulong, DateTime>();
            _canEditThanks          = new HashSet <ulong>(32);
            _thanksCooldown         = new Dictionary <ulong, DateTime>();
            _thanksReminderCooldown = new Dictionary <ulong, DateTime>();
            _codeReminderCooldown   = new Dictionary <ulong, DateTime>();

            _noXpChannels = new List <ulong>
            {
                Settings.GetBotCommandsChannel(),
                    Settings.GetCasinoChannel(),
                    Settings.GetMusicCommandsChannel()
            };

            /*
             * Init font for the profile card
             */
            _fontCollection = new FontCollection();
            _defaultFont    = _fontCollection
                              .Install(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) +
                                       "/fonts/OpenSans-Regular.ttf")
                              .CreateFont(16);
            _nameFont = _fontCollection
                        .Install(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) + "/fonts/Consolas.ttf")
                        .CreateFont(22);
            _levelFont = _fontCollection
                         .Install(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) + "/fonts/Consolas.ttf")
                         .CreateFont(59);
            _levelFontSmall = _fontCollection
                              .Install(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) + "/fonts/Consolas.ttf")
                              .CreateFont(45);

            _subtitlesBlackFont = _fontCollection
                                  .Install(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) + "/fonts/OpenSansEmoji.ttf")
                                  .CreateFont(80);
            _subtitlesWhiteFont = _fontCollection
                                  .Install(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) + "/fonts/OpenSansEmoji.ttf")
                                  .CreateFont(75);

            /*
             * Init XP
             */
            _xpMinPerMessage = SettingsHandler.LoadValueInt("xpMinPerMessage", JsonFile.UserSettings);
            _xpMaxPerMessage = SettingsHandler.LoadValueInt("xpMaxPerMessage", JsonFile.UserSettings);
            _xpMinCooldown   = SettingsHandler.LoadValueInt("xpMinCooldown", JsonFile.UserSettings);
            _xpMaxCooldown   = SettingsHandler.LoadValueInt("xpMaxCooldown", JsonFile.UserSettings);

            /*
             * Init thanks
             */
            StringBuilder sbThanks = new StringBuilder();

            string[] thx = SettingsHandler.LoadValueStringArray("thanks", JsonFile.UserSettings);
            sbThanks.Append("(?i)\\b(");
            for (int i = 0; i < thx.Length; i++)
            {
                sbThanks.Append(thx[i]).Append("|");
            }

            sbThanks.Length--; //Efficiently remove the final pipe that gets added in final loop, simplifying loop
            sbThanks.Append(")\\b");
            _thanksRegex                = sbThanks.ToString();
            _thanksCooldownTime         = SettingsHandler.LoadValueInt("thanksCooldown", JsonFile.UserSettings);
            _thanksReminderCooldownTime = SettingsHandler.LoadValueInt("thanksReminderCooldown", JsonFile.UserSettings);
            _thanksMinJoinTime          = SettingsHandler.LoadValueInt("thanksMinJoinTime", JsonFile.UserSettings);

            /*
             * Init Code analysis
             */
            _codeReminderCooldownTime      = SettingsHandler.LoadValueInt("codeReminderCooldown", JsonFile.UserSettings);
            _codeReminderFormattingExample = (
                @"\`\`\`cs" + Environment.NewLine +
                "Write your code on new line here." + Environment.NewLine +
                @"\`\`\`" + Environment.NewLine + Environment.NewLine +
                "Simple as that! If you'd like me to stop reminding you about this, simply type \"!disablecodetips\"");

            LoadData();
            UpdateLoop();
        }
Example #8
0
        // TODO: Response to people asking if anyone is around to help.

        /*
         * public async Task UselessAskingCheck(SocketMessage messageParam)
         * {
         *  if (messageParam.Author.IsBot)
         *      return;
         *
         *  ulong userId = messageParam.Author.Id;
         *  string content = messageParam.Content;
         * }*/

        //TODO: If Discord ever enables a hook that allows modifying a message during creation of it, then this could be put to use...
        // Disabled for now.

        /*
         * public async Task EscapeMessage(SocketMessage messageParam)
         * {
         *  if (messageParam.Author.IsBot)
         *      return;
         *
         *  ulong userId = messageParam.Author.Id;
         *  string content = messageParam.Content;
         *  //Escape all \, ~, _, ` and * character's so they don't trigger any Discord formatting.
         *  content = content.EscapeDiscordMarkup();
         * }*/

        public async Task <string> SubtitleImage(IMessage message, string text)
        {
            var            attachments = message.Attachments;
            Attachment     file        = null;
            Image <Rgba32> image       = null;

            foreach (var a in attachments)
            {
                if (Regex.Match(a.Filename, @"(.*?)\.(jpg|jpeg|png|gif)$").Success)
                {
                    file = (Attachment)a;
                }
            }

            if (file == null)
            {
                return("");
            }

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    using (HttpResponseMessage response = await client.GetAsync(file.Url))
                    {
                        response.EnsureSuccessStatusCode();

                        byte[] reader = await response.Content.ReadAsByteArrayAsync();

                        image = ImageSharp.Image.Load(reader);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to load image : " + e);
                return("");
            }

            float beginHeight = image.Height - (image.Height * 0.3f);
            float beginWidth  = (image.Width * .10f);
            float totalWidth  = image.Width * .8f;

            //Shitty outline effect
            image.DrawText(text, _subtitlesWhiteFont, Rgba32.Black, new PointF(beginWidth - 4, beginHeight), new TextGraphicsOptions(true)
            {
                WrapTextWidth       = totalWidth,
                HorizontalAlignment = HorizontalAlignment.Center,
            });
            image.DrawText(text, _subtitlesWhiteFont, Rgba32.Black, new PointF(beginWidth + 4, beginHeight), new TextGraphicsOptions(true)
            {
                WrapTextWidth       = totalWidth,
                HorizontalAlignment = HorizontalAlignment.Center
            });
            image.DrawText(text, _subtitlesWhiteFont, Rgba32.Black, new PointF(beginWidth, beginHeight - 4), new TextGraphicsOptions(true)
            {
                WrapTextWidth       = totalWidth,
                HorizontalAlignment = HorizontalAlignment.Center
            });
            image.DrawText(text, _subtitlesWhiteFont, Rgba32.Black, new PointF(beginWidth, beginHeight + 4), new TextGraphicsOptions(true)
            {
                WrapTextWidth       = totalWidth,
                HorizontalAlignment = HorizontalAlignment.Center
            });

            image.DrawText(text, _subtitlesWhiteFont, Rgba32.White, new PointF(beginWidth, beginHeight), new TextGraphicsOptions(true)
            {
                WrapTextWidth       = totalWidth,
                HorizontalAlignment = HorizontalAlignment.Center
            });

            string path = SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) +
                          $"/images/subtitles/{message.Author}-{message.Id}.png";

            image.Save(path, new JpegEncoder {
                Quality = 95
            });

            return(path);
        }
Example #9
0
        public async Task <string> GenerateProfileCard(IUser user)
        {
            var backgroundPath = SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) +
                                 "/images/background.png";
            var foregroundPath = SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) +
                                 "/images/foreground.png";
            Image <Rgba32> profileCard = ImageSharp.Image.Load(backgroundPath);
            Image <Rgba32> profileFg   = ImageSharp.Image.Load(foregroundPath);
            Image <Rgba32> avatar;
            Image <Rgba32> triangle = ImageSharp.Image.Load(
                SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) +
                "/images/triangle.png");
            Stream stream;
            string avatarUrl = user.GetAvatarUrl();
            ulong  userId    = user.Id;

            if (string.IsNullOrEmpty(avatarUrl))
            {
                avatar = ImageSharp.Image.Load(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) +
                                               "/images/default.png");
            }
            else
            {
                try
                {
                    using (var http = new HttpClient())
                    {
                        stream = await http.GetStreamAsync(new Uri(avatarUrl));
                    }

                    avatar = ImageSharp.Image.Load(stream);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    avatar = ImageSharp.Image.Load(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) +
                                                   "/images/default.png");
                }
            }

            uint   xp     = _databaseService.GetUserXp(userId);
            uint   rank   = _databaseService.GetUserRank(userId);
            int    karma  = _databaseService.GetUserKarma(userId);
            uint   level  = _databaseService.GetUserLevel(userId);
            double xpLow  = GetXpLow((int)level);
            double xpHigh = GetXpHigh((int)level);

            const float startX = 104;
            const float startY = 39;
            const float height = 16;
            float       endX   = (float)((xp - xpLow) / (xpHigh - xpLow) * 232f);

            profileCard.DrawImage(profileFg, 100f, new Size(profileFg.Width, profileFg.Height), Point.Empty);

            var   u        = user as IGuildUser;
            IRole mainRole = null;

            foreach (ulong id in u.RoleIds)
            {
                IRole role = u.Guild.GetRole(id);
                if (mainRole == null)
                {
                    mainRole = u.Guild.GetRole(id);
                }
                else if (role.Position > mainRole.Position)
                {
                    mainRole = role;
                }
            }

            Color c = mainRole.Color;

            var brush = new RecolorBrush <Rgba32>(Rgba32.White,
                                                  new Rgba32(c.R, c.G, c.B), .25f);

            triangle.Fill(brush);

            profileCard.DrawImage(triangle, 100f, new Size(triangle.Width, triangle.Height), new Point(346, 17));

            profileCard.Fill(Rgba32.FromHex("#3f3f3f"),
                             new RectangleF(startX, startY, 232, height));              //XP bar background
            profileCard.Fill(Rgba32.FromHex("#00f0ff"),
                             new RectangleF(startX + 1, startY + 1, endX, height - 2)); //XP bar
            profileCard.DrawImage(avatar, 100f, new Size(80, 80), new Point(16, 28));
            profileCard.DrawText(user.Username, _nameFont, Rgba32.FromHex("#3C3C3C"),
                                 new PointF(144, 8));
            profileCard.DrawText(level.ToString(), level < 100 ? _levelFont : _levelFontSmall, Rgba32.FromHex("#3C3C3C"),
                                 new PointF(98, 35));
            profileCard.DrawText("Server Rank        #" + rank, _defaultFont, Rgba32.FromHex("#3C3C3C"),
                                 new PointF(167, 60));
            profileCard.DrawText("Karma Points:    " + karma, _defaultFont, Rgba32.FromHex("#3C3C3C"),
                                 new PointF(167, 77));
            profileCard.DrawText("Total XP:              " + xp, _defaultFont, Rgba32.FromHex("#3C3C3C"),
                                 new PointF(167, 94));

            profileCard.Resize(400, 120);

            profileCard.Save(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) +
                             $"/images/profiles/{user.Username}-profile.png");
            return(SettingsHandler.LoadValueString("serverRootPath", JsonFile.Settings) +
                   $"/images/profiles/{user.Username}-profile.png");
        }