Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace Larpl.Extensions
- {
- public static class DiscordExtensions
- {
- static void ValidateEmbed(dynamic d, out bool has_fields, out bool has_timestamp, out bool has_color, out bool has_description)
- {
- try { has_fields = !(d.fields is null); }
- catch { has_fields = false; }
- try { has_timestamp = !(d.timestamp is null); }
- catch { has_timestamp = false; }
- try { has_color = !(d.color is null); }
- catch { has_color = false; }
- try { has_description = !(d.description is null); }
- catch { has_description = false; }
- }
- public static DiscordEmbedBuilder CreateNewDynamicEmbed(dynamic d)
- {
- var temp = new DiscordEmbedBuilder();
- if (d is null)
- return temp;
- ValidateEmbed(d, out bool has_fields,
- out bool has_timestamp,
- out bool has_color,
- out bool has_description);
- if (has_fields)
- {
- foreach(var field in d.fields)
- {
- string name = default;
- string value = default;
- bool is_inline = default;
- if (Dynamic_IsValidEmbedField(field, ref name, ref value, ref is_inline))
- {
- temp.AddField($"{ZERO_WIDTH_SPACE}{name}", $"{ZERO_WIDTH_SPACE}{value}", is_inline);
- }
- }
- }
- if(has_color)
- {
- if (d.color is string hex)
- temp.WithColor(new DiscordColor(hex));
- else if(d.color is int value)
- temp.WithColor(new DiscordColor(value));
- else if(d.color is int[] ivec && ivec.Length >= 3)
- {
- var r = ivec[0];
- var g = ivec[1];
- var b = ivec[2];
- temp.WithColor(new DiscordColor(r, g, b));
- }
- else if(d.color is float[] fvec && fvec.Length >= 3)
- {
- var r = fvec[0];
- var g = fvec[1];
- var b = fvec[2];
- temp.WithColor(new DiscordColor(r, g, b));
- }
- }
- if(has_timestamp)
- {
- if (d.timestamp is DateTime dt)
- temp.WithTimestamp(dt);
- else if(d.timestamp is DateTimeOffset dto)
- temp.WithTimestamp(dto);
- else if (d.timestamp is ulong unix)
- temp.WithTimestamp(unix);
- }
- if(has_description)
- {
- temp.WithDescription($"{ZERO_WIDTH_SPACE}{Convert.ToString(d.description)}");
- }
- return temp;
- }
- static bool Dynamic_IsValidEmbedField(dynamic field, ref string name, ref string value, ref bool inline)
- {
- var state = !(field is null) && !(field.name is null) && !(field.value is null);
- if (state)
- {
- name = Convert.ToString(field.name);
- value = Convert.ToString(field.value);
- try
- {
- inline = field.inline;
- }
- catch
- {
- inline = false;
- }
- }
- return state;
- }
- public static async Task<DiscordMessage> DynamicRespondAsync(this CommandContext ctx, string content = default, dynamic embed = default)
- {
- return await ctx.RespondAsync(content, false, CreateNewDynamicEmbed(embed));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement