public Color(uint id, string name, Discord.Color color, uint price) { ID = id; Name = name; RightColor = color; Price = price; }
public static Windows.UI.Color ToWinColor(this Discord.Color color) { if (color.RawValue == 0) { return(Windows.UI.Color.FromArgb(0x99, 0xff, 0xff, 0xff)); } return(Windows.UI.Color.FromArgb(0xff, color.R, color.G, color.B)); }
public void GetDiscordColor_White() { var rank = new Rank() { ColorCode = "#ffffff" }; var color = rank.GetDiscordColor(); var colorToCompare = new Discord.Color(255, 255, 255); color.Should().Be(colorToCompare); }
public void GetDiscordColor_Purple() { var rank = new Rank() { ColorCode = "#9134b3" }; var color = rank.GetDiscordColor(); var colorToCompare = new Discord.Color(145, 52, 179); color.Should().Be(colorToCompare); }
public void GetDiscordColor_RedColor() { var rank = new Rank() { ColorCode = "#ff0000" }; var color = rank.GetDiscordColor(); var colorToCompare = new Discord.Color(255, 0, 0); color.Should().Be(colorToCompare); }
public static bool TryParseDiscordColor(string colorString, [NotNullWhen(true)] out Discord.Color color) { try { color = (Discord.Color)ColorTranslator.FromHtml(colorString); return(true); } catch { color = default; return(false); } }
internal void StartupInfo() { CurseDict = fileReader.DESERIALISE_DICT_LIST("Resources/Curses.json"); CurrentCurseList = 1; //!modChannelID = 643313827915759617; //!GOG's MOD CHANNEL modChannelID = 694015797340667914; // CONCRETE's MOD CHANNEL GGCounter = fileReader.DESERIALISE_DICT_STRING("Resources/Counter.json")["GG"]; SnzCounter = fileReader.DESERIALISE_DICT_STRING("Resources/Counter.json")["Sneeze"]; HckCounter = fileReader.DESERIALISE_DICT_STRING("Resources/Counter.json")["Hacker"]; GOG_Gold = new Discord.Color(250, 164, 5); GOG_Purple = new Discord.Color(177, 31, 224); }
public static async Task ChangeRoleColor(CommandArgs e) { if (!e.Server.GetUser(Convert.ToUInt64(ConstData.clientId)).ServerPermissions.ManageRoles) { await e.Channel.SendMessage("I never thought I'd have to ask you that but.. I need you to give me more power."); return; } if (!e.User.GetPermissions(e.Channel).ManagePermissions || !DataBase.IsUniqueUser(e.User.Id) || e.Args.Count() < 2) { await e.Channel.SendMessage(Util.GetRandomGrump()); return; } Discord.Role role = e.Server.FindRoles(e.Args.ElementAt(1)).FirstOrDefault(); if (role == null || role.Position > e.Server.GetUser(Convert.ToUInt64(ConstData.clientId)).Roles.FirstOrDefault().Position) { await e.Channel.SendMessage(Util.GetRandomGrump()); return; } uint numColor = 0; if (!uint.TryParse(e.Args.ElementAt(2), System.Globalization.NumberStyles.HexNumber, null, out numColor)) { await e.Channel.SendMessage("I hate this color."); return; } Discord.Color dcColor = null; if (numColor != 0) { dcColor = new Discord.Color(numColor); } if (dcColor == null) { await e.Channel.SendMessage(Util.GetRandomGrump()); return; } await role.Edit(color : dcColor); await e.Channel.SendMessage(String.Format("The `{0}` role has successfully changed its color.", role.ToString())); }
public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args) { StringBuilder retVal = new StringBuilder(); ServerSettings serverSettings = senderDetail.ServerSettings; CommandMessageHelper command = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message); string[] commandParams = command.CommandParams; Command[] commands = commandController.GetCommandsForLanguage(senderDetail.ServerSettings.Language); Discord.Color responseColor = Discord.Color.Green; if (string.IsNullOrWhiteSpace(command.CommandDetail)) { var commandsByModule = commands.GroupBy(x => x.Module).ToDictionary(grouping => grouping.Key, grouping => grouping.ToList()); foreach (var pair in commandsByModule) { retVal.Append("**"); retVal.Append(pair.Key.ToString()); retVal.AppendLine("**"); retVal.AppendLine(string.Join(", ", pair.Value.Select(c => c.Aliases[0]))); retVal.AppendLine(); } } else { string search = command.CommandArgs.First().ToLowerInvariant(); Command found = commands.FirstOrDefault(c => c.Aliases.Contains(search, StringComparer.OrdinalIgnoreCase)); if (found != null) { retVal.AppendLine(found.Help + "\r\n" + found.Examples); } else { retVal.AppendLine($"{Emojis.QuestionSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}"); responseColor = Discord.Color.Red; } } string message = retVal.ToString(); Response response = new Response { Embed = Utility.EmbedUtility.ToEmbed(message, responseColor), Message = message, ResponseType = ResponseType.Default }; return(new[] { response }); }
private bool TryGetFromName(string input, out Discord.Color?color) { color = null; try { var wrongTypeColor = Color.FromName(input); if (wrongTypeColor.IsEmpty) { return(false); } color = new Discord.Color(wrongTypeColor.R, wrongTypeColor.G, wrongTypeColor.B); return(true); } catch { return(false); } }
public async Task PingAsync(string rolename, string color) { var context = this.Context.User; Discord.Color col; if (color.Contains(",")) { var rgb = color.Split(','); if (rgb.Count() != 3) { await ReplyAsync("Invalid number of parameters"); return; } else { col = new Discord.Color(Convert.ToInt32(rgb[0]), Convert.ToInt32(rgb[1]), Convert.ToInt32(rgb[2])); } } else if (color != string.Empty) { col = new Discord.Color(); FieldInfo[] fields = col.GetType().GetFields(); var field = fields.Where(x => x.Name == color).First(); col = (Discord.Color)field.GetValue(null); // Discord.Color.//GetType().GetField(color); } else { await this.Context.Guild.CreateRoleAsync(rolename); return; } //Discord.Color col = new Discord.Color() await this.Context.Guild.CreateRoleAsync(rolename, null, col); }
private bool TryGetFromRGB(string input, out Discord.Color?color) { color = null; try { input = input.Replace(", ", ","); var rgbArr = input.Split(',', ';', '|', ' '); if (rgbArr.Length != 3 || !byte.TryParse(rgbArr[0], out var r) || !byte.TryParse(rgbArr[1], out var g) || !byte.TryParse(rgbArr[2], out var b)) { return(false); } color = new Discord.Color(r, g, b); return(true); } catch { return(false); } }
public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args) { ServerSettings serverSettings = senderDetail.ServerSettings; CommandMessageHelper command = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message); Discord.Color responseColor; string message; if (ImageManipulator.FindHexColour(command.CommandDetail, out string foundColour)) { var color = ImageManipulator.FromHexCode(foundColour); responseColor = new Discord.Color(color.R, color.G, color.B); var knownColor = color.ToKnownColor(); message = knownColor != 0 ? $"✓ {knownColor}" : $"(~) {color.ToConsoleColor()}"; } else if (Enum.TryParse(command.CommandDetail, true, out KnownColor knownColor)) { var color = Color.FromKnownColor(knownColor); responseColor = new Discord.Color(color.R, color.G, color.B); message = $"✓ {knownColor}"; } else { responseColor = Discord.Color.Default; message = $"{Emojis.QuestionSymbol} {command.CommandDetail}"; } Response response = new Response { Embed = Utility.EmbedUtility.ToEmbed(message, responseColor), Message = message, ResponseType = ResponseType.Default }; return(new[] { response }); }
public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args) { StringBuilder sb = new StringBuilder(); ServerSettings serverSettings = senderDetail.ServerSettings; CommandMessageHelper command = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message); string commandDetail = command.CommandDetail; Discord.Color?embedColour = null; if (string.IsNullOrEmpty(commandDetail)) { sb.AppendLine(Help); } else { // Remove decorators commandDetail = commandDetail.Replace("0x", "").Replace("0b", "").Replace("#", ""); // Replace commas with spaces commandDetail = commandDetail.Replace(",", " ").Trim(); // Special case hex to decimal in cases of 6 or 8 characters. bool is6Chars = commandDetail.Length == 6; bool is8Chars = commandDetail.Length == 8; if (fromBase == 16 && (is6Chars || is8Chars)) { // Try and convert the source hex number into a colour. if (uint.TryParse(commandDetail, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint argb)) { // Remove alpha channel (N.B. this usually makes it transparent as a = 0, but Discord fixes this to fully opaque) argb &= 0x00FFFFFF; embedColour = new Discord.Color(argb); } commandDetail += " "; commandDetail += commandDetail.Substring(0, 2); commandDetail += " "; commandDetail += commandDetail.Substring(2, 2); commandDetail += " "; commandDetail += commandDetail.Substring(4, 2); if (is8Chars) { commandDetail += " "; commandDetail += commandDetail.Substring(6, 2); } } string[] commandParams = commandDetail.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s)).ToArray(); if (fromBase == 10) { // Try and convert the source decimal number(s) into a colour. if (commandParams.Length == 1) { if (uint.TryParse(commandParams[0], out uint argb)) { // Remove alpha channel (N.B. this usually makes it transparent as a = 0, but Discord fixes this to fully opaque) argb &= 0x00FFFFFF; embedColour = new Discord.Color(argb); } } else if (commandParams.Length == 3 || commandParams.Length == 4) { // Using -n here as alpha could be included at the front. bool canParseColour = (byte.TryParse(commandParams[commandParams.Length - 3], out byte r)); canParseColour &= (byte.TryParse(commandParams[commandParams.Length - 2], out byte g)); canParseColour &= (byte.TryParse(commandParams[commandParams.Length - 1], out byte b)); if (canParseColour) { embedColour = new Discord.Color(r, g, b); } } } foreach (string col in commandParams) { try { switch (fromBase) { case 2: case 8: case 10: case 16: { long part = Convert.ToInt64(col, fromBase); byte[] parts = BitConverter.GetBytes(part); if (toBase == 64) { sb.Append(Convert.ToBase64String(parts) + " "); } else if (toBase == 16) { sb.Append(part.ToString("X2") + " "); } else { sb.Append(Convert.ToString(part, toBase) + " "); } break; } case 64: { byte[] parts = Convert.FromBase64String(col); long part = BitConverter.ToInt64(parts, 0); if (toBase == 64) { sb.Append(Convert.ToBase64String(parts) + " "); } else if (toBase == 16) { sb.Append(part.ToString("X2") + " "); } else { sb.Append(Convert.ToString(part, toBase) + " "); } break; } } } catch (FormatException) { sb.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(serverSettings.Language, "Error_IncorrectParameter")}: {col}."); } catch (Exception ex) { sb.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(serverSettings.Language, "Error_Oops")}: {col} {ex.Message}"); } } // If multiple things to translate, also provide the answer without spaces. if (command.CommandParams.Length > 2) { string outputWithoutSpace = sb.ToString().Replace(" ", ""); sb.AppendLine(); switch (toBase) { case 2: sb.Append("0b "); break; case 8: sb.Append("0o "); break; case 16: sb.Append("0x "); break; } sb.AppendLine(outputWithoutSpace); } } string output = sb.ToString(); Response response = new Response { Embed = EmbedUtility.ToEmbed(output, embedColour), Message = output, ResponseType = ResponseType.Default }; return(new[] { response }); }
public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args) { ServerSettings serverSettings = senderDetail.ServerSettings; CommandMessageHelper command = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message); string[] commandParams = command.CommandParams; Discord.Color responseColor = Discord.Color.Green; object ans; StringBuilder output = new StringBuilder(); string commandDetail = command.CommandDetail; try { if (commandDetail.Contains('!')) { output.AppendLine("*! is ambiguous, use ~ for 'bitwise-not'. Factorial is not yet supported. Assuming conditional-not.*"); } if (commandDetail.Contains('^')) { output.AppendLine("*Assumed ^ means XOR. For Power, use Pow(x,y).*"); } if (commandDetail.Contains('%')) { output.AppendLine("*Assumed % means modulo. For percentages, simply divide by 100.*"); } if (commandDetail.Count(c => c == '=') == 1) { output.AppendLine($"*Assumed = means is equal. For an equation solver, use the `{senderDetail.ServerSettings.CommandSymbol}wolframalpha` (`{senderDetail.ServerSettings.CommandSymbol}wa`) command.*"); } // Tidy up some common operator symbols. commandDetail = commandDetail .Replace("fix", "floor") // before the x replacement .Replace("x", "*") .Replace("modulo", "mod") .Replace("mod", "%") .Replace("¬", "~") .Replace("cosine", "cos") .Replace("sine", "sin") .Replace("tangent", "tan") .Replace("sqr ", "sqrt ") .Replace("root", "sqrt") .Replace("√", "sqrt") .Replace("atn", "atan") .Replace("π", "[pi]") .Replace("∞", "[infinity]") .Replace("pi ", "[pi] ") .Replace("infinity", "[infinity]") .Replace("inf", "[infinity]"); // Use ; to split statements. : can be used for more powerful functionality // such as [Convert]::ToString(1234, 16) foreach (string split in commandDetail.Split(';')) { Expression e = new Expression(split, EvaluateOptions.NoCache | EvaluateOptions.IgnoreCase); e.Parameters["pi"] = Math.PI; e.Parameters["e"] = Math.E; e.Parameters["infinity"] = double.MaxValue; ans = e.Evaluate(); if (ans == null) { output.AppendLine("I don't understand your input (undefined). Please check constants are enclosed by parentheses."); } else { if (e.HasErrors()) { output.AppendLine(e.Error); } else { output.AppendLine(split + " == " + ans.ToString()); } } } } catch (EvaluationException eEx) { responseColor = Discord.Color.Red; output.AppendLine("I can't evaluate your input: " + eEx.Message + "."); } catch (DivideByZeroException) { output.AppendLine("NaN."); } catch (OverflowException) { responseColor = Discord.Color.Red; output.AppendLine("Overflow."); } Response response = new Response { Embed = Utility.EmbedUtility.ToEmbed(output.ToString(), responseColor), Message = output.ToString(), ResponseType = ResponseType.Default }; return(new[] { response }); }
public async Task <Image <Rgba32> > GetLevelUpBadgeAsync(string name, long ulvl, string avatarUrl, Discord.Color color) { if (color == Discord.Color.Default) { color = Discord.Color.DarkerGrey; } var msgText1 = "POZIOM"; var msgText2 = "Awansuje na:"; var textFont = new Font(_latoRegular, 16); var nickNameFont = new Font(_latoBold, 22); var lvlFont = new Font(_latoBold, 36); var msgText1Length = TextMeasurer.Measure(msgText1, new RendererOptions(textFont)); var msgText2Length = TextMeasurer.Measure(msgText2, new RendererOptions(textFont)); var nameLength = TextMeasurer.Measure(name, new RendererOptions(nickNameFont)); var lvlLength = TextMeasurer.Measure($"{ulvl}", new RendererOptions(lvlFont)); var textLength = lvlLength.Width + msgText1Length.Width > nameLength.Width ? lvlLength.Width + msgText1Length.Width : nameLength.Width; var estimatedLength = 106 + (int)(textLength > msgText2Length.Width ? textLength : msgText2Length.Width); var nickNameColor = color.RawValue.ToString("X6"); var baseImg = new Image <Rgba32>((int)estimatedLength, 100); baseImg.Mutate(x => x.BackgroundColor(Rgba32.FromHex("#36393e"))); baseImg.Mutate(x => x.DrawText(msgText1, textFont, Rgba32.Gray, new Point(98 + (int)lvlLength.Width, 75))); baseImg.Mutate(x => x.DrawText(name, nickNameFont, Rgba32.FromHex(nickNameColor), new Point(98, 10))); baseImg.Mutate(x => x.DrawText(msgText2, textFont, Rgba32.Gray, new Point(98, 33))); baseImg.Mutate(x => x.DrawText($"{ulvl}", lvlFont, Rgba32.Gray, new Point(96, 61))); using (var colorRec = new Image <Rgba32>(82, 82)) { colorRec.Mutate(x => x.BackgroundColor(Rgba32.FromHex(nickNameColor))); baseImg.Mutate(x => x.DrawImage(colorRec, new Point(9, 9), 1)); using (var stream = await GetImageFromUrlAsync(avatarUrl)) { if (stream == null) { return(baseImg); } using (var avatar = Image.Load(stream)) { avatar.Mutate(x => x.Resize(new ResizeOptions { Mode = ResizeMode.Crop, Size = new Size(80, 80) })); baseImg.Mutate(x => x.DrawImage(avatar, new Point(10, 10), 1)); } } } return(baseImg); }
public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args) { StringBuilder output = new StringBuilder(); ServerSettings serverSettings = senderDetail.ServerSettings; CommandMessageHelper command = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message); string[] commandParams = command.CommandParams; long min = 0; long max; if (commandParams.Length == 1) { max = 10; } else if (commandParams.Length == 2) { if (!long.TryParse(commandParams[1], NumberStyles.Any, CultureInfo.InvariantCulture, out max)) { if (commandParams[1] == "∞" || commandParams[1].StartsWith("inf")) { max = long.MaxValue; } else if (commandParams[1] == "-∞" || commandParams[1].StartsWith("-inf")) { max = long.MinValue; } else { output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(serverSettings.Language, Errors.ErrorCode.IncorrectParameter)}: {commandParams[1]}."); max = 10; } } } else { if (!long.TryParse(commandParams[1], NumberStyles.Any, CultureInfo.InvariantCulture, out min)) { if (commandParams[1] == "∞" || commandParams[1].StartsWith("inf")) { min = long.MaxValue; } else if (commandParams[1] == "-∞" || commandParams[1].StartsWith("-inf")) { min = long.MinValue; } else { output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(serverSettings.Language, Errors.ErrorCode.IncorrectParameter)}: {commandParams[1]}."); min = 0; } } if (!long.TryParse(commandParams[2], NumberStyles.Any, CultureInfo.InvariantCulture, out max)) { if (commandParams[2] == "∞" || commandParams[2].StartsWith("inf")) { max = long.MaxValue; } else if (commandParams[2] == "-∞" || commandParams[2].StartsWith("-inf")) { max = long.MinValue; } else { output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(serverSettings.Language, Errors.ErrorCode.IncorrectParameter)}: {commandParams[2]}."); max = 10; } } } if (min > max) { // Swap long temp = max; max = min; min = temp; } long num = rand.NextLong(min, max == long.MaxValue ? long.MaxValue : max + 1); output.AppendLine((min) + " -> " + (max) + ": " + num); ulong range = (ulong)(max - min); if (range == 0) { range = 1; } long normNum = (num - min); float percentage = (((float)normNum) / range) * 360; if (percentage > 360) { percentage = 360; } var drawingColour = Imaging.ImageManipulator.FromAHSB(255, percentage, 0.8f, 0.5f); var responseColor = new Discord.Color(drawingColour.R, drawingColour.G, drawingColour.B); string retVal = output.ToString(); Response response = new Response { Embed = Utility.EmbedUtility.ToEmbed(retVal, responseColor), Message = retVal, ResponseType = ResponseType.Default }; return(new[] { response }); }
public async Task <Image <Rgba32> > GetUserProfileAsync(IUserInfo shindenUser, User botUser, string avatarUrl, long topPos, string nickname, Discord.Color color) { if (color == Discord.Color.Default) { color = Discord.Color.DarkerGrey; } string rangName = shindenUser?.Rank ?? ""; string colorRank = color.RawValue.ToString("X6"); var nickFont = GetFontSize(_latoBold, 28, nickname, 290); var rangFont = new Font(_latoRegular, 16); var levelFont = new Font(_latoBold, 40); var template = Image.Load("./Pictures/profileBody.png"); var profilePic = new Image <Rgba32>(template.Width, template.Height); if (!File.Exists(botUser.BackgroundProfileUri)) { botUser.BackgroundProfileUri = "./Pictures/defBg.png"; } using (var userBg = Image.Load(botUser.BackgroundProfileUri)) { profilePic.Mutate(x => x.DrawImage(userBg, new Point(0, 0), 1)); profilePic.Mutate(x => x.DrawImage(template, new Point(0, 0), 1)); template.Dispose(); } using (var avatar = Image.Load(await GetImageFromUrlAsync(avatarUrl))) { using (var avBack = new Image <Rgba32>(82, 82)) { avBack.Mutate(x => x.BackgroundColor(Rgba32.FromHex(colorRank))); avBack.Mutate(x => x.Round(42)); profilePic.Mutate(x => x.DrawImage(avBack, new Point(20, 115), 1)); } avatar.Mutate(x => x.Resize(new Size(80, 80))); avatar.Mutate(x => x.Round(42)); profilePic.Mutate(x => x.DrawImage(avatar, new Point(21, 116), 1)); } var defFontColor = Rgba32.FromHex("#7f7f7f"); var posColor = Rgba32.FromHex("#FFD700"); if (topPos == 2) { posColor = Rgba32.FromHex("#c0c0c0"); } else if (topPos == 3) { posColor = Rgba32.FromHex("#cd7f32"); } else if (topPos > 3) { posColor = defFontColor; } profilePic.Mutate(x => x.DrawText(nickname, nickFont, Rgba32.FromHex("#a7a7a7"), new Point(132, 150 + (int)((30 - nickFont.Size) / 2)))); profilePic.Mutate(x => x.DrawText(rangName, rangFont, defFontColor, new Point(132, 180))); var mLevel = TextMeasurer.Measure($"{botUser.Level}", new RendererOptions(levelFont)); profilePic.Mutate(x => x.DrawText($"{botUser.Level}", levelFont, defFontColor, new Point((int)(125 - mLevel.Width) / 2, 206))); var mTopPos = TextMeasurer.Measure($"{topPos}", new RendererOptions(levelFont)); profilePic.Mutate(x => x.DrawText($"{topPos}", levelFont, posColor, new Point((int)(125 - mTopPos.Width) / 2, 284))); var mScOwn = TextMeasurer.Measure($"{botUser.ScCnt}", new RendererOptions(rangFont)); profilePic.Mutate(x => x.DrawText($"{botUser.ScCnt}", rangFont, defFontColor, new Point((int)(125 - mScOwn.Width) / 2, 365))); var mTcOwn = TextMeasurer.Measure($"{botUser.TcCnt}", new RendererOptions(rangFont)); profilePic.Mutate(x => x.DrawText($"{botUser.TcCnt}", rangFont, defFontColor, new Point((int)(125 - mTcOwn.Width) / 2, 405))); var mMsg = TextMeasurer.Measure($"{botUser.MessagesCnt}", new RendererOptions(rangFont)); profilePic.Mutate(x => x.DrawText($"{botUser.MessagesCnt}", rangFont, defFontColor, new Point((int)(125 - mMsg.Width) / 2, 445))); if (botUser.GameDeck.Waifu != 0 && botUser.ShowWaifuInProfile) { var tChar = botUser.GameDeck.Cards.OrderBy(x => x.Rarity).FirstOrDefault(x => x.Character == botUser.GameDeck.Waifu); if (tChar != null) { using (var cardImage = await GetWaifuInProfileCardAsync(tChar)) { cardImage.Mutate(x => x.Resize(new ResizeOptions { Mode = ResizeMode.Max, Size = new Size(105, 0) })); profilePic.Mutate(x => x.DrawImage(cardImage, new Point(10, 350), 1)); } } } var prevLvlExp = ExperienceManager.CalculateExpForLevel(botUser.Level); var nextLvlExp = ExperienceManager.CalculateExpForLevel(botUser.Level + 1); var expOnLvl = botUser.ExpCnt - prevLvlExp; var lvlExp = nextLvlExp - prevLvlExp; if (expOnLvl < 0) { expOnLvl = 0; } if (lvlExp < 0) { lvlExp = expOnLvl + 1; } int progressBarLength = (int)(305f * ((double)expOnLvl / (double)lvlExp)); if (progressBarLength > 0) { using (var progressBar = new Image <Rgba32>(progressBarLength, 19)) { progressBar.Mutate(x => x.BackgroundColor(Rgba32.FromHex("#828282"))); profilePic.Mutate(x => x.DrawImage(progressBar, new Point(135, 201), 1)); } } string expText = $"EXP: {expOnLvl} / {lvlExp}"; var mExp = TextMeasurer.Measure(expText, new RendererOptions(rangFont)); profilePic.Mutate(x => x.DrawText(expText, rangFont, Rgba32.FromHex("#ffffff"), new Point(135 + ((int)(305 - mExp.Width) / 2), 204))); using (var inside = GetProfileInside(shindenUser, botUser)) { profilePic.Mutate(x => x.DrawImage(inside, new Point(125, 228), 1)); } return(profilePic); }
public async Task <Image <Rgba32> > GetSiteStatisticAsync(IUserInfo shindenInfo, Discord.Color color, List <ILastReaded> lastRead = null, List <ILastWatched> lastWatch = null) { if (color == Discord.Color.Default) { color = Discord.Color.DarkerGrey; } var baseImg = new Image <Rgba32>(500, 320); baseImg.Mutate(x => x.BackgroundColor(Rgba32.FromHex("#36393e"))); using (var template = Image.Load("./Pictures/siteStatsBody.png")) { baseImg.Mutate(x => x.DrawImage(template, new Point(0, 0), 1)); } using (var avatar = await GetSiteStatisticUserBadge(shindenInfo.AvatarUrl, shindenInfo.Name, color.RawValue.ToString("X6"))) { baseImg.Mutate(x => x.DrawImage(avatar, new Point(0, 0), 1)); } using (var image = new Image <Rgba32>(325, 248)) { if (shindenInfo?.ListStats?.AnimeStatus != null) { using (var stats = GetRWStats(shindenInfo?.ListStats?.AnimeStatus, "./Pictures/statsAnime.png", shindenInfo.GetMoreSeriesStats(false))) { image.Mutate(x => x.DrawImage(stats, new Point(0, 0), 1)); } } if (shindenInfo?.ListStats?.MangaStatus != null) { using (var stats = GetRWStats(shindenInfo?.ListStats?.MangaStatus, "./Pictures/statsManga.png", shindenInfo.GetMoreSeriesStats(true))) { image.Mutate(x => x.DrawImage(stats, new Point(0, 128), 1)); } } baseImg.Mutate(x => x.DrawImage(image, new Point(5, 71), 1)); } using (var image = await GetLastRWList(lastRead, lastWatch)) { baseImg.Mutate(x => x.DrawImage(image, new Point(330, 69), 1)); } return(baseImg); }
public ColorAttribute(Discord.Color color) { Color = color; }
public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args) { ServerSettings serverSettings = senderDetail.ServerSettings; CultureInfo cultureInfo = languageHandler.GetCultureInfo(serverSettings.Language); CommandMessageHelper command = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message); string[] commandParams = command.CommandParams; Discord.Color responseColor = Discord.Color.Green; string[] typeStrings; if (command.CommandDetail.Contains('-')) { // User wrote e.g. normal-flying typeStrings = command.CommandDetail.Split('-'); } else { typeStrings = command.CommandArgs.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray(); } if (typeStrings.Length == 0) { // No types specified. return(Response.CreateArrayFromString("http://bulbapedia.bulbagarden.net/wiki/Type")); } List <string> incorrectTypes = new List <string>(); List <string> duplicateTypes = new List <string>(); var foundTypes = new HashSet <PokemonType>(); // TODO - translate. if (typeStrings.Length == 1 && typeStrings[0].Equals("all", StringComparison.OrdinalIgnoreCase)) { // Add all types. foreach (PokemonType t in PokemonTypeHandler.PokemonTypes) { if (t != PokemonType.NumberOfTypes) { foundTypes.Add(t); } } } else { foreach (string typeStr in typeStrings) { bool found = PokemonTypeHandler.GetTypeFromLocalisedName(typeStr, cultureInfo, out PokemonType t); if (found) { bool added = foundTypes.Add(t); if (!added) { duplicateTypes.Add(typeStr); } } else { incorrectTypes.Add(typeStr); } } } bool foundAny = foundTypes.Any(); if (!foundAny) { // Check if is actually a Pokémon. Pokemon pokemon = (KnowledgeBase.GetOrFetchPokémon(command.CommandDetail)); if (pokemon != null) { foundTypes.Add(pokemon.PrimaryType); if (pokemon.SecondaryType != PokemonType.NumberOfTypes) { foundTypes.Add(pokemon.SecondaryType); } foundAny = true; // Ignore the typing - it's a Pokémon. incorrectTypes.Clear(); duplicateTypes.Clear(); } } StringBuilder sb = new StringBuilder(); // Incorrect types if (incorrectTypes.Any()) { sb.Append($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}"); sb.Append(": "); sb.AppendLine(string.Join(" ", incorrectTypes)); } // Duplicate types if (duplicateTypes.Any()) { sb.Append($"{Emojis.ExclamationSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Warning_SameType")}"); sb.Append(": "); sb.AppendLine(string.Join(" ", duplicateTypes)); } if (foundAny) { sb.AppendLine("```objectivec"); sb.Append("// "); foreach (PokemonType foundType in foundTypes) { string foundTypeName = PokemonTypeHandler.GetLocalisedName(foundType, cultureInfo); sb.Append(foundTypeName); sb.Append(" "); } sb.AppendLine(); // Attacking if (foundTypes.Count < 3) { sb.AppendLine($"# {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Attacking")}"); foreach (PokemonType foundType in foundTypes) { double[] attackingType1 = PokemonTypeHandler.GetAttacking(foundType); for (int i = 0; i < attackingType1.Length; i++) { double eff = attackingType1[i]; if (eff != 1.0) { sb.Append(eff.ToString("G", cultureInfo.NumberFormat)); sb.Append($"x {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Against")} "); sb.Append(PokemonTypeHandler.GetLocalisedName(PokemonTypeHandler.PokemonTypes[i], cultureInfo)); sb.Append($" {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "WhenAttackingWith")} "); sb.Append(PokemonTypeHandler.GetLocalisedName(foundType, cultureInfo)); sb.AppendLine(); } } } } sb.AppendLine(); // Defending sb.AppendLine($"# {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Defending")}"); double[] defending = PokemonTypeHandler.GetDefending(foundTypes.ToArray()); for (int i = 0; i < defending.Length; i++) { double eff = defending[i]; if (eff != 1.0) { sb.Append(eff.ToString("G", cultureInfo.NumberFormat)); sb.Append($"x {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "DamageTakenFrom")} "); sb.AppendLine(PokemonTypeHandler.GetLocalisedName(PokemonTypeHandler.PokemonTypes[i], cultureInfo)); } } // Add on status immunities. foreach (PokemonType foundType in foundTypes) { string immunity = PokemonTypeHandler.GetTypeStatusImmunityString(foundType, cultureInfo); if (immunity != string.Empty) { sb.AppendLine(immunity); } } sb.Append("```"); } return(Response.CreateArrayFromString(sb.ToString(), responseColor)); }
protected async Task <CommandResponse> FailCommandAsync(Message message, string reason, Discord.Color color, string title = null) { _responseBuilder.Clear(); _responseBuilder.WithFooter(_config.Footer) .FailWithDescription(reason) .WithColor(color); if (title != null) { _responseBuilder.WithTitle(title); } var response = _responseBuilder.Build(); await message.Channel.ReplyToAsync(message, response).ConfigureAwait(false); return(response); }
public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args) { ServerSettings serverSettings = senderDetail.ServerSettings; CultureInfo cultureInfo = languageHandler.GetCultureInfo(serverSettings.Language); CommandMessageHelper command = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message); Discord.Color responseColor = Discord.Color.Green; // First, check the cache if we already have this pokémon. string query = command.CommandDetail; if (args.URLs.Length > 0) { var response = new[] { waitHandler.CreatePleaseWaitResponse(senderDetail.ServerSettings.Language) }; Task.Run(async() => { Response asyncResponse = await CorrelatePokemonAsync(senderDetail.ServerSettings.Language, args); if (asyncResponse == null) { string err = ($"{Emojis.NoEntry} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_NoImageMessages")}"); asyncResponse = new Response { Embed = EmbedUtility.ToEmbed(err), Message = err, ResponseType = ResponseType.Default }; } await asyncResponder.SendResponseAsync(args, asyncResponse); waitHandler.PopPleaseWaitMessage(); }); return(response); } query = query.Replace("(Pokemon)", "").Replace("(Pokémon)", "").Trim(); query = query.Replace("(move)", "").Trim(); StringBuilder output = new StringBuilder(); Pokemon pokemon = KnowledgeBase.GetPokémon(query); string imageUrl = null; bool isCached = (pokemon != null); try { // For now, assume that it is a Pokémon. string url = "https://bulbapedia.bulbagarden.net/wiki/" + query.Capitalize() + "_(Pokémon)"; string urlRaw = url + "?action=raw"; if (!isCached) { // Assume correct URL pokemon = Pokemon.ParsePage(urlRaw); } if (pokemon != null) { string p = pokemon.Name + "_(Pokémon)"; dynamic imageJson = null; output .Append("https://bulbapedia.bulbagarden.net/wiki/") .Append(p) .AppendLine("#") // # is for mobile where () is not correctly parsed in the URL parser .AppendLine(MakeAPokemonString(pokemon, cultureInfo, serverSettings.Language)); try { cancellationTokenSource.CancelAfter(300000); Task.Run(async() => { imageJson = await JSONHelper.GetJsonAsync(Uri.EscapeUriString("https://bulbapedia.bulbagarden.net/w/api.php?action=query&format=json&prop=pageimages&titles=" + p)).ConfigureAwait(false); }, cancellationTokenSource.Token).Wait(); JToken token = imageJson["query"]["pages"]; token = token.First.First; imageUrl = token["thumbnail"]["source"]?.ToString(); } catch (TaskCanceledException tcex) { errorLogger.LogDebug("Did not query Bulbapedia in time to retrieve the Pokemon image.", true); errorLogger.LogException(tcex, ErrorSeverity.Warning); } catch (Exception ex) { errorLogger.LogDebug($"Exception occurred retrieving the Pokemon image for {pokemon?.Name}.\n" + $"imageUrl: {imageUrl}\n" + $"imageJson: {imageJson}", true); errorLogger.LogException(ex, ErrorSeverity.Error); } } else { output.AppendLine($"{Emojis.ExclamationSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_PokemonNotFound")}: {urlRaw}"); } } catch (WebException) { output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_PokemonNotFound")}: {query}"); } catch (Exception ex) { output.AppendLine($"{languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_Oops")}: {ex.Message}"); } return(Response.CreateArrayFromString(output.ToString(), responseColor, pokemon.Name, imageUrl)); }
public static String HexConverter(Discord.Color c) { return(c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2")); }
public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args) { string retVal = ""; ServerSettings serverSettings = senderDetail.ServerSettings; CommandMessageHelper command = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message); string[] commandParams = command.CommandParams; ushort flips; Discord.Color responseColor = new Discord.Color(0); if (commandParams.Length == 1) { flips = 1; } else { if (!ushort.TryParse(commandParams[1], out flips) || flips <= 0) { retVal = ($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(serverSettings.Language, Errors.ErrorCode.IncorrectParameter)}: {commandParams[1]}. [1-{uint.MaxValue}]."); } } if (flips > 0) { int heads = 0, tails = 0; string localeHead = languageHandler.GetPhrase(serverSettings.Language, "CoinHead"); string localeTail = languageHandler.GetPhrase(serverSettings.Language, "CoinTail"); if (flips == 1) { switch (rand.Next(2)) { default: case 0: retVal = localeHead; heads++; break; case 1: retVal = localeTail; tails++; break; } } else { char headLetter = (localeHead)[0]; char tailLetter = (localeTail)[0]; string flipped = languageHandler.GetPhrase(serverSettings.Language, "Flipped"); if (flips > 100) { for (int i = 0; i < flips; i++) { switch (rand.Next(2)) { case 0: heads++; break; case 1: tails++; break; } } retVal = ($"{flipped} {flips}x, `{localeHead}:` {heads}, `{localeTail}:` {tails}"); } else { StringBuilder coinflips = new StringBuilder(); for (int i = 0; i < flips; i++) { switch (rand.Next(2)) { case 0: coinflips.Append(headLetter); heads++; break; case 1: coinflips.Append(tailLetter); tails++; break; } } retVal = ($"{flipped} {flips}x, `{localeHead}:` {heads}, `{localeTail}:` {tails}: {coinflips.ToString()}"); } } if (heads < tails) { responseColor = new Discord.Color(200, 50, 50); } else if (heads > tails) { responseColor = new Discord.Color(50, 200, 50); } else { responseColor = new Discord.Color(200, 200, 50); } } Response response = new Response { Embed = Utility.EmbedUtility.ToEmbed(retVal, responseColor), Message = retVal, ResponseType = ResponseType.Default }; return(new[] { response }); }
public static string ToRgbString(this DiscordColor color) => $"rgb({color.R}, {color.G}, {color.B})";