public async Task UpdateColor([Summary("The hex value of the Color Role.")] string colorValue, [Remainder, Summary("The name of the Color Role.")] string roleName) { if (Xml.CommandAllowed("update color", Context)) { var users = await Context.Guild.GetUsersAsync(); var colorRole = Context.Guild.Roles.FirstOrDefault(r => r.Name.ToUpper().Contains($"COLOR: {roleName.ToUpper()}")); if (users.Any(x => x.RoleIds.Contains(colorRole.Id) && x.Id != Context.User.Id)) { await Context.Channel.SendMessageAsync($"Role 'Color: {roleName}' is already in use by a different Member, so you can't update it. Try creating a new color role with ``?create color``"); } else { colorValue = colorValue.Replace("#", ""); Discord.Color roleColor = new Discord.Color(uint.Parse(colorValue, NumberStyles.HexNumber)); try { await colorRole.ModifyAsync(r => r.Color = roleColor); await Context.Channel.SendMessageAsync("Role successfully updated!"); } catch { await Context.Channel.SendMessageAsync($"Role 'Color: {roleName}' couldn't be found. Make sure you entered the exact role name!"); } } } }
public Embed FindAndFormatAnimeResult(string animeTitle) { var animeResult = KitsuApi.GetAnime.WithTitle(animeTitle).Result().Result; if (animeResult == null) { return(new EmbedBuilder().WithTitle("Anime not found!").Build()); } string description = TagMatcher.Replace(animeResult.Synopsis, string.Empty); System.Drawing.Color bestColor = Extensions.GetBestColor(animeResult.Poster.MediumUrl); Discord.Color bestDiscordColor = new Discord.Color(bestColor.R, bestColor.G, bestColor.B); return(new EmbedBuilder() .WithThumbnailUrl(animeResult.Poster.OriginalUrl) .WithTitle(animeResult.Titles.Romanized) .WithDescription(new StringBuilder() .AppendLine(description) .AppendLine() .AppendLine($"{animeResult.SubType.ToString().ToTitleCase()} - {animeResult.Status.ToString().ToTitleCase()}") .AppendLine() .AppendLine($"{animeResult.EpisodeCount} episodes") .ToString()) .WithColor(bestDiscordColor) .WithFooter($"{animeResult.StartDate?.ToString("MMMM dd, yyyy")} - {animeResult.EndDate?.ToString("MMMM dd, yyyy")}") .Build()); }
public static Discord.Color GetEmbedColor(ICommandContext CommandMessage) { Discord.Color Color = new Discord.Color(0); Color = _Bot.FavoriteColor; if (CommandMessage.Guild != null) { IGuildUser GuildUser = CommandMessage.User as IGuildUser; if (GuildUser.RoleIds.Count != 1) { if (Settings.ForceRoleColor == "Yes") { if (GuildUser.GuildPermissions.EmbedLinks || GuildUser.GetPermissions(CommandMessage.Channel as ITextChannel).EmbedLinks) { if (CommandMessage.Guild.Roles.Count() > 1 && GuildUser.RoleIds.Count() > 1) { foreach (var i in GuildUser.Guild.Roles.Where(x => x.Id != CommandMessage.Guild.EveryoneRole.Id && GuildUser.RoleIds.Contains(x.Id)).OrderByDescending(x => x.Position)) { if (i.Color.R != 0 && i.Color.G != 0 && i.Color.B != 0) { Color = i.Color; break; } } } } } } } if (GUI_Form.EmbedColor.RawValue != 0) { Color = GUI_Form.EmbedColor; } return(Color); }
// Generic Embed template public static Embed Embed(string t, string d, Discord.Color c, string f, string thURL) => new EmbedBuilder() .WithTitle(t) .WithDescription(d) .WithColor(c) .WithFooter(f) .WithThumbnailUrl(thURL) .Build();
// Generic Image Embed template public static Embed ImageEmbed(string t, string d, Discord.Color c, string f, string imageURL) => new EmbedBuilder() .WithTitle(t) .WithDescription(d) .WithColor(c) .WithFooter(f) .WithImageUrl(imageURL) .Build();
public async Task CreateColor([Summary("The hex value of the Color Role.")] string colorValue, [Remainder, Summary("The name of the Color Role.")] string roleName) { if (Xml.CommandAllowed("create color", Context)) { try { //Create color role at highest possible position var lowestModeratorRole = Context.Guild.Roles.FirstOrDefault(x => !x.Permissions.Administrator).Position; colorValue = colorValue.Replace("#", ""); Discord.Color roleColor = new Discord.Color(uint.Parse(colorValue, NumberStyles.HexNumber)); var colorRole = await Context.Guild.CreateRoleAsync($"Color: {roleName}", null, roleColor, false, null); await colorRole.ModifyAsync(r => r.Position = lowestModeratorRole - 1); await Context.Channel.SendMessageAsync("Role successfully created!"); //Sort color roles by hue as high as possible on list var orderedRoles = Context.Guild.Roles.Where(x => x.Name.StartsWith("Color: ")).OrderBy(x => System.Drawing.Color.FromArgb(x.Color.R, x.Color.R, x.Color.G, x.Color.B).GetHue()); foreach (var role in orderedRoles) { await role.ModifyAsync(x => x.Position = lowestModeratorRole - 1); } } catch { await Context.Channel.SendMessageAsync("Role couldn't be created. Make sure you entered a valid hexadecimal value!"); } } }
public static Embed Embed(string title, string desc, Discord.Color col, string foot, string thURL) => new EmbedBuilder() .WithTitle(title) .WithDescription(desc) .WithColor(col) .WithFooter(foot) .WithThumbnailUrl(thURL) .Build();
/// <summary> /// Save role settings to DB /// </summary> /// <param name="guild">Discord guild containing role</param> /// <returns>True on success modify/insert</returns> public bool Save(DW.SocketGuild guild = null) { if (!string.IsNullOrWhiteSpace(this.Path)) { this.Path = "/" + string.Join( '/', this.Path.Trim().Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries) .Select(folder => Regex.Replace(folder, "^[0-9A-Za-z ]+$", string.Empty).Trim()) .Where(folder => !string.IsNullOrWhiteSpace(folder))); if (string.IsNullOrWhiteSpace(this.Path) || !this.Path.StartsWith('/')) { this.Path = "/"; } } Role.UpdateDatabase(ulong.Parse(this.Identifier), this.Path, ulong.Parse(this.GuildIdentifier)); if (guild != null) { if (this.Identifier == "0" || string.IsNullOrWhiteSpace(this.Identifier)) { // Create role DNET.Color?color = null; if (this.Color != null && this.Color.Count == 3) { color = new DNET.Color(this.Color[0], this.Color[1], this.Color[2]); } Task.Run(() => guild.CreateRoleAsync(this.Name, this.Permissions, color)); return(true); } else { // Modify role DW.SocketRole role = guild.GetRole(ulong.Parse(this.Identifier)); if (role != null) { Task.Run(() => role.ModifyAsync(changed => { changed.Name = this.Name; changed.Permissions = this.Permissions; if (this.Color != null && this.Color.Count == 3) { changed.Color = new DNET.Optional <DNET.Color>(new DNET.Color(this.Color[0], this.Color[1], this.Color[2])); } })); return(true); } } } return(false); }
public static Embed ColoredMsg(string input) { var embed = new EmbedBuilder(); Discord.Color color = Discord.Color.Purple; embed.WithColor(color); embed.Description = input; return(embed.Build()); }
//TODO: Add local members cache internal Role(DiscordClient client, string id, string serverId) : base(client, id) { _server = new Reference<Server>(serverId, x => _client.Servers[x], x => x.AddRole(this), x => x.RemoveRole(this)); Permissions = new ServerPermissions(0); Permissions.Lock(); Color = new Color(0); Color.Lock(); }
/// <summary> Creates a basic embed with specified information and returns it. </summary> /// <returns> The created embed. </returns> public static Embed CreateBasicEmbed(string title, string description, Color color) { var embed = new EmbedBuilder() .WithTitle(title) .WithDescription(description) .WithColor(color).Build(); return(embed); }
public async Task ColorMe(string color) { // Check if this guild supports ColorMe. if (!guildsDefinition.GetSettings(Context.Guild.Id).colorMe) { await Context.Channel.SendMessageAsync("ColorMe is not enabled for this server."); return; } string roleName = ("colorme" + Context.User.Id); // Check if the color is valid. Discord.Color roleColor = new Discord.Color(); try { roleColor = new Discord.Color(GetRawColor(color)); } catch { await Context.Channel.SendMessageAsync("Invalid hex code."); return; } // Check if the user already has a color role. IRole colorRole = Context.Guild.Roles.FirstOrDefault(x => x.Name == roleName); // Get where this role should go so it works, which is right above their current role. int highestRole = Context.Guild.GetUser(Context.User.Id).Roles.LastOrDefault(x => x.Name != roleName).Position + 1; // Create the role if needed. if (colorRole == null) { colorRole = await Context.Guild.CreateRoleAsync(roleName, null, roleColor, false, null); await colorRole.ModifyAsync(new Action <RoleProperties>(x => x.Position = highestRole)); } else { await colorRole.ModifyAsync(new Action <RoleProperties>(x => x.Color = roleColor)); } // If the user doesn't have the color role assigned, add it to them. if (Context.Guild.GetUser(Context.User.Id).Roles.FirstOrDefault(x => x.Name == roleName) == null) { try { await Context.Guild.GetUser(Context.User.Id).AddRolesAsync(new List <IRole>() { colorRole }); }catch (Exception e) { Console.WriteLine(e.Message); } } await Context.Channel.SendMessageAsync($"Assigned color {roleColor.ToString()} to {Context.User.Username}."); }
public static EmbedBuilder ResultFeedback(Discord.Color color, string symbol, string text) { var eb = new EmbedBuilder() { Color = color, Title = $"{symbol} {text}" }; return(eb); }
public async Task Embed() { var FullMoon = new EmbedBuilder(); var DiscordGray = new Discord.Color(0x36393F); FullMoon.WithImageUrl("https://i.imgur.com/Tg3b9H3.png"); FullMoon.WithDescription("http://godfall.azurewebsites.net/world/solace/calendar/"); FullMoon.WithColor(DiscordGray); await ReplyAsync("", false, FullMoon.Build()); }
public async Task EmbedString(string clr, [Remainder] string text) { var tempColour = System.Drawing.Color.FromName(clr); var colour = new Discord.Color(tempColour.R, tempColour.G, tempColour.B); var embed = new EmbedBuilder(); embed.WithDescription(text); embed.WithColor(colour); await Context.Channel.SendMessageAsync("", embed : embed); }
public async Task test(params string[] args) { List <TwitchHandler.TwitchData> userInfo = await TwitchHandler.GetTwitchInfo(args[1]); Color TwitchColour = new Color(100, 65, 165); EmbedBuilder eb = new EmbedBuilder(); eb.Title = userInfo[0].display_name; eb.Color = TwitchColour; eb.WithCurrentTimestamp(); switch (args[0].ToLower()) { case "channel": eb.Description = userInfo[0].description; eb.Footer = new EmbedFooterBuilder() { IconUrl = userInfo[0].profile_image_url, Text = $"created at: {userInfo[0].created_at}" }; eb.AddField("Twitch account information", $"Link to profile: https://www.twitch.tv/{args[1]} \nView count: {userInfo[0].view_count}\nUser id: {userInfo[0].id}"); break; case "av": case "avatar": case "pfp": eb.Description = $"Here's the profile picture for {userInfo[0].display_name}:"; eb.ImageUrl = userInfo[0].profile_image_url; break; case "livetest": List <TwitchHandler.UserStreams> userStreams = await TwitchHandler.GetStreams(args[1]); if (userStreams.Count == 0) { await Context.Message.ReplyAsync("", false, Global.EmbedMessage("Error", $"The user {args[1]} is not currently live on Twitch.", false, Color.Red).Build()); return; } eb.Title = $"{args[1]} is live on Twitch!"; eb.ImageUrl = $"https://static-cdn.jtvnw.net/previews-ttv/live_user_{args[1]}.jpg"; eb.Description = $"[Watch {args[1]} live on Twitch!](https://twitch.tv/{args[1]})"; eb.AddField("Stream information", $"title: {userStreams[0].title}\ngame name: {userStreams[0].game_name}\nviewer count: {userStreams[0].viewer_count}"); eb.Footer = new EmbedFooterBuilder() { IconUrl = userInfo[0].profile_image_url, Text = $"Live started at: {userStreams[0].started_at}" }; break; } await ReplyAsync("", false, eb.Build()); }
//Work Cooldown // Generic Embed template public Embed Embed(string t, string d, Discord.Color c, string f, string thURL) { var embed = new EmbedBuilder(); embed.WithTitle(t); embed.WithDescription(d); embed.WithColor(c); embed.WithFooter(f); embed.WithThumbnailUrl(thURL); return(embed.Build()); }
public async Task Set(IGuildUser user, string colorStr) { if (user is null) { throw new ArgumentNullException(nameof(user)); } if (colorStr is null) { throw new ArgumentNullException(nameof(colorStr)); } // Try and convert the color to a .NET color to pass to Discord later. // This also serves as validation that the color string is valid since this _should_ throw an exception if it isn't. System.Drawing.Color color; try { color = System.Drawing.ColorTranslator.FromHtml(colorStr); } catch (Exception) { await Context.Channel.SendMessageAsync("Color was not known!").ConfigureAwait(false); return; } colorStr = ColorTranslator.ToHtml(System.Drawing.Color.FromArgb(color.ToArgb())); // Done to standardize the role name var discordColor = new Discord.Color(color.R, color.G, color.B); // Because Discord.Net has it's own color format, ig var roleName = "color-" + colorStr; var possibleRoles = Context.Guild.Roles .Where(role => role.Name == roleName && role.Color == discordColor); // Check if the server has roles already IRole role; if (possibleRoles.Any()) // if it does.. { role = possibleRoles.First(); // grab that role } else // create if if not { role = await Context.Guild.CreateRoleAsync(roleName, GuildPermissions.None, discordColor, false, null); await role.ModifyAsync(r => r.Position = 2).ConfigureAwait(false); } // remove any existing color roles from the user var roles = user.RoleIds .Select(id => Context.Guild.GetRole(id)) // Convert each role ID the user has into a role object .Where(role => role.Name.StartsWith("color-")); // Find the ones starting with "color" await user.RemoveRolesAsync(roles).ConfigureAwait(false); // add new color role to user await user.AddRoleAsync(role).ConfigureAwait(false); await Context.Channel.SendMessageAsync($"{user.Mention} now has the **{roleName}** role.").ConfigureAwait(false); }
public static Discord.Color GetRandomColour() { var random = new Random(); var hex = String.Format("#{0:X6}", random.Next(0x1000000)); // = "#A197B9" System.Drawing.Color hexColour = ColorTranslator.FromHtml(hex); Discord.Color c = new Discord.Color(hexColour.R, hexColour.G, hexColour.B); return(c); }
public override Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) { if (input.StartsWith("#")) { Dis.Color col = input.FromHex(); return(Task.FromResult(TypeReaderResult.FromSuccess(Color.FromArgb(col.R, col.G, col.B)))); } Color?result = null; if (!AngleSharp.Text.CharExtensions.IsDigit(input[0])) { result = Color.FromName(input); } if (result is not null) { return(Task.FromResult(TypeReaderResult.FromSuccess(result))); } string[] split; if (input.Contains(",")) { split = input.Split(","); } else { split = input.Split(" "); } split[0] = split[0].Replace(" ", ""); split[1] = split[1].Replace(" ", ""); split[2] = split[2].Replace(" ", ""); if (!int.TryParse(split[0], out int r)) { return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, $"`{input}` is not a valid Color Input"))); } if (!int.TryParse(split[1], out int g)) { return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, $"`{input}` is not a valid Color Input"))); } if (!int.TryParse(split[2], out int b)) { return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, $"`{input}` is not a valid Color Input"))); } result = Color.FromArgb(r, g, b); return(Task.FromResult(TypeReaderResult.FromSuccess(result.Value))); }
public static Embed ColoredMsg(string input, Discord.Color color) { var embed = new EmbedBuilder(); if (color == null) { color = Discord.Color.Magenta; } embed.WithColor(color); embed.Description = input; return(embed.Build()); }
public async Task Divorce([Remainder] string str = "") { //common variables IUser user = Context.User; EmbedBuilder eb = new EmbedBuilder(); Discord.Color userColour = ProfileDb.GetHex(out string colour, user.Id) ? (Discord.Color)UserUtil.HexToColor(colour) : BasicUtil.RandomColor(); eb.WithColor(userColour); eb.WithAuthor(user); var marriages = MarriageDb.GetMarriages(user.Id, Context.Guild.Id); var marriage = await UserUtil.SelectMarriage(marriages, this); if (marriage == null) { eb.WithDescription("~ You are not married ~"); await Context.Channel.SendMessageAsync($"", false, eb.Build()); return; } ulong wife = UserUtil.GetWifeId(marriage, user.Id); // //creating divorce action var divorce = new DialogueBoxOption { Action = async(IUserMessage message) => { await MarriageDb.DeleteMarriageOrProposal(marriage); await message.ModifyAsync((x) => x.Embed = eb.WithDescription($"You divorced **{ BasicUtil.IdToMention(wife) }**.\n*~ May you both find happiness elsewhere ~*").Build()); //execution condition }, After = OnExecute.RemoveReactions }; //creating cancel var cancel = new DialogueBoxOption { After = OnExecute.Delete }; //making dialog embed var dia = new DialogueBox(); dia.Options.Add(Emote.Parse("<:TickYes:577838859107303424>"), divorce); dia.Options.Add(Emote.Parse("<:TickNo:577838859077943306>"), cancel); dia.Timeout = new TimeSpan(0, 1, 0); dia.Embed = new EmbedBuilderPrepared(user) .WithColor(userColour) .WithDescription($"Are you sure you wish to Divorce **{ BasicUtil.IdToMention(wife) }**?").Build(); // await DialogueReplyAsync(dia); }
private void Embed_ColorMenu_SelectedColorChanged(object sender, ColorEventArgs e) { if (e.Color.IsEmpty) { Embed_ColorStrip.BackColor = new System.Drawing.Color(); EmbedColor = new Discord.Color(); } else { Embed_ColorStrip.BackColor = e.Color; EmbedColor = new Discord.Color(e.Color.R, e.Color.G, e.Color.B); } }
public Task GetRunDstAsync(params string[] args) { var runKind = (RunDisplayTypeBA)(-1); var color = new Color(); if (args.Length != 0) { try { runKind = (RunDisplayTypeBA)Enum.Parse(typeof(RunDisplayTypeBA), args[0], true); var runKindColor = RunDisplayTypes.GetColor(runKind); color = new Color(runKindColor.RGB[0], runKindColor.RGB[1], runKindColor.RGB[2]); } catch (ArgumentException) { /* Nothing to do */ } } var embed = new EmbedBuilder() .WithTitle($"Historical Scheduled Runs by Hour {(Enum.IsDefined(typeof(RunDisplayTypeBA), runKind) ? $"({runKind})" : string.Empty)}") .WithColor(Enum.IsDefined(typeof(RunDisplayTypeBA), runKind) ? color : Color.DarkTeal) .WithFooter("RSVP'd users may not be reflective of users who actually took part in a run."); var runsByHour = Db.Events .Where(@event => @event.Notified && !Enum.IsDefined(typeof(RunDisplayTypeBA), runKind) || @event.RunKind == runKind) .Select(@event => { var runTime = DateTime.FromBinary(@event.RunTime); return(new { Value = @event, Hour = runTime.Hour * 2 }); }) .GroupBy(kvp => kvp.Hour, kvp => kvp.Value) .OrderBy(bucket => bucket.Key); foreach (var runBucket in runsByHour) { var hour = runBucket.Key / 2; if (hour > 12) { hour -= 12; } var label = $"{hour}:00 {(runBucket.Key > 24 ? "PM" : "AM")}"; embed = embed.AddField(label, $"{runBucket.Count()} runs (Average {Math.Round(runBucket.Aggregate(0, (i, @event) => i += @event.SubscribedUsers.Count) / (double)runBucket.Count(), 2)} users per run)"); } return(ReplyAsync(embed: embed.Build())); }
public async Task CreateColor([Summary("The hex value of the Color Role.")] string colorValue, [Remainder, Summary("The name of the Color Role.")] string roleName) { if (Xml.CommandAllowed("create color", Context)) { try { colorValue = colorValue.Replace("#", ""); Discord.Color roleColor = new Discord.Color(uint.Parse(colorValue, NumberStyles.HexNumber)); await Context.Guild.CreateRoleAsync($"Color: {roleName}", null, roleColor); await Context.Channel.SendMessageAsync("Role successfully created!"); } catch { await Context.Channel.SendMessageAsync("Role couldn't be created. Make sure you entered a valid hexadecimal value!"); } } }
public async Task NewID([Remainder] int num) { AnonUser cur_user; if (GetUser(Context.User.Id) == null) // Does the user have an AnonUser profile? { activeUsers.Add(new AnonUser(Context.User.Id)); GetUser(Context.User.Id).lastNewID = DateTime.Now - (cooldown * 2); } cur_user = GetUser(Context.User.Id); if (cur_user.IsBlacklisted()) // Is this profile blacklisted? { await(Context.User).SendMessageAsync($"you are blacklisted"); return; } if (cur_user.IsTimedout()) // Is this profile timed out? { await(Context.User).SendMessageAsync($"you are timed out, wait {((GetUser(Context.User.Id).timeoutEnd) - DateTime.Now).Minutes} minutes and " + $"{((GetUser(Context.User.Id).timeoutEnd) - DateTime.Now).Seconds} seconds"); return; } if (DateTime.Now - cur_user.lastNewID < cooldown) // Is newID on cooldown? { await(Context.User).SendMessageAsync($"newID is on cooldown, wait {(cooldown - (DateTime.Now - GetUser(Context.User.Id).lastNewID)).Minutes} minutes and " + $"{(cooldown - (DateTime.Now - GetUser(Context.User.Id).lastNewID)).Seconds} seconds"); return; } if ((RecentlyUsed(num) || num < 0 || num > maxID)) // Is this ID taken or out of bounds? { await(Context.User).SendMessageAsync($"{num} is either taken or out of acceptable range"); return; } cur_user.NewAlias(num); cur_user.lastNewID = DateTime.Now; Discord.Color newColor = new Discord.Color(random.Next(255), random.Next(255), random.Next(255)); cur_user.message_color = newColor; await(Context.User).SendMessageAsync($"you are now speaking under id: `{num}`"); return; }
public async Task UpdateColor([Summary("The hex value of the Color Role.")] string colorValue, [Remainder, Summary("The name of the Color Role.")] string roleName) { if (Xml.CommandAllowed("update color", Context)) { var users = await Context.Guild.GetUsersAsync(); var colorRole = Context.Guild.Roles.FirstOrDefault(r => r.Name.ToUpper().Contains($"COLOR: {roleName.ToUpper()}")); if (users.Any(x => x.RoleIds.Contains(colorRole.Id) && x.Id != Context.User.Id)) { await Context.Channel.SendMessageAsync($"Role 'Color: {roleName}' is already in use by a different Member, so you can't update it. Try creating a new color role with ``?create color``"); } else { colorValue = colorValue.Replace("#", ""); Discord.Color roleColor = new Discord.Color(uint.Parse(colorValue, NumberStyles.HexNumber)); try { //Sort color roles by hue var lowestModeratorRole = Context.Guild.Roles.FirstOrDefault(x => !x.Permissions.Administrator).Position; await colorRole.ModifyAsync(r => r.Color = roleColor); await colorRole.ModifyAsync(r => r.Position = lowestModeratorRole - 1); await Context.Channel.SendMessageAsync("Role successfully updated!"); var orderedRoles = Context.Guild.Roles.Where(x => x.Name.StartsWith("Color: ")).OrderBy(x => System.Drawing.Color.FromArgb(x.Color.R, x.Color.R, x.Color.G, x.Color.B).GetHue()); //Try to move color role to highest spot possible foreach (var role in orderedRoles) { await role.ModifyAsync(x => x.Position = lowestModeratorRole - 1); } } catch { await Context.Channel.SendMessageAsync($"Role 'Color: {roleName}' couldn't be found. Make sure you entered the exact role name!"); } } } }
private async Task ChangeSonyaRoleColour(string inputColour) { try { var user = Context.User as SocketGuildUser; if (!user.Roles.Where(x => x.Name.ToLower() == "sonya").Any()) { return; } var sonyaRole = Helpers.ReturnRole(Context.Guild, "sonya"); string conversion = "0x" + inputColour.Replace("#", ""); var colorHex = Convert.ToUInt32(conversion, 16); var color = new Discord.Color(colorHex); if (colorHex != 0) { await sonyaRole.ModifyAsync(x => { x.Color = color; }); await Context.Channel.SendMessageAsync($"Colour successfully changed to {inputColour}"); } else { var insult = await Personality.Insults.GetInsult(); await Context.Channel.SendMessageAsync($"what the F**K is that supposed to be? retard {insult}"); } } catch (Exception ex) { await ExceptionHandler.HandleExceptionPublically(GetType().FullName, ExceptionHandler.GetAsyncMethodName(), ex); } }
// Prevent same colour twice in a row // Default colour to always allow the first colour selected // (black can never be selected, so the equality always fails) private static bool IsSameColorAs(Discord.Color A, Discord.Color B) => (A.R == B.R && A.B == B.B && A.G == B.G);
public Utility(IServiceProvider provider) { color = new Discord.Color(0, 138, 168); ISP = provider; DA = ISP.GetService <DataService>(); }
public async Task bomb_() { Discord.Color electricgreen = new Discord.Color(0x00ff00); UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Sheets API service. var service = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define request parameters. String spreadsheetId = "1S-AIIx2EQrLX8RHJr_AVIGPsQjehEdfUmbwKyinOs_I"; String america_bombs = "Bomb Table!B19:L29"; String germany_bombs = "Bomb Table!B33:L39"; String russia_bombs = "Bomb Table!B43:L54"; String britain_bombs = "Bomb Table!B58:L64"; String japan_bombs = "Bomb Table!B68:L81"; String italy_bombs = "Bomb Table!B85:L91"; String china_bombs = "Bomb Table!B95:L115"; String france_bombs = "Bomb Table!B119:L125"; String sweden_bombs = "Bomb Table!B128:L138"; //List of all countries. var countries = new List <string>() { "america", "germany", "russia", "britain", "japan", "italy", "china", "france", "sweden" }; var placeholder_list = new List <int>() { 0, 0, 0, 0, 0, 0 }; var placeholder_dict = new Dictionary <string, List <int> >() { { "bomb name", placeholder_list } }; //Dictionary that will hold every countries bomb data. IDictionary <string, Dictionary <string, List <int> > > bomb_data = new Dictionary <string, Dictionary <string, List <int> > >() { { "america", placeholder_dict }, { "germany", placeholder_dict }, { "russia", placeholder_dict }, { "britain", placeholder_dict }, { "japan", placeholder_dict }, { "italy", placeholder_dict }, { "china", placeholder_dict }, { "france", placeholder_dict }, { "sweden", placeholder_dict } }; //Function to get bomb data for each country given. void get_bomb_data(String country_bombs, string country) { var country_bomb_data = new Dictionary <string, List <int> >(); SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, country_bombs); ValueRange response = request.Execute(); IList <IList <Object> > values = response.Values; var bomb_values_list = new List <int>(); string bomb_name = ""; string bomb_values = ""; string first_value = ""; foreach (var row in values) { bomb_name = $"{row[0]}"; bomb_values = ""; first_value = $"{row[3]}"; if (bomb_values.Length == 0 && first_value.Length > 0) { bomb_values = $"{row[3]}"; } else { bomb_values = "0"; } for (int i = 4; i < 11; i++) { string item = $"{row[i]}"; if (item != null && item.Length > 0 && item != "You need a whole lotta these (only 30kg filler)" && item != "A whole lotta these (barely 10kg filler)" && item != "U.T." && item != "N/A") { string added_value = $"{bomb_values},{row[i]}"; bomb_values = added_value; } else { string added_value = $"{bomb_values},0"; bomb_values = added_value; } } List <int> bomb_values_int_list = new List <int>(Array.ConvertAll(bomb_values.Split(','), int.Parse)); country_bomb_data[bomb_name] = bomb_values_int_list; } bomb_data[country].Remove("bomb name"); bomb_data[country] = country_bomb_data; } //Gets bomb data for each country. get_bomb_data(america_bombs, "america"); get_bomb_data(germany_bombs, "germany"); get_bomb_data(russia_bombs, "russia"); get_bomb_data(britain_bombs, "britain"); get_bomb_data(japan_bombs, "japan"); get_bomb_data(italy_bombs, "italy"); get_bomb_data(china_bombs, "china"); get_bomb_data(france_bombs, "france"); get_bomb_data(sweden_bombs, "sweden"); //Embed maker helper function. string embed_maker(List <string> thing_list) { int list_number = 1; string embed = ""; foreach (string thing in thing_list) { string item = $"{list_number} = {thing.ToUpper()}\n"; embed += item; list_number += 1; } return(embed); } try { string countries_embed = embed_maker(countries); var builder = new EmbedBuilder(); builder.WithTitle("Select a country to view bombs from:"); builder.WithDescription(countries_embed); builder.WithColor(electricgreen); var embedvar = builder.Build(); await Context.Channel.SendMessageAsync("", false, embedvar); int country_number = 0; string country_number_string = ""; //Give them 5 tries to enter a number. for (int i = 0; i < 6; i++) { //Waits for the answer, makes sure it's the user who called the command, and gets the text if it was. var result = await InteractiveService.NextMessageAsync(x => x.Author.Id == Context.User.Id); if (result.IsSuccess) { //Text from user. country_number_string = result.Value.Content; } else { await Context.Channel.SendMessageAsync("Unable to get user answer."); return; } //Converting to int. bool isParsable = Int32.TryParse(country_number_string, out country_number); //If it converts, break the loop and keep going. if (isParsable) { break; } //If it doesn't, they didn't enter a number. Restart the loop. else { await Context.Channel.SendMessageAsync("Please use a number."); } continue; } //If they don't use a number after 5 tries just exit the command. They need help :D. if (country_number == 0) { await Context.Channel.SendMessageAsync("You didn't use a number. Goodbye."); return; } bool did_it_find_the_countries_bombs = false; //Bomb names list helper function. Embed get_bomb_names(int number) { int actual_country_number = number - 1; string country = countries[actual_country_number]; var bomb_names = new List <string>(); foreach (KeyValuePair <string, List <int> > bomb_ in bomb_data[country]) { bomb_names.Add(bomb_.Key); } string bomb_names_embed = embed_maker(bomb_names); var country_builder = new EmbedBuilder(); string country_name = countries[actual_country_number]; country_builder.WithTitle($"Select a bomb to view from {country_name.ToUpper()}:"); country_builder.WithDescription(bomb_names_embed); country_builder.WithColor(electricgreen); var country_bombs_embed = country_builder.Build(); did_it_find_the_countries_bombs = true; return(country_bombs_embed); } //Sends the bombs list for the country they selected. if (country_number == 1) { var country1_bomb_names = get_bomb_names(country_number); await Context.Channel.SendMessageAsync("", false, country1_bomb_names); } if (country_number == 2) { var country2_bomb_names = get_bomb_names(country_number); await Context.Channel.SendMessageAsync("", false, country2_bomb_names); } if (country_number == 3) { var country1_bomb_names = get_bomb_names(country_number); await Context.Channel.SendMessageAsync("", false, country1_bomb_names); } if (country_number == 4) { var country1_bomb_names = get_bomb_names(country_number); await Context.Channel.SendMessageAsync("", false, country1_bomb_names); } if (country_number == 5) { var country1_bomb_names = get_bomb_names(country_number); await Context.Channel.SendMessageAsync("", false, country1_bomb_names); } if (country_number == 6) { var country1_bomb_names = get_bomb_names(country_number); await Context.Channel.SendMessageAsync("", false, country1_bomb_names); } if (country_number == 7) { var country1_bomb_names = get_bomb_names(country_number); await Context.Channel.SendMessageAsync("", false, country1_bomb_names); } if (country_number == 8) { var country1_bomb_names = get_bomb_names(country_number); await Context.Channel.SendMessageAsync("", false, country1_bomb_names); } if (country_number == 9) { var country1_bomb_names = get_bomb_names(country_number); await Context.Channel.SendMessageAsync("", false, country1_bomb_names); } if (did_it_find_the_countries_bombs == false) { await Context.Channel.SendMessageAsync("Couldn't find that country's bombs."); return; } int bomb_number = 0; string bomb_number_string = ""; //Give them 5 tries to enter a number to get the bomb number. for (int i = 0; i < 6; i++) { //Waits for the answer, makes sure it's the user who called the command, and gets the text if it was. var result = await InteractiveService.NextMessageAsync(x => x.Author.Id == Context.User.Id); if (result.IsSuccess) { //Text from user. bomb_number_string = result.Value.Content; } else { await Context.Channel.SendMessageAsync("Unable to get user answer."); return; } //Converting to int. bool isParsable = Int32.TryParse(bomb_number_string, out bomb_number); //If it converts, break the loop and keep going. if (isParsable) { break; } //If it doesn't, they didn't enter a number. Restart the loop. else { await Context.Channel.SendMessageAsync("Please use a number."); } continue; } //If they don't use a number after 5 tries just exit the command. They need help :D. if (bomb_number == 0) { await Context.Channel.SendMessageAsync("You didn't use a number. Goodbye."); return; } string bomb_type = ""; var bomb_names_list = new List <string>(); foreach (KeyValuePair <string, List <int> > bomb_name_ in bomb_data[countries[country_number - 1]]) { bomb_names_list.Add(bomb_name_.Key); } int number_of_bombs_plus1 = bomb_names_list.Count + 1; for (int x = 0; x < number_of_bombs_plus1; x++) { if (bomb_number == x) { bomb_type = bomb_names_list[x - 1]; } } await Context.Channel.SendMessageAsync("Enter max battle rating in match:"); double battle_rating = 0; string battle_rating_string = ""; //Give them 5 tries to enter a number to get the battle rating. for (int i = 0; i < 6; i++) { //Waits for the answer, makes sure it's the user who called the command, and gets the text if it was. var result = await InteractiveService.NextMessageAsync(x => x.Author.Id == Context.User.Id); if (result.IsSuccess) { //Text from user. battle_rating_string = result.Value.Content; } else { await Context.Channel.SendMessageAsync("Unable to get user answer."); return; } //Converting to int. try { //If it converts, break the loop and keep going. battle_rating = Convert.ToDouble(battle_rating_string); break; } catch (Exception e) { //If it doesn't, they didn't enter a number. Restart the loop. await Context.Channel.SendMessageAsync("Please use a decimal number."); continue; } } //If they don't use a number after 5 tries just exit the command. They need help :D. if (battle_rating == 0) { await Context.Channel.SendMessageAsync("You didn't use a decimal number. Goodbye."); return; } //Check if they need 4 base map data. await Context.Channel.SendMessageAsync("Is this a four base map? Enter 'YES' or 'NO'"); //Gets the users answer and makes sure it's "YES" or "NO". string is_it_a_four_base = ""; for (int i = 0; i < 6; i++) { //Waits for the answer, makes sure it's the user who called the command, and gets the text if it was. var result = await InteractiveService.NextMessageAsync(x => x.Author.Id == Context.User.Id); if (result.IsSuccess) { //Text from user. is_it_a_four_base = result.Value.Content; } else { await Context.Channel.SendMessageAsync("Unable to get user answer."); return; } if (is_it_a_four_base.ToUpper() == "YES" | is_it_a_four_base.ToUpper() == "NO") { break; } else { await Context.Channel.SendMessageAsync("Please enter 'YES or 'NO'."); continue; } } //If they don't use a number after 5 tries just exit the command. They need help :D. if (is_it_a_four_base == "") { await Context.Channel.SendMessageAsync("You didn't use a decimal number. Goodbye."); return; } var base_bombs_list = new List <int>(); base_bombs_list = bomb_data[countries[country_number - 1]][bomb_type]; string four_base = is_it_a_four_base.ToUpper(); int base_bombs_required = 0; int airfield_bombs_required = 0; try { if (1.0 <= battle_rating && battle_rating <= 2.0) { if (four_base == "YES") { base_bombs_required = base_bombs_list[0]; airfield_bombs_required = base_bombs_required * 5; } else { base_bombs_required = base_bombs_list[1]; airfield_bombs_required = base_bombs_required * 5; } } if (2.3 <= battle_rating && battle_rating <= 3.3) { if (four_base == "YES") { base_bombs_required = base_bombs_list[2]; airfield_bombs_required = base_bombs_required * 6; } else { base_bombs_required = base_bombs_list[3]; airfield_bombs_required = base_bombs_required * 6; } } if (3.7 <= battle_rating && battle_rating <= 4.7) { if (four_base == "YES") { base_bombs_required = base_bombs_list[4]; airfield_bombs_required = base_bombs_required * 8; } else { base_bombs_required = base_bombs_list[5]; airfield_bombs_required = base_bombs_required * 8; } } if (5.0 <= battle_rating) { if (four_base == "YES") { base_bombs_required = base_bombs_list[6]; airfield_bombs_required = base_bombs_required * 15; } else { base_bombs_required = base_bombs_list[7]; airfield_bombs_required = base_bombs_required * 15; } } if (base_bombs_required == 0 | airfield_bombs_required == 0) { await Context.Channel.SendMessageAsync("This bomb data hasn't been added to the spreadsheet yet. If you are requesting a 4 base map, it may be too soon. Please refer to 3 base map data and multiply it by 2x for each base to get approximate 4 base data."); return; } } catch (Exception e) { await Context.Channel.SendMessageAsync("That battle rating doesn't exist."); return; } await Context.Channel.SendMessageAsync($"Bombs required for bases: {base_bombs_required}\nBombs required for airfield: {airfield_bombs_required}"); } catch (Exception e) { await Context.Channel.SendMessageAsync("User error, try again."); Console.WriteLine(e); } // Prints all bombs in each country and their values to the console. /* * string bomb_display = ""; * foreach (string country in countries) * { * Console.WriteLine($"\n{country.ToUpper()}"); * foreach (var bomb in bomb_data[country]) * { * bomb_display = ""; * foreach (int i in bomb.Value) * { * if (bomb_display.Length > 0) * { * string added_value = $"{bomb_display}, {i}"; * bomb_display = added_value; * } * else * bomb_display = $"{i}"; * } * Console.WriteLine($"{bomb.Key}: {bomb_display}"); * } * } */ Console.Read(); }
public ColorDefinition(string name, Color color) { Name = name; Id = name.ToLowerInvariant(); Color = color; }