public static EmbedFieldBuilder ToBuilder(this EmbedField field)
 => new EmbedFieldBuilder()
 {
     IsInline = field.Inline,
     Name     = field.Name,
     Value    = field.Value
 };
Ejemplo n.º 2
0
        private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            var msg = await arg1.DownloadAsync();

            var user  = arg3.User.Value;
            var emote = arg3.Emote;

            if (BotReactions.ViewMessage.Equals(emote) && !user.IsBot)
            {
                if (msg.Author.Id == Client.CurrentUser.Id && msg.Embeds.Any())
                {
                    IEmbed encipheredEmbed = msg.Embeds.First();
                    if (encipheredEmbed.Fields.Any())
                    {
                        EmbedField field = encipheredEmbed.Fields[0];
                        if (field.Name == EncipheredTitle)
                        {
                            DateTime dateTime   = encipheredEmbed.Timestamp.Value.DateTime;
                            string   enciphered = Desanitize(field.Value);
                            string   deciphered = Decipher(enciphered, dateTime, false);

                            var          author = encipheredEmbed.Author.Value;
                            EmbedBuilder embed  = new EmbedBuilder();
                            embed.WithColor(EmbedColor);
                            embed.WithAuthor(author.Name, author.IconUrl, author.Url);
                            embed.WithTimestamp(encipheredEmbed.Timestamp.Value);
                            embed.AddField(DecipheredTitle, deciphered);
                            var dm = await arg3.User.Value.GetOrCreateDMChannelAsync();

                            await dm.SendMessageAsync(null, false, embed.Build());
                        }
                    }
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates a UIElement (StackPanel) for field in Embed
        /// </summary>
        /// <param name="field">Field to add</param>
        /// <returns>StackPanel display of field</returns>
        private StackPanel GenerateField(EmbedField field)
        {
            StackPanel sp = new StackPanel();

            if (field.Name != null)
            {
                sp.Children.Add(new MarkdownTextBlock.MarkdownTextBlock()
                {
                    Text = field.Name, FontSize = 13, EnableHiddenLinks = true, FontWeight = FontWeights.SemiBold
                });
            }
            if (field.Value != null)
            {
                sp.Children.Add(new MarkdownTextBlock.MarkdownTextBlock()
                {
                    Text = field.Value, FontSize = 13, Opacity = 0.75, EnableHiddenLinks = true
                });
            }
            if (field.Inline)
            {
                sp.MinWidth = 150;
                sp.MaxWidth = 204;
            }
            sp.Margin = new Thickness(0, 6, 0, 0);
            return(sp);
        }
Ejemplo n.º 4
0
        public FieldViewer(IMessage msg, EmbedField field)
        {
            InitializeComponent();

            message  = msg;
            embField = field;

            if (field.Name != null)
            {
                Title.Text = field.Name;
            }
            else
            {
                Title.Visibility = Visibility.Hidden;
            }

            if (field.Value != null)
            {
                Content.Document = (FlowDocument)(App.Current.Resources["TextToFlowDocumentConverter"] as TextToFlowDocumentConverter).Convert(field.Value, typeof(FlowDocument), null, null);
            }
            else
            {
                Content.Visibility = Visibility.Hidden;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Make StackPanel control from <paramref name="field"/>
        /// </summary>
        /// <param name="field">Field to parse</param>
        /// <returns>StackPanel of Field Control</returns>
        private StackPanel GenerateField(EmbedField field)
        {
            StackPanel sp = new StackPanel();

            // If there's a name, add a name
            if (field.Name != null)
            {
                sp.Children.Add(new MarkdownTextBlock.MarkdownTextBlock()
                {
                    Text = field.Name, FontSize = 13, EnableHiddenLinks = true, FontWeight = FontWeights.SemiBold
                });
            }

            // If there's content, add content
            if (field.Value != null)
            {
                sp.Children.Add(new MarkdownTextBlock.MarkdownTextBlock()
                {
                    Text = field.Value, FontSize = 13, Opacity = 0.75, EnableHiddenLinks = true
                });
            }

            // If it's line, set a max width a height
            if (field.Inline)
            {
                sp.MinWidth = 150;
                sp.MaxWidth = 204;
            }

            // Add margin
            sp.Margin = new Thickness(0, 6, 0, 0);

            return(sp);
        }
Ejemplo n.º 6
0
 private RocketLeagueRanks getRank(EmbedField field)
 {
     if (field.Value.Contains("Unranked"))
     {
         return(RocketLeagueRanks.Unranked);
     }
     else if (field.Value.Contains("Bronze"))
     {
         return(RocketLeagueRanks.Bronze);
     }
     else if (field.Value.Contains("Silver"))
     {
         return(RocketLeagueRanks.Silver);
     }
     else if (field.Value.Contains("Gold"))
     {
         return(RocketLeagueRanks.Gold);
     }
     else if (field.Value.Contains("Platinum"))
     {
         return(RocketLeagueRanks.Platinum);
     }
     else if (field.Value.Contains("Diamond"))
     {
         return(RocketLeagueRanks.Diamond);
     }
     else if (field.Value.Contains("Grand Champion"))
     {
         return(RocketLeagueRanks.GrandChamp);
     }
     else
     {
         return(RocketLeagueRanks.Champ);
     }
 }
Ejemplo n.º 7
0
        protected async Task <bool> RemoveAsync(IMessageChannel channel, ulong msgId, string footer, string title)
        {
            if (!(await InitMessage(channel, msgId, new string[] { footer }, false)))
            {
                return(false);
            }

            EmbedBuilder builder = new EmbedBuilder();

            builder.WithAuthor(new EmbedAuthorBuilder().WithName(_oldEmbed.Author.Value.Name).WithIconUrl(_oldEmbed.Author.Value.IconUrl));
            builder.WithFooter(footer);

            List <EmbedField> deletedFields = _oldEmbed.Fields.Where(em => em.Name == title).ToList();

            if (deletedFields.Count < 1)
            {
                await ReplyAsync(database["string", "errEntryNotInMessage"]);

                return(false);
            }
            EmbedField deletedField = deletedFields[0];

            foreach (EmbedField f in _oldEmbed.Fields)
            {
                if (f.Name != title)
                {
                    builder.AddField(f.Name, f.Value);
                }
            }

            _newEmbed = builder.Build();
            await _msg.ModifyAsync(m => m.Embed = _newEmbed);

            return(true);
        }
Ejemplo n.º 8
0
 public static EmbedFieldModel ToModel(this EmbedField field)
 => field == null ? null : new EmbedFieldModel
 {
     Name   = field.Name,
     Value  = field.Value,
     Inline = field.IsInline
 };
        private static List <EmbedField> ExtractRepoChangesField(IEnumerable <BitbucketServerChange> changes)
        {
            var fieldList   = new List <EmbedField>();
            var changeCount = 0;

            foreach (var change in changes)
            {
                changeCount++;

                if (changeCount > 10)
                {
                    break;
                }

                var branch = change.Ref.DisplayId;
                var hash   = change.ToHash.Substring(0, 10);
                var type   = change.Type;

                var field = new EmbedField
                {
                    Name  = "Change",
                    Value = $"**Branch**: {branch}\n" +
                            $"**New Hash**: {hash}\n" +
                            $"**Type**: {type}"
                };

                fieldList.Add(field);
            }

            return(fieldList);
        }
Ejemplo n.º 10
0
        public static Asset FromEmbed(IServiceProvider Services, IEmbed embed)
        {
            var game  = Utilities.GetGameContainedInString(embed.Footer.Value.Text ?? string.Empty);
            var asset = Services.GetRequiredService <List <Asset> >().Single(a => embed.Title.Contains(a.Name) && a.Game == game).DeepCopy();

            for (int i = 0; i < asset.AssetFields.Count; i++)
            {
                EmbedField embedField = embed.Fields.FirstOrDefault(fld => fld.Name.Contains((i + 1).ToString()));

                if (embedField.Value == null)
                {
                    embedField = embed.Fields.FirstOrDefault(fld => fld.Value.Contains(asset.AssetFields[i].Text));                           //match old style assets
                }
                if (embedField.Value == null)
                {
                    continue;
                }

                asset.AssetFields[i].Enabled = embedField.Name.Contains(AssetEnabledEmoji) || embedField.Name.Contains(OldAssetEnabledEmoji);
            }

            if (asset.NumericAssetTrack != null)
            {
                var field = embed.Fields.First(f => f.Name == asset.NumericAssetTrack.Name);
                var match = Regex.Match(field.Value, @"__\*\*(\d+)\*\*__");
                int value = 0;
                if (match.Success)
                {
                    int.TryParse(match.Groups[1].Value, out value);
                }
                asset.NumericAssetTrack.ActiveNumber = value;
            }

            if (asset.CountingAssetTrack != null)
            {
                var field = embed.Fields.First(f => f.Name == asset.CountingAssetTrack.Name);
                var match = Regex.Match(field.Value, @"-?\d+");
                int value = 0;
                if (match.Success)
                {
                    int.TryParse(match.Groups[0].Value, out value);
                }
                asset.CountingAssetTrack.StartingValue = value;
            }

            if (asset.MultiFieldAssetTrack != null)
            {
                foreach (var assetField in asset.MultiFieldAssetTrack.Fields)
                {
                    assetField.IsActive = embed.Fields.Any(f => assetField.Name.Contains(f.Name, StringComparison.OrdinalIgnoreCase) && assetField.ActiveText.Contains(f.Value, StringComparison.OrdinalIgnoreCase));
                }
            }

            foreach (var input in asset.InputFields)
            {
                string partialFormated = string.Format(AssetResources.UserInputField, input, ".*");
                var    match           = Regex.Match(embed.Description, partialFormated);
                if (match.Success && match.Value.UndoFormatString(AssetResources.UserInputField, out string[] descValues, true))
Ejemplo n.º 11
0
        public static EmbedFieldBuilder CreateFieldBuilder(EmbedField embedField)
        {
            EmbedFieldBuilder builder = new EmbedFieldBuilder();
            
            builder.Name = embedField.Name;

            builder.Value = embedField.Value;

            return builder;
        }
        private void WriteEmbedField(EmbedField embedField)
        {
            _writer.WriteStartObject();

            _writer.WriteString("name", FormatMarkdown(embedField.Name));
            _writer.WriteString("value", FormatMarkdown(embedField.Value));
            _writer.WriteBoolean("isInline", embedField.IsInline);

            _writer.WriteEndObject();
        }
Ejemplo n.º 13
0
 public static async Task RfrDelRoleAsync(IEmbed embed, SocketReaction reaction)
 {
     Console.WriteLine($"Embed fields: {embed.Fields.Count()}");
     EmbedField field   = embed.Fields.First(f => f.Value.StartsWith(reaction.Emote.ToString()));
     int        atIndex = field.Value.IndexOf('@');
     ulong      roleId  = Convert.ToUInt64(field.Value.Remove(0, atIndex + 2).TrimEnd('>').ToString());
     IGuildUser user    = reaction.User.Value as IGuildUser;
     IRole      role    = user.Guild.Roles.First(r => r.Id == roleId);
     await user.RemoveRoleAsync(role);
 }
        private async ValueTask WriteEmbedFieldAsync(EmbedField embedField)
        {
            _writer.WriteStartObject();

            _writer.WriteString("name", FormatMarkdown(embedField.Name));
            _writer.WriteString("value", FormatMarkdown(embedField.Value));
            _writer.WriteBoolean("isInline", embedField.IsInline);

            _writer.WriteEndObject();
            await _writer.FlushAsync();
        }
Ejemplo n.º 15
0
 private EmbedFieldBuilder EditField(EmbedField field, string emoteName, bool addReaction, int counter, int id, ulong guildId)
 {
     if (counter == id)
     {
         bool   found          = false;
         string finalStr       = "";
         string emoteSmallName = emoteName;
         Match  match          = Regex.Match(emoteSmallName, "<(:[^:]+:)[0-9]+>");
         if (match.Success)
         {
             emoteSmallName = match.Groups[1].Value;
         }
         foreach (string s in field.Value.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
         {
             if (s == Sentences.NothingYet(guildId))
             {
                 continue;
             }
             string[] emote = s.Split(' ');
             if (emote[0] == emoteName || emote[0] == emoteSmallName)
             {
                 int newNb = Convert.ToInt32(emote[1].Substring(1, emote[1].Length - 1)) + ((addReaction) ? (1) : (-1));
                 if (newNb > 0)
                 {
                     finalStr += emote[0] + " x" + newNb + Environment.NewLine;
                 }
                 found = true;
             }
             else
             {
                 finalStr += s + Environment.NewLine;
             }
         }
         if (!found)
         {
             finalStr += emoteName + " x1" + Environment.NewLine;
         }
         if (finalStr == "")
         {
             finalStr = Sentences.NothingYet(guildId);
         }
         return(new EmbedFieldBuilder()
         {
             Name = field.Name,
             Value = finalStr
         });
     }
     return(new EmbedFieldBuilder()
     {
         Name = field.Name,
         Value = field.Value
     });
 }
        private List <EmbedField> ExtractPullRequestFields(BitbucketServerPullRequest pullRequest)
        {
            var fieldList = new List <EmbedField>();
            var fromField = new EmbedField
            {
                Name  = "From",
                Value = pullRequest.FromRef.DisplayId
            };

            var toField = new EmbedField
            {
                Name  = "To",
                Value = pullRequest.ToRef.DisplayId
            };

            fieldList.Add(fromField);
            fieldList.Add(toField);

            var fieldCount = 0;

            foreach (var reviewer in pullRequest.Reviewers)
            {
                fieldCount++;

                if (fieldCount > 10)
                {
                    break;
                }
                if (Environment.GetEnvironmentVariable("ALLOW_REAL_NAMES") == "true")
                {
                    var reviewerField = new EmbedField
                    {
                        Name  = "Reviewer",
                        Value = reviewer.User.DisplayName
                    };

                    fieldList.Add(reviewerField);
                }
                else
                {
                    var reviewerField = new EmbedField
                    {
                        Name  = "Reviewer Status",
                        Value = reviewer.Status
                    };

                    fieldList.Add(reviewerField);
                }
            }

            return(fieldList);
        }
Ejemplo n.º 17
0
        public async Task CommandList(Message message)
        {
            EmbedField[] commands = this.GetType().GetMethods()
                                    .Where(m => m.GetCustomAttributes(true).Length != 0)
                                    .Select(m => (
                                                ((CommandAttr)m.GetCustomAttributes(true).Single(a => a is CommandAttr))))
                                    .Where(a => !(a.Names.Contains(CommandInterface.UnknownCommandKey)))
                                    .Select(a => EmbedField.Build((a.Names.Length > 1) ? $"__**{a.Names[0]}**__ ({String.Join(",", a.Names.Skip(1))})" : $"__**{a.Names[0]}**__", a.Info))
                                    .ToArray();

            Embed temp = Embed.Build(title: "__***List of Commands***__", fields: commands);
            await http.CreateMessage(message, Outbound_Message.Build(embed : temp).Serialize());
        }
Ejemplo n.º 18
0
        private async Task <Task> ClearReactionsAfterDelay(ISocketMessageChannel channel)
        {
            while (activeMBEmbeds.Count > 0)
            {
                Log.Write("MB Windows - Checking For Inactive MB Windows from total of " + activeMBEmbeds.Count, "Bot");

                DateTime runTime = DateTime.Now;

                foreach (KeyValuePair <ulong, ActiveMBWindow> mb in activeMBEmbeds)
                {
                    if ((runTime - mb.Value.LastInteractedWith).TotalSeconds > 20)
                    {
                        Log.Write("MB Windows - Clearing MB Command: " + mb.Key, "Bot");

                        IMessage message = await channel.GetMessageAsync(mb.Key);

                        // Convert to UserMessage so we can edit the embed to remove the react help message
                        if (message is IUserMessage userMessage)
                        {
                            // Get the embed and duplicate
                            IEmbed       embed   = message.Embeds.FirstOrDefault();
                            EmbedBuilder builder = new EmbedBuilder()
                                                   .WithTitle(embed.Title)
                                                   .WithColor(embed?.Color ?? Color.Teal)
                                                   .WithDescription(embed?.Description)
                                                   .WithThumbnailUrl(embed?.Thumbnail?.Url ?? string.Empty);

                            // Get MB field and duplicate - remove reaction hint text
                            EmbedField field = embed?.Fields.GetFirst() ?? default;
                            builder.AddField(new EmbedFieldBuilder()
                                             .WithName(field.Name)
                                             .WithValue(field.Value.Substring(0, field.Value.Length - 124)));

                            await userMessage.ModifyAsync(x => x.Embed = builder.Build());
                        }

                        // Remove reactions
                        await message.RemoveAllReactionsAsync();

                        activeMBEmbeds.Remove(mb.Key);
                    }
                }

                Log.Write("MB Windows - Begin Wait", "Bot");
                await Task.Delay(15000);
            }

            Log.Write("MB Windows - All MB Windows Inactive", "Bot");
            Program.DiscordClient.ReactionAdded -= this.OnReactionAdded;
            return(Task.CompletedTask);
        }
Ejemplo n.º 19
0
        protected async Task <bool> PositionAsync(IMessageChannel channel, string footer, ulong msgId, string title, int position)
        {
            if (!(await InitMessage(channel, msgId, new string[] { footer, "React-for-Role" }, false)))
            {
                return(false);
            }

            if (position > 20 || position > _oldEmbed.Fields.Length)
            {
                await ReplyAsync(database["string", "errTooManyFields"]);

                return(false);
            }

            EmbedBuilder builder = new EmbedBuilder();

            builder.WithAuthor(new EmbedAuthorBuilder().WithName(_oldEmbed.Author.Value.Name).WithIconUrl(_oldEmbed.Author.Value.IconUrl));
            builder.WithFooter(footer);

            List <EmbedField> fields = _oldEmbed.Fields.Where(em => em.Name == title).ToList();

            if (fields.Count < 1)
            {
                await ReplyAsync(database["string", "errEntryNotInMessage"]);

                return(false);
            }
            EmbedField field = fields[0];

            for (int i = 0; i < _oldEmbed.Fields.Length; i++)
            {
                EmbedField f = _oldEmbed.Fields[i];
                if (f.Name != title)
                {
                    builder.AddField(f.Name, f.Value);
                }
                if (i + 1 == position)
                {
                    builder.AddField(field.Name, field.Value);
                }
            }
            _newEmbed = builder.Build();
            await _msg.ModifyAsync(m => m.Embed = _newEmbed);

            return(true);
        }
Ejemplo n.º 20
0
        public static async Task RfrAddRoleAsync(IEmbed embed, SocketReaction reaction)
        {
            IGuildUser      user     = reaction.User.Value as IGuildUser;
            dbWalrusContext database = new dbWalrusContext();

            if (user.GuildId == Convert.ToUInt64(database["config", "svgeServerId"]) && // if this is the main server (means it can be used in other servers)
                !user.RoleIds.Contains <ulong>(Convert.ToUInt64(database["role", "communityMember"])) && // and they don't have community membership
                !user.RoleIds.Contains <ulong>(Convert.ToUInt64(database["role", "student"])))
            {
                return;                                                                                   // and aren't a student, then don't give a role.
            }
            EmbedField field   = embed.Fields.First(f => f.Value.StartsWith(reaction.Emote.ToString()));
            int        atIndex = field.Value.IndexOf('@');
            ulong      roleId  = Convert.ToUInt64(field.Value.Remove(0, atIndex + 2).TrimEnd('>').ToString());
            IRole      role    = user.Guild.Roles.First(r => r.Id == roleId);
            await user.AddRoleAsync(role);
        }
Ejemplo n.º 21
0
        private async Task OnReactionAddedAsync(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            var msg = await arg1.DownloadAsync().ConfigureAwait(false);

            var user  = arg3.User.Value;
            var emote = arg3.Emote;

            if (EnigmaReactions.ViewMessage.Equals(emote) && !user.IsBot)
            {
                if (msg.Author.Id == Client.CurrentUser.Id && msg.Embeds.Any())
                {
                    IEmbed encipheredEmbed = msg.Embeds.First();
                    if (encipheredEmbed.Title == EncipheredTitle)
                    {
                        EmbedField field     = encipheredEmbed.Fields.FirstOrDefault();
                        RotorKeys  rotorKeys = this.rotorKeys;
                        if (encipheredEmbed.Fields.Any() && field.Name == RotorKeysTitle)
                        {
                            rotorKeys = ParseRotorKeys(field.Value);
                        }
                        Machine machine = new Machine(new SetupArgs {
                            LetterSet  = letterSet,
                            Steckering = steckering,
                            RotorKeys  = rotorKeys,
                        });
                        string enciphered = Desanitize(encipheredEmbed.Description);
                        string deciphered = machine.Decipher(enciphered);

                        var          author = encipheredEmbed.Author.Value;
                        EmbedBuilder embed  = new EmbedBuilder {
                            Title       = DecipheredTitle,
                            Color       = configParser.EmbedColor,
                            Timestamp   = encipheredEmbed.Timestamp.Value,
                            Description = deciphered,
                        };
                        embed.WithAuthor(author.Name, author.IconUrl, author.Url);
                        var dm = await arg3.User.Value.GetOrCreateDMChannelAsync().ConfigureAwait(false);

                        await dm.SendMessageAsync(embed : embed.Build()).ConfigureAwait(false);
                    }
                }
            }
        }
Ejemplo n.º 22
0
 private void processField(EmbedField field)
 {
     if (field.Name.Equals("Solo"))
     {
         duel = getRank(field);
     }
     else if (field.Name.Equals("Doubles"))
     {
         doubles = getRank(field);
     }
     else if (field.Name.Equals("Solo Standard"))
     {
         soloStandard = getRank(field);
     }
     else if (field.Name.Equals("Standard"))
     {
         standard = getRank(field);
     }
 }
Ejemplo n.º 23
0
        public async Task TopCrypto(int num = 0)
        {
            List <CoinMarketCap.Currency> currencies = CoinMarketCap.GetTop10();
            string msg   = "";
            int    count = 0;

            EmbedField[] fields = new EmbedField[(num == 0) ? 10 : num];
            foreach (CoinMarketCap.Currency currency in currencies)
            {
                msg += "\n\n__" + currency.name + "__";
                msg += "\n**Symbol:** " + currency.symbol;
                msg += "\n**Rank:** " + currency.cmc_rank;

                double price       = currency.quote.USD.price;
                string priceString = string.Format("${0:N2}", price);
                if (price <= 1.99)
                {
                    priceString = string.Format("${0:N6}", price);
                }
                else if (price <= 9.99)
                {
                    priceString = string.Format("${0:N3}", price);
                }
                msg += "\n**Price:** " + priceString;
                msg += "\n**Market Cap:** " + string.Format("${0:N2}", currency.quote.USD.market_cap);
                msg += "\n**Volume 24h:** " + string.Format("${0:N2}", currency.quote.USD.volume_24h);
                msg += "\n**Change 1h:** " + string.Format("{0:N2}%", currency.quote.USD.percent_change_1h);
                msg += "\n**Change 24h:** " + string.Format("{0:N2}%", currency.quote.USD.percent_change_24h);
                msg += "\n**Change 7d:** " + string.Format("{0:N2}%", currency.quote.USD.percent_change_7d);
                msg += "\n**Circulating Supply:** " + currency.circulating_supply;
                string max_supply = "None";
                if (currency.max_supply != null)
                {
                    max_supply = "" + currency.max_supply;
                }
                msg += "\n**Max Supply:** " + max_supply;
                if (num != 0)
                {
                    num--;
                    if (num <= 0)
                    {
                        break;
                    }
                }
                count++;
                if (count >= 6)
                {
                    msg  += "|";
                    count = 0;
                }
            }

            string[] split = msg.Split('|');
            for (int i = 0; i < split.Length; i++)
            {
                string title = "Top 10 Crypto";
                if (num != 0)
                {
                    title = "Top " + num + " Crypto";
                }
                await PrintEmbedMessage("Top Crypto", split[i]);
            }

            //await Context.Channel.SendMessageAsync(msg);
        }
Ejemplo n.º 24
0
 public static API.EmbedField ToModel(this EmbedField entity)
 {
     return(new API.EmbedField {
         Name = entity.Name, Value = entity.Value, Inline = entity.Inline
     });
 }
Ejemplo n.º 25
0
        public async Task CalcETH(float hashrate)
        {
            List <NanoPool.Amount> amounts = NanoPool.CalculateEth(hashrate);
            string msg = "";

            EmbedField[] fields = new EmbedField[6];
            int          count  = 0;
            int          num    = 0;

            foreach (NanoPool.Amount amount in amounts)
            {
                switch (num)
                {
                case 0:
                {
                    fields[0].name = "__Minute__";
                    //msg += "\n\n__Minute__";
                    break;
                }

                case 1:
                {
                    fields[1].name = "__Hour__";
                    //msg += "\n\n__Hour__";
                    break;
                }

                case 2:
                {
                    fields[2].name = "__Day__";
                    //msg += "\n\n__Day__";
                    break;
                }

                case 3:
                {
                    fields[3].name = "__Week__";
                    //msg += "\n\n__Week__";
                    break;
                }

                case 4:
                {
                    fields[4].name = "__Month__";
                    //msg += "\n\n__Month__";
                    break;
                }

                case 5:
                {
                    fields[5].name = "__Year__";
                    //msg += "\n\n__Month__";
                    break;
                }
                }
                msg  = "**Coins:** " + string.Format("{0:N10}", amount.coins);
                msg += "\n**Dollars:** " + string.Format("${0:N8}", amount.dollars);
                msg += "\n**Bitcoins:** " + string.Format("{0:N10}", amount.bitcoins);
                msg += "\n**Euros:** " + string.Format("€{0:N8}", amount.euros);
                msg += "\n**Pounds:** " + string.Format("£{0:N8}", amount.pounds);
                fields[num].value = msg;
                num++;
                count++;
                if (count >= 6)
                {
                    //msg += "|";
                    count = 0;
                }
            }

            //string[] split = msg.Split('|');
            //for (int i = 0; i < split.Length; i++)
            {
                await PrintEmbedMessage("ETH Calculator " + hashrate + " Mh/s", fields : fields);
            }

            //await Context.Channel.SendMessageAsync(msg);
        }
        /*
         * author : yuha
         * funcName : makeMstContent
         * summary : 웹훅 string content 생성
         * input : SearchVo
         * return : string
         */
        public Webhook makeMstContent(SearchVo searchVo)
        {
            Webhook webhook = new Webhook(searchVo.webHookUrl);
            MstInfo mstInfo = searchVo.mstInfo;
            Dictionary <string, DetailInfo> detailMap = mstInfo.detailInfoMap;

            List <Embed>      embeds    = new List <Embed>();
            List <EmbedField> fileds    = new List <EmbedField>();
            Embed             embed1    = new Embed();
            EmbedThumbnail    thumbnail = new EmbedThumbnail();

            string title        = "product name : [" + mstInfo.prdNm + "]\n";
            string description  = "stockX url : [stockX](" + searchVo.stockXUrl + ")\nkream url : [kream](" + searchVo.kreamUrl + ")";
            string thumbnailUrl = mstInfo.thumbnailUrl;

            thumbnail.Url = thumbnailUrl;

            if (detailMap.Count > 0)
            {
                foreach (string key in detailMap.Keys)
                {
                    EmbedField field = new EmbedField();
                    field.Name = detailMap[key].sizeLabel;
                    if (detailMap[key].latestYn.Equals("N"))
                    { /*kreamX 최근 판매가 널인경우 추가 2021-02-18*/
                        field.Value += detailMap[key].stockXUsPriceLabel
                                       + " | " + detailMap[key].stockXKrPriceLabel
                                       + " | " + detailMap[key].kreamKrPriceLabel
                                       + " | " + detailMap[key].differenceLabel + " | " + detailMap[key].roiLabel;
                    }
                    else
                    {
                        field.Value += detailMap[key].stockXUsPriceLabel
                                       + "(" + detailMap[key].stockXLatestUsPriceLabel + ")"
                                       + " | " + detailMap[key].stockXKrPriceLabel
                                       + "(" + detailMap[key].stockXLatestKrPriceLabel + ")"
                                       + " | " + detailMap[key].kreamKrPriceLabel
                                       + "(" + detailMap[key].kreamKrLatestPriceLabel + ")"
                                       + " | " + detailMap[key].differenceLabel + " | " + detailMap[key].roiLabel
                                       + "(" + detailMap[key].latestRoiLabel + ")";
                    }
                    fileds.Add(field);
                }

                embed1.Fields = fileds;
            }
            else
            {
                description += "\n\n**No Mapped fields**";
            }

            embed1.Title       = title;
            embed1.Description = description;
            embed1.Thumbnail   = thumbnail;

            embeds.Add(embed1);

            webhook.Embeds = embeds;

            /*
             * string content = "";
             *
             * content = "product name : [" + mstInfo.prdNm + "]\n";
             * Dictionary<string, DetailInfo> detailMap = mstInfo.detailInfoMap;
             * content += "[size] | [stockX_price] | [stockX_Krprice] | [kream_Krprice] | [difference_price] \n";
             * foreach (string key in detailMap.Keys)
             * {
             *  content += detailMap[key].sizeLabel + " | " + detailMap[key].stockXUsPriceLabel + " | " + detailMap[key].stockXKrPriceLabel +
             *       " | " + detailMap[key].kreamKrPriceLabel + " | " + detailMap[key].differenceLabel + "\n";
             * }
             */

            return(webhook);
        }
Ejemplo n.º 27
0
        public async Task PollCloseCommand(int id)
        {
            Poll currentPoll = null;

            using (var db = new DatabaseContext())
            {
                try { currentPoll = db.Polls.FirstOrDefault(x => x.Id == id); } catch { }
            }

            if (currentPoll == null)
            {
                await ReplyAsync("A poll with that id doesnt exist");

                return;
            }
            if (currentPoll.GuildId != Context.Guild.Id)
            {
                await ReplyAsync("That poll is from a different guild");

                return;
            }
            var      channel = (Context.Guild.GetChannel(currentPoll.ChannelId) as ISocketMessageChannel);
            IMessage message = await channel.GetMessageAsync(currentPoll.MessageId);


            char[] alpha = "abcdefghjiklmnopqrstuvwxyz".ToCharArray();
            Dictionary <string, int> pepe = new Dictionary <string, int>();

            pepe.Clear();



            foreach (var c in currentPoll.Emotes)
            {
                try { pepe.Add(c.ToString(), 0); } catch { }
            }
            if (!currentPoll.IsMultiple)
            {
                foreach (var c in currentPoll.Votes.Values)
                {
                    pepe.TryGetValue(c.ToString(), out int val);
                    val++;
                    pepe.Remove(c.ToString());
                    pepe.Add(c.ToString(), val);
                }
            }
            else
            {
                var cyka = await Context.Channel.GetMessageAsync(currentPoll.MessageId) as IUserMessage;

                foreach (var c in cyka.Reactions)
                {
                    pepe.Add(c.Key.Name, c.Value.ReactionCount - 1);
                }
            }


            var embed = new EmbedBuilder
            {
                Author = new EmbedAuthorBuilder {
                    Name = Context.User.Username, IconUrl = Context.User.GetAvatarUrl()
                },
                Title       = $"Poll #{currentPoll.Id} results",
                Description = message.Embeds.First().Description,
                Color       = new Color(178, 224, 40),
            };



            for (int i = 0; i < pepe.Count; i++)
            {
                var        emoji = EmojiMaker.Get(alpha[i]);
                EmbedField field = message.Embeds.First().Fields.Where(x => x.Name == emoji).First();

                pepe.TryGetValue(emoji, out int value);

                embed.AddInlineField(EmojiMaker.Get(alpha[i]) + field.Value, $"Total votes: {value}");
            }

            using (var db = new DatabaseContext())
            {
                db.Polls.Remove(currentPoll);
                db.SaveChanges();
            }


            embed.WithUrl("http://heeeeeeeey.com/");
            await ReplyAsync("", false, embed);
        }
Ejemplo n.º 28
0
 public static EmbedFieldBuilder ToBuilder(this EmbedField field) => new EmbedFieldBuilder()
 .WithIsInline(field.Inline)
 .WithName(field.Name)
 .WithValue(field.Value);
Ejemplo n.º 29
0
 public DiscordEmbed AddField(EmbedField field)
 {
     this.PrivateEmbedFields.Add(field);
     return(this);
 }