Пример #1
0
        public static async Task SendImageAsync(this ISocketMessageChannel channel, Image finalQR, string msg = "")
        {
            const string fn = "tmp.png";

            finalQR.Save(fn, ImageFormat.Png);
            await channel.SendFileAsync(fn, msg).ConfigureAwait(false);
        }
Пример #2
0
        public static async Task <IUserMessage> SendImageAsync(ISocketMessageChannel channel, string imageUrl)
        {
            var memoryStream = await FetchImage(imageUrl);

            memoryStream.Seek(0, SeekOrigin.Begin);

            return(await channel.SendFileAsync(memoryStream, $"{imageUrl}"));
        }
Пример #3
0
        public static async Task SendPKMAsync(this ISocketMessageChannel channel, PKM pkm, string msg = "")
        {
            var tmp = Path.Combine(Path.GetTempPath(), Util.CleanFileName(pkm.FileName));

            File.WriteAllBytes(tmp, pkm.DecryptedPartyData);
            await channel.SendFileAsync(tmp, msg).ConfigureAwait(false);

            File.Delete(tmp);
        }
Пример #4
0
 public async Task NotifyAboutLevelAsync(SocketGuildUser user, ISocketMessageChannel channel, long level)
 {
     using (var badge = await _img.GetLevelUpBadgeAsync(user.Nickname ?? user.Username,
                                                        level, user.GetAvatarUrl(), user.Roles.OrderByDescending(x => x.Position).First().Color))
     {
         using (var badgeStream = badge.ToPngStream())
         {
             await channel.SendFileAsync(badgeStream, $"{user.Id}.png");
         }
     }
 }
Пример #5
0
        private async Task SendRandomDragon(List <string> tags, ISocketMessageChannel channel)
        {
            string dragonPath = await dragonManager.GetRandomDragonByTagsAsync(tags);

            if (dragonPath == null)
            {
                await channel.SendMessageAsync("Didn't found any one Dragon that match tags :c Try different or less tags");

                return;
            }
            await channel.SendFileAsync(dragonPath, "owo");
        }
Пример #6
0
        public static async Task SendSourceAsync(this ISocketMessageChannel channel, MessageStructure message)
        {
            if (!message.CanSend)
                throw new ArgumentException("The MessageStructure specified does not contains any valid fields that can send.");

            if (message.FilePath.Exists())
            {
                await channel.SendFileAsync(message.FilePath, message.Text, embed: message.Embed);
                return;
            }

            await channel.SendMessageAsync(message.Text, false, message.Embed);
        }
Пример #7
0
        internal override async Task <ResponseSentArgs> Respond(ISocketMessageChannel channel)
        {
            RestUserMessage msg;

            if (ImageAttachmentFilePath == null)
            {
                msg = await channel.SendMessageAsync(string.Empty, embed : CreateDiscordEmbed());
            }
            else
            {
                msg = await channel.SendFileAsync(ImageAttachmentFilePath, embed : CreateDiscordEmbed());
            }
            return(new ResponseSentArgs(msg));
        }
Пример #8
0
        public static async void SendSpoilerLog(string SpoilerLog, string LogName, ISocketMessageChannel FoundChannel)
        {
            // Wait 20 minutes then write the file to a temp file to send it off
            System.Threading.Thread.Sleep(TimeSpan.FromMinutes(20));
            string fileName = LogName;

            System.IO.File.WriteAllText(fileName, SpoilerLog);
            await FoundChannel.SendFileAsync(fileName);

            // Cleanup
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }
        }
Пример #9
0
        // Show the welcome message
        private async Task ShowWelcomeMessage(SocketGuildUser userJoining)
        {
            var server = await _servers.GetServer(userJoining.Guild);

            if (server.WelcomeUsers)
            {
                _logger.LogInformation("Showing welcome message for {user} in {server}", userJoining.Username, userJoining.Guild.Name);

                var channelId = server.WelcomeChannel;
                if (channelId == 0)
                {
                    return;
                }

                ISocketMessageChannel channel = userJoining.Guild.GetTextChannel(channelId);
                if (channel == null)
                {
                    await _servers.ClearWelcomeChannel(userJoining.Guild.Id);

                    return;
                }

                var welcomeMessages = await _welcomeMessageRepository.GetWelcomeMessagesByServerId(userJoining.Guild.Id);

                if (welcomeMessages.Count < 1)
                {
                    await channel.SendMessageAsync($"{userJoining.Mention} {_settings.WelcomeMessage}");
                }
                else
                {
                    var message = welcomeMessages.RandomItem().Message;
                    message = message.Replace("{username}", userJoining.Username);
                    message = message.Replace("{mention}", userJoining.Mention);

                    await channel.SendMessageAsync(message);
                }

                var background = await _servers.GetBackground(userJoining.Guild.Id);

                var memoryStream = await _bannerImageService.CreateImage(userJoining, background);

                memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                await channel.SendFileAsync(memoryStream, $"{userJoining.Username}.png");
            }
        }
Пример #10
0
 private void WebSocketClient_OnMessage(object sender, MessageEventArgs e)
 {
     try
     {
         //Log.OutputLine(string.Format("Web socket[{0}] received a {1} message: {2} ",this.conversionid, e.IsPing?"Ping":(e.IsText?"Text":"Binary"), e.Data));
         var activitySet = JsonConvert.DeserializeObject <ActivitySet>(e.Data);
         if (activitySet == null || activitySet.Activities == null)
         {
             return;
         }
         var activities = from x in activitySet.Activities where x.From.Id == BotId select x;
         ISocketMessageChannel channel = Program.GetDiscordSocketChannel(ChannelId);
         foreach (Activity activity in activities)
         {
             Log.OutputLine(string.Format("Bot response to conversion{0} channel{1}: {2}", conversionid, ChannelId, GetMessageText(activity)));
             if (null != channel)
             {
                 channel.SendMessageAsync(GetMessageText(activity));
                 Thread.Sleep(20);
             }
             if (activity.Attachments.Count > 0)
             {
                 foreach (Microsoft.Bot.Connector.DirectLine.Attachment att in activity.Attachments)
                 {
                     if ("application/vnd.microsoft.card.hero" == att.ContentType)
                     {
                         RenderHeroCard(att);
                     }
                     else if (IsImage(att.ContentType))
                     {
                         // Send image to DiscordApp.
                         channel.SendFileAsync(att.ContentUrl);
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Log.OutputLine(ex.ToString());
         //ConnectToConversion(true);
     }
 }
Пример #11
0
        private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction)
        {
            //  capture all the naughty eggplants
            if (reaction.Emote.Name == "🍆")
            {
                var account = UserAccounts.GetAccount((SocketUser)reaction.User);
                account.EP += 1;
                UserAccounts.SaveAccounts();
            }
            if (Global.MessageIdToTrack[0].Contains(reaction.MessageId))
            {
                string[] checklist = { "👋" };
                if (checklist.Contains(reaction.Emote.Name))
                {
                    RestUserMessage msg = await channel.SendMessageAsync(":eggplant::sweat_drops:");

                    Global.MessageIdToTrack[1].Add(msg.Id);
                }
            }
            if (Global.MessageIdToTrack[1].Contains(reaction.MessageId))
            {
                string[] checklist = { "👋" };
                if (checklist.Contains(reaction.Emote.Name))
                {
                    RestUserMessage msg = await channel.SendMessageAsync(":eggplant::sweat_drops::sweat_drops:");

                    Global.MessageIdToTrack[2].Add(msg.Id);
                }
            }
            if (Global.MessageIdToTrack[2].Contains(reaction.MessageId))
            {
                string[] checklist = { "👋" };
                if (checklist.Contains(reaction.Emote.Name))
                {
                    await channel.SendFileAsync("Resources/emotes/" + "judge.png");

                    await channel.SendMessageAsync("GOD IS WATCHING");
                }
            }
        }
Пример #12
0
        private static async Task SendLogToChannelAsync(ISocketMessageChannel channel, string id)
        {
            var file = Path.Combine("Logs", id + ".txt");

            if (!File.Exists(file))
            {
                file = Path.Combine("Logs", "Archive", id + ".txt");
            }
            if (!File.Exists(file))
            {
                file = Path.Combine("Logs", "Failed", id + ".txt");
            }

            if (File.Exists(file))
            {
                await channel.TriggerTypingAsync();

                try
                {
                    await DecksiteApi.UploadLogAsync(int.Parse(id));

                    await channel.SendMessageAsync($"https://logs.pennydreadfulmagic.com/match/{id}/");
                }
                catch (Exception e)
                {
                    var contents = File.ReadAllLines(file);
                    var caption  = $"Format={contents[0]}, Comment=\"{contents[1]}\", Players=[{contents[3]}]";
                    await channel.SendFileAsync(file, caption);

                    Console.WriteLine($"Couldn't upload to logsite, {e}");
                }
            }
            else
            {
                await channel.TriggerTypingAsync();

                await channel.SendMessageAsync($"Could not find log for MatchID {id}");
            }
        }
Пример #13
0
        public async Task NotifyAboutLevelAsync(SocketGuildUser user, ISocketMessageChannel channel, long level)
        {
            using (var badge = await _img.GetLevelUpBadgeAsync(user.Nickname ?? user.Username,
                                                               level, user.GetAvatarUrl() ?? "https://i.imgur.com/xVIMQiB.jpg", user.Roles.OrderByDescending(x => x.Position).First().Color))
            {
                using (var badgeStream = badge.ToPngStream())
                {
                    await channel.SendFileAsync(badgeStream, $"{user.Id}.png");
                }
            }

            using (var dba = new Database.AnalyticsContext(_config))
            {
                dba.UsersData.Add(new Database.Models.Analytics.UserAnalytics
                {
                    Value       = level,
                    UserId      = user.Id,
                    GuildId     = user.Guild.Id,
                    MeasureDate = DateTime.Now,
                    Type        = Database.Models.Analytics.UserAnalyticsEventType.Level
                });
                dba.SaveChanges();
            }
        }
Пример #14
0
        public static async void RenderImage(SocketUser user, ISocketMessageChannel channel)
        {
            RestUserMessage loader = await channel.SendMessageAsync("", false, LoadingMessage().Build());

            var    account  = UserInfoClasses.GetAccount(user);
            string username = Shorten_Long_Strings(user.Username, 32);

            //Establish other variables of the user's data
            string level             = $"{account.Level}";
            int    total_exp         = account.Total_Exp;
            string pmedals           = $"{account.P_Medals}";
            string proficiency_title = Core.LevelSystem.SocialStats.ProficiencyRankTitle(account.Proficiency_Rank);
            string diligence_title   = Core.LevelSystem.SocialStats.DiligenceRankTitle(account.Diligence_Rank);
            string expression_title  = Core.LevelSystem.SocialStats.ExpressionRankTitle(account.Expression_Rank);

            //Determine the Next Exp value
            int next_exp = 0;

            if (account.Level != 99)
            {
                next_exp = Core.LevelSystem.Leveling.CalculateExp(account.Level + 1) - account.Total_Exp;
            }

            Bitmap base_template = new Bitmap(template_width, template_height);

            Bitmap chara_bg   = (Bitmap)System.Drawing.Image.FromFile($@"{AssetDirectoryConfig.assetDirectory.assetFolderPath}//Profile//StatusScreens//Decor//Decor_TMS_Tiki_1//chara_bg.png");
            Bitmap ui_overlay = (Bitmap)System.Drawing.Image.FromFile($@"{AssetDirectoryConfig.assetDirectory.assetFolderPath}//Profile//StatusScreens//Decor//Decor_TMS_Tiki_1//ui_overlay.png");

            using (Graphics graphics = Graphics.FromImage(base_template))
            {
                graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

                graphics.DrawImage(chara_bg, 0, 0, template_width, template_height);
                graphics.DrawImage(ui_overlay, 0, 0, template_width, template_height);

                graphics.DrawImage(RenderFont(user, account), 0, 0, template_width, template_height);
                graphics.DrawImage(RenderLevelProgressBar(user), 0, 0, template_width, template_height);
                graphics.DrawImage(CombineSocialStatRankBitmaps(account), 0, 0, template_width, template_height);

                if (account.Level_Resets > 0)
                {
                    graphics.DrawImage(RenderPrestigeCounter(account.Level_Resets), 0, 0, template_width, template_height);
                }
            }

            MemoryStream memoryStream = new MemoryStream();

            base_template.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
            memoryStream.Seek(0, SeekOrigin.Begin);

            try
            {
                await channel.SendFileAsync(memoryStream, $"status_{user.Id}_{DateTime.UtcNow}.png");
            }
            catch (Exception ex)
            {
                _ = ErrorHandling.Scene_Upload_Failed(user, channel);
                Console.WriteLine(ex);

                memoryStream.Dispose();
                await loader.DeleteAsync();

                return;
            }

            memoryStream.Dispose();
            await loader.DeleteAsync();
        }
        public static async void RenderImage(SocketUser user, ISocketMessageChannel channel)
        {
            // Send a loading message while the status screen gets made
            RestUserMessage loader = await channel.SendMessageAsync("", false, LoadingMessage().Build());

            try
            {
                var account = UserInfoClasses.GetAccount(user);

                string username = Shorten_Long_Strings(user.Username, 24);

                //Establish other variables of the user's data
                string level             = $"{account.Level}";
                int    total_exp         = account.Total_Exp;
                string profile_picture   = user.GetAvatarUrl();
                string pmedals           = $"{account.P_Medals}";
                string proficiency_title = Core.LevelSystem.SocialStats.ProficiencyRankTitle(account.Proficiency_Rank);
                string diligence_title   = Core.LevelSystem.SocialStats.DiligenceRankTitle(account.Diligence_Rank);
                string expression_title  = Core.LevelSystem.SocialStats.ExpressionRankTitle(account.Expression_Rank);

                //Determine the Next Exp value
                int next_exp = 0;
                if (account.Level != 99)
                {
                    next_exp = Core.LevelSystem.Leveling.CalculateExp(account.Level + 1) - account.Total_Exp;
                }

                //If the user doesn't have a profile picture, use a default one
                if (profile_picture == null)
                {
                    profile_picture = "https://i.imgur.com/T0AjCLh.png";
                }

                // Create a base bitmap to render all the elements on
                Bitmap base_template = new Bitmap(template_width, template_height);

                //Copy the status template to a bitmap
                Bitmap layer_1 = (Bitmap)System.Drawing.Image.FromFile($@"{AssetDirectoryConfig.assetDirectory.assetFolderPath}//Profile//StatusScreens//Decor//Decor_TMS_GamePad_1//layer_1.png");
                Bitmap layer_4 = (Bitmap)System.Drawing.Image.FromFile($@"{AssetDirectoryConfig.assetDirectory.assetFolderPath}//Profile//StatusScreens//Decor//Decor_TMS_GamePad_1//layer_4.png");


                //Use a graphics object to edit the bitmap
                using (Graphics graphics = Graphics.FromImage(base_template))
                {
                    //Set text rendering to have antialiasing
                    graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

                    // Create color and brush
                    System.Drawing.Color tms_white  = System.Drawing.Color.White;
                    System.Drawing.Color tms_pink   = System.Drawing.Color.FromArgb(233, 125, 174);
                    System.Drawing.Color tms_yellow = System.Drawing.Color.FromArgb(255, 255, 3);
                    System.Drawing.Color tms_green  = System.Drawing.Color.FromArgb(0, 207, 0);

                    // Draw the first bitmap layer to the template
                    graphics.DrawImage(layer_1, 0, 0, layer_1.Width, layer_1.Height);

                    graphics.DrawImage(RenderLevelProgressBar(user), 0, 0, template_width, template_height);

                    //Use a web client to download the user's profile picture and draw it to the template
                    using (var wc = new WebClient())
                    {
                        using (var imgStream = new MemoryStream(wc.DownloadData(profile_picture)))
                        {
                            using (var objImage = System.Drawing.Image.FromStream(imgStream))
                            {
                                graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
                                graphics.DrawImage(objImage, 1610, 18, 288, 288);
                            }
                        }
                    }

                    graphics.DrawImage(RenderServerLocationLayer(channel), 0, 0, template_width, template_height);

                    graphics.DrawImage(RenderRoleColorLayer(user), 0, 0, template_width, template_height);

                    graphics.DrawImage(layer_4, 0, 0, template_width, template_height);

                    graphics.DrawImage(RenderFont(user, channel, account), 0, 0, template_width, template_height);

                    graphics.DrawImage(CombineSocialStatRankBitmaps(account), 0, 0, template_width, template_height);

                    if (account.Level_Resets > 0)
                    {
                        graphics.DrawImage(RenderPrestigeCounter(account.Level_Resets), 0, 0, template_width, template_height);
                    }
                }

                //Save the bitmap to a data stream
                MemoryStream memoryStream = new MemoryStream();
                base_template.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
                memoryStream.Seek(0, SeekOrigin.Begin);

                //Send the image
                await channel.SendFileAsync(memoryStream, $"status_{user.Id}_{DateTime.UtcNow}.png");

                //Delete the loading message
                await loader.DeleteAsync();
            }
            catch (Exception ex)
            {
                _ = ErrorHandling.Scene_Upload_Failed(user, channel);
                Console.WriteLine(ex);

                //Delete the loading message
                await loader.DeleteAsync();

                return;
            }
        }
Пример #16
0
        public async Task AssignLeagueFARoles(ISocketMessageChannel channel, IGuild guild)
        {
            int remaining = _latestValues.Where(x => x[0].ToString() != "").Count();
            Dictionary <string, int> _assignedCounters = new Dictionary <string, int>();
            var message = await channel.SendMessageAsync("", false, Embeds.AssigningLeagueRoles(remaining, _assignedCounters));

            await GetLatestValues().ConfigureAwait(false);

            string errorLog = "";

            for (int row = 1; row < _latestValues.Count; row++)
            {
                var signup = _latestValues[row];
                if (signup[(int)ColumnIDs.Discord].ToString() == "")
                {
                    continue;
                }

                ulong discordId = ulong.Parse(signup[(int)ColumnIDs.Discord].ToString());
                if (signup[(int)ColumnIDs.ApplicationStatus].ToString() != "Approved and Notified")
                {
                    continue;
                }
                string league = signup[(int)ColumnIDs.League].ToString();



                var user = await guild.GetUserAsync(discordId);

                if (user is null)
                {
                    errorLog += $"{signup[(int)ColumnIDs.Name]}: User left Discord\r\n";
                    continue;
                }
                if (user.RoleIds.Any(x => x == 472145107056066580))
                {
                    league = "GM (Skipped)";
                }

                if (_assignedCounters.ContainsKey(league))
                {
                    _assignedCounters[league]++;
                }
                else
                {
                    _assignedCounters.Add(league, 1);
                }

                if (league == "GM (Skipped)")
                {
                    continue;
                }

                try
                {
                }
                catch (Exception ex)
                {
                    if (ex.Message.ToLower().Contains("forbidden"))
                    {
                        errorLog += $"{signup[(int)ColumnIDs.Name]}: Permission Error\r\n";
                    }
                    else
                    {
                        errorLog += $"{signup[(int)ColumnIDs.Name]}: {ex.Message}\r\n";
                    }
                }

                remaining--;

                if (row % 100 == 0)
                {
                    await message.ModifyAsync(x =>
                                              x.Embed = Embeds.AssigningLeagueRoles(remaining, _assignedCounters)
                                              );
                }

                await Task.Delay(1500);
            }

            await message.ModifyAsync(
                x => x.Embed = Embeds.AssigningLeagueRoles(remaining, _assignedCounters)
                );


            if (errorLog.Length > 2000)
            {
                File.WriteAllText(@"./DiscordErrorLog.log", errorLog);
                await channel.SendFileAsync(@"./DiscordErrorLog.log", "");
            }
            else
            {
                await channel.SendMessageAsync("", false, Embeds.ErrorLog(errorLog)).ConfigureAwait(false);
            }
        }
Пример #17
0
        internal static async void RenderImage(SocketUser user, ISocketMessageChannel channel)
        {
            RestUserMessage loader = await channel.SendMessageAsync("", false, LoadingMessage().Build());

            // Place the bulk of the function in a try-catch block in case something fails and an error message needs to be sent
            try
            {
                // Grab the user's account information
                var account = UserInfoClasses.GetAccount(user);

                //Establish variables to write on the template
                string username = "";

                //If the username is over 12 characters, replace the last parts with an ellipsis
                if (user.Username.Length > 12)
                {
                    username = $"{username.Substring(0, 12)}...";
                }
                else
                {
                    username = $"{user.Username}";
                }

                //Establish other variables of the user's data
                string level             = $"{account.Level}";
                string profile_picture   = user.GetAvatarUrl();
                string pmedals           = $"{account.P_Medals}";
                string proficiency_title = Core.LevelSystem.SocialStats.ProficiencyRankTitle(account.Proficiency_Rank);
                string diligence_title   = Core.LevelSystem.SocialStats.DiligenceRankTitle(account.Diligence_Rank);
                string expression_title  = Core.LevelSystem.SocialStats.ExpressionRankTitle(account.Expression_Rank);

                //Determine the Next Exp value
                int next_exp = 0;
                if (account.Level != 99)
                {
                    next_exp = Core.LevelSystem.Leveling.CalculateExp(account.Level + 1) - account.Total_Exp;
                }

                //If the user doesn't have a profile picture, use a default one
                if (profile_picture == null)
                {
                    profile_picture = "https://i.imgur.com/T0AjCLh.png";
                }

                // Create a base bitmap to render all the elements on
                Bitmap p4_template = new Bitmap(1920, 1080);

                //Copy the P4 status background to a bitmap
                Bitmap base_layer = (Bitmap)System.Drawing.Image.FromFile($@"{AssetDirectoryConfig.assetDirectory.assetFolderPath}//Profile//StatusScreens//Default//P4//layer_1.png");

                //Copy the P4 status info fields to a bitmap
                Bitmap info_layer = (Bitmap)System.Drawing.Image.FromFile($@"{AssetDirectoryConfig.assetDirectory.assetFolderPath}//Profile//StatusScreens//Default//P4//layer_2.png");

                //Copy the plot point overlay to a bitmap
                Bitmap graph_overlay = (Bitmap)System.Drawing.Image.FromFile($@"{AssetDirectoryConfig.assetDirectory.assetFolderPath}//Profile//StatusScreens//Default//P4//layer_3.png");

                //Copy the P-Medal icon to a bitmap
                Bitmap pmedal_icon = (Bitmap)System.Drawing.Image.FromFile($@"{AssetDirectoryConfig.assetDirectory.assetFolderPath}//Profile//StatusScreens//Default//P4//pmedal_icon.png");

                //Use a graphics object to edit the bitmap
                using (Graphics graphics = Graphics.FromImage(p4_template))
                {
                    //Set text rendering to have antialiasing
                    graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

                    // Draw the first bitmap layer to the template
                    graphics.DrawImage(base_layer, 0, 0, base_layer.Width, base_layer.Height);

                    //Draw the randomized elements to the template first
                    graphics.DrawImage(RandomizeWaveAndWindow(), 0, 0, 1920, 1080);

                    //Draw the information fields
                    graphics.DrawImage(info_layer, 0, 0, 1920, 1080);

                    //Using a font object, draw the user's username value to the template
                    using (Font p4g_font = new Font("P4G", 37))
                    {
                        graphics.DrawString(username, p4g_font, System.Drawing.Brushes.Black, new Point(276, 139));
                    }

                    //Create text boxes to place the user's level and P-Medal values in
                    Rectangle level_box    = new Rectangle(70, 84, 210, 100);
                    Rectangle pmedal_box   = new Rectangle(50, 180, 210, 100);
                    Rectangle next_exp_box = new Rectangle(575, 222, 1000, 100);

                    //Create new colors to shade the level and P-Medal values with
                    System.Drawing.Color level_color  = System.Drawing.Color.FromArgb(255, 247, 130);
                    System.Drawing.Color pmedal_color = System.Drawing.Color.FromArgb(225, 108, 1);

                    //Create new brushes so that the colors can be used on a font object
                    SolidBrush level_brush  = new SolidBrush(level_color);
                    SolidBrush pmedal_brush = new SolidBrush(pmedal_color);

                    //Using a font object, draw the user's level value to the template
                    using (Font p4g_stats_font = new Font("P4G Stats", 68))
                    {
                        //Format the string so that its placement is on the right side of the text box
                        StringFormat stringFormat = new StringFormat();
                        stringFormat.Alignment = StringAlignment.Far;

                        graphics.DrawString(level, p4g_stats_font, level_brush, level_box, stringFormat);
                    }

                    //Draw P-Medal text and graphic information within this font object
                    using (Font p4g_stats_font = new Font("P4G Stats", 48))
                    {
                        //Format the string so that its placement is on the right side of the text box
                        StringFormat stringFormat = new StringFormat();
                        stringFormat.Alignment = StringAlignment.Far;

                        //If the user's P-Medal count has 2 or less digits, draw the P-Medal icon in a specific place
                        if (pmedals.Length <= 2)
                        {
                            graphics.DrawImage(pmedal_icon, 85, 189, 72, 52);
                        }
                        //Else, if the user's P-Medal count has 3 digits, draw the P-Medal icon in a different place
                        else if (pmedals.Length == 3)
                        {
                            graphics.DrawImage(pmedal_icon, 55, 189, 72, 52);
                        }

                        //Draw the user's P-Medal value to the screen
                        graphics.DrawString(pmedals, p4g_stats_font, pmedal_brush, pmedal_box, stringFormat);
                    }

                    //Draw the user's next EXP value to the template within this font object
                    using (Font p4g_stats_font = new Font("P4G Stats", 47))
                    {
                        //Format the string so that its placement is on the left side of the text box
                        StringFormat stringFormat = new StringFormat();
                        stringFormat.Alignment = StringAlignment.Near;

                        graphics.DrawString($"{next_exp}", p4g_stats_font, System.Drawing.Brushes.Black, next_exp_box, stringFormat);
                    }

                    //Create text boxes to draw the social link rank titles
                    Rectangle proficiency_title_box = new Rectangle(1163, 233, 309, 53);
                    Rectangle diligence_title_box   = new Rectangle(834, 860, 309, 53);
                    Rectangle expression_title_box  = new Rectangle(1493, 859, 309, 53);

                    //Draw the rank titles onto the template
                    using (Font p4g_font = new Font("P4G", 31))
                    {
                        //Format the strings so that their placements are at the center of the text boxes
                        StringFormat stringFormat = new StringFormat();
                        stringFormat.Alignment = StringAlignment.Center;

                        graphics.DrawString(proficiency_title, p4g_font, System.Drawing.Brushes.White, proficiency_title_box, stringFormat);
                        graphics.DrawString(diligence_title, p4g_font, System.Drawing.Brushes.White, diligence_title_box, stringFormat);
                        graphics.DrawString(expression_title, p4g_font, System.Drawing.Brushes.White, expression_title_box, stringFormat);
                    }

                    //Create points that define radar chart
                    Point proficiency_point = ProficiencyGraphPoint(account.Proficiency_Rank);
                    Point diligence_point   = DiligenceGraphPoint(account.Diligence_Rank);
                    Point expression_point  = ExpressionGraphPoint(account.Expression_Rank);

                    //Create rectangles for large endpoints that emphasize where the radar points are
                    Rectangle proficiency_endpoint = ProficiencyEndpoint(account.Proficiency_Rank);
                    Rectangle diligence_endpoint   = DiligenceEndpoint(account.Diligence_Rank);
                    Rectangle expression_endpoint  = ExpressionEndpoint(account.Expression_Rank);

                    //Create a color for the radar chart
                    SolidBrush orangeBrush = new SolidBrush(System.Drawing.Color.Orange);

                    //Bind radar chart points
                    Point[] curvePoints = { proficiency_point, diligence_point, expression_point };

                    //Draw radar chart to screen
                    graphics.FillPolygon(orangeBrush, curvePoints);

                    //Draw the plot point overlay to the template
                    graphics.DrawImage(graph_overlay, 0, 0, 1920, 1080);

                    //Create a black pen to draw large endpoints over the plot point overlay
                    System.Drawing.Pen blackPen = new System.Drawing.Pen(System.Drawing.Color.Black, 10);

                    //Draw the large endpoints to the template
                    graphics.DrawEllipse(blackPen, proficiency_endpoint);
                    graphics.DrawEllipse(blackPen, diligence_endpoint);
                    graphics.DrawEllipse(blackPen, expression_endpoint);

                    //Use a web client to download the user's profile picture and draw it to the template
                    using (var wc = new WebClient())
                    {
                        using (var imgStream = new MemoryStream(wc.DownloadData(profile_picture)))
                        {
                            using (var objImage = System.Drawing.Image.FromStream(imgStream))
                            {
                                graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
                                graphics.DrawImage(objImage, 250, 447, 440, 440);
                            }
                        }
                    }

                    // If the user has ever reset their level, render a prestige counter to the template
                    if (account.Level_Resets > 0)
                    {
                        graphics.DrawImage(RenderPrestigeCounter(account.Level_Resets), 0, 0, 1920, 1080);
                    }
                }

                //Save the bitmap to a data stream
                MemoryStream memoryStream = new MemoryStream();
                p4_template.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
                memoryStream.Seek(0, SeekOrigin.Begin);

                //Send the image
                await channel.SendFileAsync(memoryStream, $"status_{user.Id}_{DateTime.UtcNow}.png");

                //Delete the loading message
                await loader.DeleteAsync();
            }
            catch (Exception ex)
            {
                //Send an error message to the user
                _ = ErrorHandling.Scene_Upload_Failed(user, channel);
                Console.WriteLine(ex);

                //Delete the loading message
                await loader.DeleteAsync();

                return;
            }
        }
Пример #18
0
        public async Task PostSuperChat(ISocketMessageChannel channel, ulong fromId, ulong toId, int amount, string message, IDMChannel fromDmChannel, IDMChannel toDmChannel)
        {
            var fromMember = DbContext.VetMembers.FirstOrDefault(c => c.DiscordId == fromId);

            if (fromMember == null)
            {
                await fromDmChannel.SendMessageAsync("VetCoin 登録者以外はSuperChatを送信できません");

                return;
            }

            var fromAmount = CoreService.CalcAmount(fromMember);

            if (fromAmount < amount)
            {
                await fromDmChannel.SendMessageAsync($"VEC残高が不足しています。({fromAmount}VEC)");

                return;
            }

            if (amount < 100)
            {
                await fromDmChannel.SendMessageAsync($"送金下限は100VECです。それ未満は送れません");

                return;
            }


            if (amount > 50000)
            {
                await fromDmChannel.SendMessageAsync($"送金上限は50000VECです。それ以上は送れません");

                return;
            }

            var toMember = DbContext.VetMembers.FirstOrDefault(c => c.DiscordId == toId);

            if (toMember == null)
            {
                await fromDmChannel.SendMessageAsync("VetCoin 登録者以外へはSuperChatを送信できません");

                return;
                //toMember = DbContext.VetMembers.FirstOrDefault(c => c.DiscordId == 287434171570192384);
            }

            try
            {
                await fromDmChannel.SendMessageAsync($@"{toMember.Name}へ{amount}VEC 送金しました");

                await toDmChannel.SendMessageAsync($@"{fromMember.Name}から{amount}VEC をもらいました(SuperChat)");

                DbContext.CoinTransactions.Add(new CoinTransaction
                {
                    SendeVetMemberId   = fromMember.Id,
                    Amount             = amount,
                    RecivedVetMemberId = toMember.Id,
                    Text            = message,
                    TransactionType = CoinTransactionType.SuperChat,
                });
                await DbContext.SaveChangesAsync();
            }
            catch
            {
                await fromDmChannel.SendMessageAsync("システムトラブルの可能性があります。開発者に問い合わせをお願いします。");

                return;
            }

            try
            {
                var imageMs = await CreateImage(fromMember, toMember, amount);

                await channel.SendFileAsync(imageMs, $"Send{amount}.png", message);
            }
            catch
            {
                await fromDmChannel.SendMessageAsync("システムトラブルの可能性があります。開発者に問い合わせをお願いします。(送金は成功しています)");
            }
        }
        internal override async Task <ResponseSentArgs> Respond(ISocketMessageChannel channel)
        {
            RestUserMessage msg = await channel.SendFileAsync(filePath, content);

            return(new ResponseSentArgs(msg));
        }
Пример #20
0
        public static async void MessagePassed(SocketMessage message)
        {
            // Validate that this is a valid settings string
            var resp = RunPython("--output_settings  --convert_settings --settings_string " + message.Content.Replace("<@!782757480887091260>", "").Trim());

            if (resp.Item1)
            {
                // Parse the spoiler log
                JObject Settings = JObject.Parse(resp.Item2);
                // Update some defaults
                Settings["compress_rom"]         = "Patch";
                Settings["create_spoiler"]       = true;
                Settings["create_cosmetics_log"] = false;
                // Create a temp settings file
                string fileName = Path.GetDirectoryName(OoTDirectory) + "/" + Guid.NewGuid().ToString();
                System.IO.File.WriteAllText(fileName, Settings.ToString());
                // Generate a seed using our settings file
                var GeneratedSeedResponse = RunPython("--settings " + fileName);
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                // Find the channels set by the config files
                ISocketMessageChannel FoundChannel   = null;
                ISocketMessageChannel SpoilerChannel = null;
                var chan = message.Channel as SocketGuildChannel;
                foreach (var gchan in chan.Guild.Channels)
                {
                    if (gchan.Name.ToLower() == Channel.ToLower())
                    {
                        FoundChannel = gchan as ISocketMessageChannel;
                    }
                    if (gchan.Name.ToLower() == SpoilChannel.ToLower())
                    {
                        SpoilerChannel = gchan as ISocketMessageChannel;
                    }
                }

                if (FoundChannel != null)
                {
                    // Parse the spoiler log for related settings
                    var SpoilerInfo = GetSpoilerInfo(System.IO.File.ReadAllText(Path.GetDirectoryName(GeneratedSeedResponse.Item4) + @"/" + GeneratedSeedResponse.Item3));

                    string BuiltMessage = "";
                    // Create the message to send
                    BuiltMessage += "**Seed Posted by**: `" + message.Author + "`\n";
                    if (SpoilerInfo.Item2 != null)
                    {
                        BuiltMessage += "**Settings String**: `" + SpoilerInfo.Item4 + "`\n";
                        BuiltMessage += "**Version**: `" + SpoilerInfo.Item5 + "`\n";
                        BuiltMessage += "**Seed Settings**: ```" + SpoilerInfo.Item1 + "```";
                    }
                    BuiltMessage += "\nWas this a good seed? Vote using thumbs up or down. You can abstain from voting.";
                    BuiltMessage += "\nYou can patch your OoT file at: https://ootrandomizer.com/generator";
                    var sentmessage = await FoundChannel.SendMessageAsync(BuiltMessage);

                    // Send the rest of the data
                    await FoundChannel.SendFileAsync(GeneratedSeedResponse.Item4);

                    await sentmessage.AddReactionsAsync(new[] { new Emoji("👍"), new Emoji("👎") });

                    await message.Channel.SendMessageAsync("Seed info has been posted to #seed-info");

                    // Read in the spoiler log into memory so we don't store it on disk
                    var SpoilerText = File.ReadAllText(Path.GetDirectoryName(GeneratedSeedResponse.Item4) + @"/" + GeneratedSeedResponse.Item3);
                    _ = Task.Run(() => SendSpoilerLog(SpoilerText, GeneratedSeedResponse.Item3, SpoilerChannel));
                    // Cleanup the files
                    if (File.Exists(Path.GetDirectoryName(GeneratedSeedResponse.Item4) + @"/" + GeneratedSeedResponse.Item3))
                    {
                        File.Delete(Path.GetDirectoryName(GeneratedSeedResponse.Item4) + @"/" + GeneratedSeedResponse.Item3);
                    }
                    if (File.Exists(GeneratedSeedResponse.Item4))
                    {
                        File.Delete(GeneratedSeedResponse.Item4);
                    }
                }
                else
                {
                    await message.Channel.SendMessageAsync("seed-info Channel does not exist.");
                }
            }
            else
            {
                await message.Channel.SendMessageAsync("That is not a valid settings string.");
            }
        }
Пример #21
0
        public async Task PostSuperChat(ISocketMessageChannel channel, ulong fromId, ulong toId, int amount, string message, IDMChannel fromDmChannel, IDMChannel toDmChannel)
        {
            var fromMember = DbContext.VetMembers.FirstOrDefault(c => c.DiscordId == fromId);

            if (fromMember == null)
            {
                await fromDmChannel.SendMessageAsync("VetCoin 登録者以外はSuperChatを送信できません");

                return;
            }

            var fromAmount = CoreService.CalcAmount(fromMember);

            if (fromAmount < amount)
            {
                await fromDmChannel.SendMessageAsync($"{StaticSettings.CurrenryUnit}残高が不足しています。({fromAmount}{StaticSettings.CurrenryUnit})");

                return;
            }

            if (amount < StaticSettings.SuperChatLowLimit)
            {
                await fromDmChannel.SendMessageAsync($"送金下限は{StaticSettings.SuperChatLowLimit}{StaticSettings.CurrenryUnit}です。それ未満は送れません");

                return;
            }


            if (amount > StaticSettings.SuperChatHeightLimit)
            {
                await fromDmChannel.SendMessageAsync($"送金上限は{StaticSettings.SuperChatHeightLimit}{StaticSettings.CurrenryUnit}です。それ以上は送れません");

                return;
            }

            var toMember = DbContext.VetMembers.FirstOrDefault(c => c.DiscordId == toId);

            if (toMember == null)
            {
                await fromDmChannel.SendMessageAsync("VetCoin 登録者以外へはSuperChatを送信できません");

                return;
                //toMember = DbContext.VetMembers.FirstOrDefault(c => c.DiscordId == 287434171570192384);
            }

            var toAmount = CoreService.CalcAmount(toMember);

            if (toMember.Id == fromMember.Id)
            {   //念のため同一人物の対応
                toAmount   -= amount;
                fromAmount += amount;
            }

            try
            {
                if (fromDmChannel != null)
                {
                    await fromDmChannel.SendMessageAsync($@"SuperChat:{toMember.Name}へ{amount}{StaticSettings.CurrenryUnit} 送金しました [{fromAmount - amount}{StaticSettings.CurrenryUnit}]");
                }

                if (toDmChannel != null)
                {
                    await toDmChannel.SendMessageAsync($@"SuperChat:{fromMember.Name}から{amount}{StaticSettings.CurrenryUnit} をもらいました [{toAmount + amount}{StaticSettings.CurrenryUnit}]");
                }

                DbContext.CoinTransactions.Add(new CoinTransaction
                {
                    SendeVetMemberId   = fromMember.Id,
                    Amount             = amount,
                    RecivedVetMemberId = toMember.Id,
                    Text            = message,
                    TransactionType = CoinTransactionType.SuperChat,
                });
                await DbContext.SaveChangesAsync();
            }
            catch
            {
                await fromDmChannel.SendMessageAsync("システムトラブルの可能性があります。開発者に問い合わせをお願いします。");

                return;
            }

            try
            {
                var imageMs = await CreateImage(fromMember, toMember, amount);

                await channel.SendFileAsync(imageMs, $"Send{amount}.png", message);
            }
            catch
            {
                await fromDmChannel.SendMessageAsync("システムトラブルの可能性があります。開発者に問い合わせをお願いします。(送金は成功しています)");
            }
        }
Пример #22
0
 public async Task <RestUserMessage> SendImage(ISocketMessageChannel channel, DownloadedImage image, string additionalText)
 {
     return(await channel.SendFileAsync(image.ImageData, image.Filename, string.IsNullOrEmpty(additionalText)?null : additionalText.Trim()));
 }
Пример #23
0
        internal static async void RenderImage(SocketUser user, ISocketMessageChannel channel)
        {
            // Send a loading message while the status screen gets made
            RestUserMessage loader = await channel.SendMessageAsync("", false, LoadingMessage().Build());

            // Place the bulk of the function in a try-catch block in case something fails and an error message needs to be sent
            try
            {
                //Grab the user's account information
                var account = UserInfoClasses.GetAccount(user);

                //Establish variables to write on the template
                string username = "";

                //If the username is over 12 characters, replace the last parts with an ellipsis
                if (user.Username.Length > 12)
                {
                    username = $"{username.Substring(0, 12)}...";
                }
                else
                {
                    username = $"{user.Username}";
                }

                //Establish other variables of the user's data
                string level             = $"{account.Level}";
                int    total_exp         = account.Total_Exp;
                string profile_picture   = user.GetAvatarUrl();
                string pmedals           = $"{account.P_Medals}";
                string proficiency_title = Core.LevelSystem.SocialStats.ProficiencyRankTitle(account.Proficiency_Rank);
                string diligence_title   = Core.LevelSystem.SocialStats.DiligenceRankTitle(account.Diligence_Rank);
                string expression_title  = Core.LevelSystem.SocialStats.ExpressionRankTitle(account.Expression_Rank);

                //Determine the Next Exp value
                int next_exp = 0;
                if (account.Level != 99)
                {
                    next_exp = Core.LevelSystem.Leveling.CalculateExp(account.Level + 1) - account.Total_Exp;
                }

                //If the user doesn't have a profile picture, use a default one
                if (profile_picture == null)
                {
                    profile_picture = "https://i.imgur.com/T0AjCLh.png";
                }

                // Create a base bitmap to render all the elements on
                Bitmap p3_template = new Bitmap(1920, 1080);

                //Copy the P3 status template to a bitmap
                Bitmap base_layer = (Bitmap)System.Drawing.Image.FromFile($@"{AssetDirectoryConfig.assetDirectory.assetFolderPath}//Profile//StatusScreens//Default//P3//p3_template.png");

                //Copy the EXP bar to a bitmap
                Bitmap exp_bar = (Bitmap)System.Drawing.Image.FromFile($@"{AssetDirectoryConfig.assetDirectory.assetFolderPath}//Profile//StatusScreens//Default//P3//exp_bar.png");

                //Copy the rank bar to a bitmap
                Bitmap rank_bar = RankBarBitmap();

                //Use a graphics object to edit the bitmap
                using (Graphics graphics = Graphics.FromImage(p3_template))
                {
                    //Set text rendering to have antialiasing
                    graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

                    // Create color and brush
                    System.Drawing.Color dark_blue        = System.Drawing.Color.FromArgb(9, 57, 107);
                    System.Drawing.Color light_blue       = System.Drawing.Color.FromArgb(31, 116, 204);
                    SolidBrush           dark_blue_brush  = new SolidBrush(dark_blue);
                    SolidBrush           light_blue_brush = new SolidBrush(light_blue);

                    // Draw the first bitmap layer to the template
                    graphics.DrawImage(base_layer, 0, 0, base_layer.Width, base_layer.Height);

                    // Draw the rank titles to the bitmap.
                    using (Font p4g_font = new Font("P4G", 37))
                    {
                        graphics.DrawString(proficiency_title, p4g_font, System.Drawing.Brushes.White, new Point(348, 141));
                        graphics.DrawString(diligence_title, p4g_font, System.Drawing.Brushes.White, new Point(348, 280));
                        graphics.DrawString(expression_title, p4g_font, System.Drawing.Brushes.White, new Point(348, 411));
                    }

                    //Draw PLV text
                    using (Font street = new Font("Street Corner Extend", 25))
                    {
                        graphics.DrawString("PLV", street, dark_blue_brush, new Point(190, 613));
                    }

                    //Draw level number
                    using (Font street = new Font("Street Corner Extend", 32))
                    {
                        graphics.DrawString(level, street, dark_blue_brush, new Point(307, 613));
                    }

                    //Draw username
                    using (Font p4g_font = new Font("P4G", 34))
                    {
                        graphics.DrawString(username, p4g_font, dark_blue_brush, new Point(492, 610));
                    }

                    //Draw "Total EXP" & "Next EXP" text, plus total EXP value
                    using (Font street = new Font("Street Corner Extend", 28))
                    {
                        graphics.DrawString("TOTAL EXP", street, dark_blue_brush, new Point(237, 817));
                        graphics.DrawString("NEXT EXP", street, dark_blue_brush, new Point(190, 681));

                        Rectangle    box1         = new Rectangle(550, 817, 362, 46);
                        StringFormat stringFormat = new StringFormat();
                        stringFormat.Alignment     = StringAlignment.Far;
                        stringFormat.LineAlignment = StringAlignment.Far;
                        graphics.DrawString($"{total_exp}", street, dark_blue_brush, box1, stringFormat);
                    }

                    //Draw P-Medal value
                    using (Font street = new Font("Street Corner Extend", 31))
                    {
                        Rectangle    box1         = new Rectangle(817, 743, 190, 42);
                        StringFormat stringFormat = new StringFormat();
                        stringFormat.Alignment     = StringAlignment.Center;
                        stringFormat.LineAlignment = StringAlignment.Center;
                        graphics.DrawString(pmedals, street, light_blue_brush, box1, stringFormat);
                    }

                    //Draw ranks for Proficiency
                    for (int i = 0; i < account.Proficiency_Rank; i++)
                    {
                        graphics.DrawImage(rank_bar, 355 + (94 * i), 123, 87, 14);
                    }

                    //Draw ranks for Diligence
                    for (int i = 0; i < account.Diligence_Rank; i++)
                    {
                        graphics.DrawImage(rank_bar, 355 + (94 * i), 261, 87, 14);
                    }

                    //Draw ranks for Expression
                    for (int i = 0; i < account.Expression_Rank; i++)
                    {
                        graphics.DrawImage(rank_bar, 355 + (94 * i), 393, 87, 14);
                    }

                    // Draw a bitmap where the proper Next EXP progress bar overlaps with the exp_bar decorative image
                    graphics.DrawImage(KeepPixelOverlap(RenderProgressBar(user), exp_bar), 0, 0, 1920, 1080);

                    //Use a web client to download the user's profile picture and draw it to the template
                    using (var wc = new WebClient())
                    {
                        using (var imgStream = new MemoryStream(wc.DownloadData(profile_picture)))
                        {
                            using (var objImage = System.Drawing.Image.FromStream(imgStream))
                            {
                                graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
                                graphics.DrawImage(objImage, 1239, 240, 600, 600);
                            }
                        }
                    }

                    // If the user has ever reset their level, render a prestige counter to the template
                    if (account.Level_Resets > 0)
                    {
                        graphics.DrawImage(RenderPrestigeCounter(account.Level_Resets), 0, 0, 1920, 1080);
                    }
                }

                //Save the bitmap to a data stream
                MemoryStream memoryStream = new MemoryStream();
                p3_template.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
                memoryStream.Seek(0, SeekOrigin.Begin);

                //Send the image
                await channel.SendFileAsync(memoryStream, $"status_{user.Id}_{DateTime.UtcNow}.png");

                //Delete the loading message
                await loader.DeleteAsync();
            }
            catch (Exception ex)
            {
                _ = ErrorHandling.Scene_Upload_Failed(user, channel);
                Console.WriteLine(ex);

                //Delete the loading message
                await loader.DeleteAsync();

                return;
            }
        }