Ejemplo n.º 1
0
        public async Task UpdateEventDescription([Remainder] string description)
        {
            User     user    = Users.GetUser(Context.User);
            IMessage message = await Context.Channel.GetMessageAsync(user.BotMessageID);

            IEmbed oldEmbed = message.Embeds.First();
            List <EmbedFieldBuilder> fields = new List <EmbedFieldBuilder>()
            {
                new EmbedFieldBuilder()
                {
                    Name = "Description", Value = description, IsInline = false
                },
                new EmbedFieldBuilder()
                {
                    Name = "Players", Value = "Specifiy the Maximum Amount of Players", IsInline = false
                }
            };

            Embed embed = new EmbedBuilder()
                          .WithAuthor(oldEmbed.Author.ToString())
                          .WithTitle(oldEmbed.Title)
                          .WithFields(fields)
                          .WithColor(EmbedHandler.color)
                          .WithCurrentTimestamp().Build();

            await Context.Channel.DeleteMessageAsync(Context.Message);

            await message.DeleteAsync();

            IMessage newMessage = await ReplyAsync("", false, embed);

            user.BotMessageID = newMessage.Id;
            user.EventPhase   = EventPhases.Players;
        }
Ejemplo n.º 2
0
        private async Task ReactionAdded(Cacheable <IUserMessage, ulong> msg, ISocketMessageChannel channel, SocketReaction reaction)
        {
            IMessage message = await msg.GetOrDownloadAsync();

            switch (message.Embeds.Count)
            {
            case 0:
                break;      // might do something with this eventually

            case 1:
                IEmbed embed = message.Embeds.ElementAt <IEmbed>(0);
                if (embed.Footer.ToString() == "React-for-Role Embed" && reaction.UserId != _client.CurrentUser.Id)
                {
                    await ReactForRole.RfrAddRoleAsync(embed, reaction);

                    break;
                }
                if (embed.Footer.ToString().Substring(0, 4) == "Vote" && reaction.UserId != _client.CurrentUser.Id)
                {
                    await VoteModule.AddVote(message as IUserMessage, reaction);

                    break;
                }
                break;

            default:
                break;
            }
        }
Ejemplo n.º 3
0
        public Settlement FromEmbed(IEmbed embed)
        {
            if (!embed.Description.Contains(SettlementResources.Settlement))
            {
                throw new ArgumentException(SettlementResources.SettlementNotFoundError);
            }

            this.Authority              = embed.Fields.FirstOrDefault(fld => fld.Name == SettlementResources.Authority).Value;
            this.FirstLooks             = embed.Fields.Where(fld => fld.Name == SettlementResources.FirstLook)?.Select(item => item.Value).ToList() ?? new List <string>();
            this.FirstLooksToReveal     = FirstLooks.Count();
            this.InitialContactRevealed = embed.Fields.Any(fld => fld.Name == SettlementResources.InitialContact);
            if (InitialContactRevealed)
            {
                this.InitialContact = embed.Fields.FirstOrDefault(fld => fld.Name == SettlementResources.InitialContact).Value;
            }
            this.Location                  = embed.Fields.FirstOrDefault(fld => fld.Name == SettlementResources.Location).Value;
            this.Name                      = embed.Title.Replace("__", "");
            this.Population                = embed.Fields.FirstOrDefault(fld => fld.Name == SettlementResources.Population).Value;
            this.Projects                  = embed.Fields.Where(fld => fld.Name == SettlementResources.SettlementProjects)?.Select(item => item.Value).ToList() ?? new List <string>();
            this.ProjectsRevealed          = embed.Fields.Count(fld => fld.Name.Contains(SettlementResources.SettlementProjects));
            this.Region                    = StarforgedUtilites.GetAnySpaceRegion(embed.Description);
            this.SettlementTroubleRevealed = embed.Fields.Any(fld => fld.Name == SettlementResources.SettlementTrouble);
            if (SettlementTroubleRevealed)
            {
                this.SettlementTrouble = embed.Fields.FirstOrDefault(fld => fld.Name == SettlementResources.SettlementTrouble).Value;
            }
            this.IconUrl = embed.Thumbnail?.Url;

            return(this);
        }
Ejemplo n.º 4
0
        public Starship FromEmbed(IEmbed embed)
        {
            string      Name   = embed.Title.Replace("__", "");
            SpaceRegion region = StarforgedUtilites.GetAnySpaceRegion(embed.Description);

            this.FirstLooksToReveal = embed.Fields.Count(fld => fld.Name == StarShipResources.FirstLook);
            this.FirstLooks         = embed.Fields.Where(fld => fld.Name == StarShipResources.FirstLook)?.Select(item => item.Value).ToList() ?? new List <string>();
            this.Fleet           = embed.Fields.FirstOrDefault(fld => fld.Name == StarShipResources.Fleet).Value;
            this.InitialContact  = embed.Fields.FirstOrDefault(fld => fld.Name == StarShipResources.InitialContact).Value;
            this.MissionRevealed = embed.Fields.Any(fld => fld.Name == StarShipResources.StarshipMission);
            if (this.MissionRevealed)
            {
                this.Mission = embed.Fields.FirstOrDefault(fld => fld.Name == StarShipResources.StarshipMission).Value;
            }
            this.Name        = embed.Title.Replace("__", string.Empty);
            this.ShipType    = embed.Fields.FirstOrDefault(fld => fld.Name == StarShipResources.StarshipType).Value;
            this.SpaceRegion = StarforgedUtilites.GetAnySpaceRegion(embed.Description);

            bool hasTypicalRole = embed.Fields.Any(fld => fld.Name == StarShipResources.TypicalRole);

            this.TypicalRole = (hasTypicalRole) ? embed.Fields.FirstOrDefault(fld => fld.Name == StarShipResources.TypicalRole).Value : string.Empty;
            this.IconUrl     = embed.Thumbnail?.Url;

            return(this);
        }
Ejemplo n.º 5
0
        private Embed ConvertMessageToEmbed(IUserMessage message)
        {
            EmbedBuilder embedBuilder = new EmbedBuilder();

            EmbedAuthorBuilder embedAuthorBuilder = new EmbedAuthorBuilder();

            embedAuthorBuilder.Name    = message.Author.Username;
            embedAuthorBuilder.IconUrl = message.Author.GetAvatarUrl();
            embedBuilder.Author        = embedAuthorBuilder;

            IEmbed imageEmbed = message.Embeds.FirstOrDefault(x => x.Type == EmbedType.Image);

            if (imageEmbed != null)
            {
                embedBuilder.ImageUrl = imageEmbed.Thumbnail?.Url;
            }

            string[]    imageExtensions = { "png", "jpeg", "jpg", "gif", "webp" };
            IAttachment imageAttachment = message.Attachments.FirstOrDefault(x => imageExtensions.Any(y => x.Filename.EndsWith(y)));

            if (imageAttachment != null)
            {
                embedBuilder.ImageUrl = imageAttachment.Url;
            }

            embedBuilder.Description = message.Content;

            embedBuilder.Timestamp = message.Timestamp;

            embedBuilder.Color = Color.Green;

            return(embedBuilder.Build());
        }
Ejemplo n.º 6
0
        private async Task NotifyMembers(IGuildUser host, IMessage embedMessage, IEmbed embed, CancellationToken token)
        {
            Log.Information("Notifying reactors...", embedMessage.Reactions.Count);

            if (!embed.Footer.HasValue)
            {
                return;
            }
            var eventId = ulong.Parse(embed.Footer.Value.Text);

            var reactors = _db.EventReactions.Where(er => er.EventId == eventId);

            await foreach (var reactor in reactors.WithCancellation(token))
            {
                var user = _client.GetUser(reactor.UserId);
                if (user == null || user.IsBot)
                {
                    continue;
                }

                try
                {
                    await user.SendMessageAsync($"The run you reacted to (hosted by {host.Nickname ?? host.Username}) is beginning in 30 minutes!");
                }
                catch (HttpException e) when(e.DiscordCode == 50007)
                {
                    Log.Warning("Can't send direct message to user {User}.", host.ToString());
                }
            }

            await _db.RemoveAllEventReactions(eventId);
        }
Ejemplo n.º 7
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.º 8
0
        internal static EmbedBuilder GetMessageEmbed(IUserMessage msg, bool withFields)
        {
            IEmbed old = Enumerable.First(msg.Embeds);

            return(BuildEmbed(old.Title, old.Description,
                              old.Footer == null ? null : ((EmbedFooter)old.Footer).Text,
                              old.Color ?? new Color(), withFields ? old.Fields : old.Fields.Clear()));
        }
Ejemplo n.º 9
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.º 10
0
        private bool NeedsWarning(IEmbed embed)
        {
            if (embed.Title.Contains(OracleResources.OracleResult))
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 11
0
        private static Embed GetRefreshedStatus(IEmbed previousEmbed, LavaPlayer player)
        {
            EmbedBuilder builder = previousEmbed.ToEmbedBuilder();

            AddStatusInfo(builder, player);
            builder.WithCurrentTimestamp();

            return(builder.Build());
        }
Ejemplo n.º 12
0
        private static Embed GetRefreshedVolume(IEmbed previousEmbed, int volume)
        {
            EmbedBuilder builder = previousEmbed.ToEmbedBuilder();

            AddVolumeInfo(builder, volume);
            builder.WithCurrentTimestamp();

            return(builder.Build());
        }
Ejemplo n.º 13
0
        public static ulong GetMessageIDFromEmbed(IEmbed embed)
        {
            string messageID = GetAllUrlFromString(embed.Description).First();

            messageID = messageID.Remove(0, 29);
            messageID = messageID.Remove(0, GetUntilOrEmpty(messageID, '/').Length + 1);
            messageID = messageID.Remove(0, GetUntilOrEmpty(messageID, '/').Length + 1);
            return(Convert.ToUInt64(messageID));
        }
Ejemplo n.º 14
0
        private static Embed GetRefreshedQueue(IEmbed previousEmbed, LavaQueue queue)
        {
            EmbedBuilder builder = previousEmbed.ToEmbedBuilder();

            AddQueueInfo(builder, queue);
            builder.WithCurrentTimestamp();

            return(builder.Build());
        }
Ejemplo n.º 15
0
        private void RenderEmbed(IEmbed embed, UIElementCollection blockUIElementCollection)
        {
            switch (embed.Type)
            {
            case "link": {
                if (!embed.Thumbnail.HasValue)
                {
                    return;
                }
                var result = new Windows.UI.Xaml.Controls.Image {
                    HorizontalAlignment = HorizontalAlignment.Left,
                    MaxHeight           = Math.Min(75, embed.Thumbnail.Value.Height.Value),
                    Source = new BitmapImage {
                        DecodePixelType   = DecodePixelType.Logical,
                        DecodePixelHeight = Math.Min(75, embed.Thumbnail.Value.Height.Value),
                        UriSource         = new Uri(embed.Thumbnail.Value.Url),
                    },
                };
                blockUIElementCollection.Add(result);
            }
            break;

            case "gifv": {
                var result = new MediaElement {
                    IsLooping = true,
                    AreTransportControlsEnabled = false,
                    Source              = new Uri(embed.Video.Value.Url),
                    MaxHeight           = Math.Min(250, embed.Video.Value.Height.Value),
                    MaxWidth            = Math.Min(400, embed.Video.Value.Width.Value),
                    HorizontalAlignment = HorizontalAlignment.Left,
                    IsMuted             = true,
                };
                blockUIElementCollection.Add(result);
            }
            break;

            case "image": {
                var result = new Windows.UI.Xaml.Controls.Image {
                    HorizontalAlignment = HorizontalAlignment.Left,
                    MaxHeight           = Math.Min(250, embed.Thumbnail.Value.Height.Value),
                    MaxWidth            = Math.Min(400, embed.Thumbnail.Value.Width.Value),
                    Source = new BitmapImage {
                        DecodePixelType   = DecodePixelType.Logical,
                        DecodePixelHeight = Math.Min(250, embed.Thumbnail.Value.Height.Value),
                        UriSource         = new Uri(embed.Url),
                    },
                };
                blockUIElementCollection.Add(result);
            }
            break;

            default:
                Debug.WriteLine("Unknown Embed Type -- " + embed.Type);
                break;
            }
        }
Ejemplo n.º 16
0
        private static JSONContainer getFooterJSON(IEmbed embed)
        {
            EmbedFooter   footer     = embed.Footer.Value;
            JSONContainer footerJSON = JSONContainer.NewObject();

            checkAddStringField(footer.Text, footerJSON, TEXT);
            checkAddStringField(footer.IconUrl, footerJSON, ICON_URL);

            return(footerJSON);
        }
Ejemplo n.º 17
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);
 }
Ejemplo n.º 18
0
        private static async Task <Embed> GetRefreshedAudioInfo(IEmbed previousEmbed, AudioTrack audioTrack)
        {
            EmbedBuilder builder = previousEmbed.ToEmbedBuilder();

            await AddAudioTrackInfo(builder, audioTrack);

            builder.WithCurrentTimestamp();

            return(builder.Build());
        }
Ejemplo n.º 19
0
        protected string GetMockEmbedText(IEmbed embed)
        {
            if (embed == null)
            {
                throw new ArgumentNullException(nameof(embed));
            }

            return(this.GetMockEmbedText(
                       embed.Title, embed.Description, embed.Fields.ToDictionary(field => field.Name, field => field.Value)));
        }
Ejemplo n.º 20
0
        public async Task Events_ReactionAdded(Cacheable <IUserMessage, ulong> cacheable, ISocketMessageChannel channel, SocketReaction reaction)
        {
            if (channel is IDMChannel)
            {
                return;
            }
            if ((channel as SocketTextChannel).Name != "events")
            {
                return;
            }

            SocketGuildUser user = Constants.IGuilds.Jordan(_client).GetUser(reaction.UserId);

            if (user.IsBot)
            {
                return;
            }
            IEmbed embed = cacheable.GetOrDownloadAsync().Result.Embeds.First();

            if (embed.Fields.First(x => x.Name == "Location").Value == "Discord")
            {
                return;
            }

            if (user.ToUser().EventVerified)
            {
                // User is allowed.
                return;
            }

            /*else if (eVerified.Denied.Contains(reaction.User.Value.Id))
             * {
             *  // User is denied.
             *
             *  IMessage msg = (channel as SocketTextChannel).GetMessageAsync(cacheable.Id).Result;
             *  await (msg as IUserMessage).RemoveReactionAsync(reaction.Emote, reaction.User.Value);
             *
             *  IDMChannel dm = reaction.User.Value.GetOrCreateDMChannelAsync().Result;
             *  await dm.SendMessageAsync(":x: You are denied from using the events system.");
             *  return;
             * }*/
            else
            {
                // User is not verified.

                IMessage msg = (channel as SocketTextChannel).GetMessageAsync(cacheable.Id).Result;
                await(msg as IUserMessage).RemoveReactionAsync(reaction.Emote, reaction.User.Value);

                IDMChannel dm = user.GetOrCreateDMChannelAsync().Result;
                await dm.SendMessageAsync(":x: Please verify your age using the Event Verification System before using events.");

                return;
            }
        }
Ejemplo n.º 21
0
        public static Starship FromEmbed(ServiceProvider services, IEmbed embed)
        {
            string      Name   = embed.Title.Replace("__", "");
            SpaceRegion region = StarforgedUtilites.GetAnySpaceRegion(embed.Description);

            var ship = GenerateShip(services, region, Name);

            ship.MissionRevealed = embed.Fields.Any(fld => fld.Name.Equals(StarShipResources.StarshipMission));

            return(ship);
        }
Ejemplo n.º 22
0
        private ulong?GetAskerId(IEmbed b)
        {
            var r = Regex.Match(b.Description, @"\[\]\((\d{17,18})\)");

            if (!r.Success)
            {
                return(null);
            }

            return(ulong.Parse(r.Groups[1].Value));
        }
Ejemplo n.º 23
0
 public static Embed CreateFromEmbed(IEmbed embed)
 {
     return(new Embed()
     {
         Description = embed.Description,
         Url = embed.Url,
         Color = embed.Color?.RawValue.ToString(),
         ImageUrl = embed.Image?.Url,
         Author = embed.Author?.Name,
         Title = embed.Title,
         Footer = embed.Footer?.Text,
         Fields = embed.Fields.Select(x => (x.Name, x.Value)).ToArray()
     });
Ejemplo n.º 24
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.º 25
0
        /// <summary>
        /// Constructs a <see cref="JSONContainer"/> from a Message
        /// </summary>
        /// <param name="message">Message to pull information from</param>
        public static JSONContainer GetJSONFromUserMessage(IMessage message)
        {
            string messageContent = message.Content;
            IEmbed embed          = null;

            IReadOnlyCollection <IEmbed> embeds = message.Embeds;

            if (embeds != null)
            {
                embed = embeds.FirstOrDefault();
            }

            return(GetJSONFromMessageContentAndEmbed(messageContent, embed));
        }
Ejemplo n.º 26
0
        public static Creature FromEmbed(IEmbed embed, IServiceProvider serviceProvider, ulong ChannelId)
        {
            var creature = new Creature(serviceProvider, ChannelId);

            creature.Environment         = StarforgedUtilites.GetAnyEnvironment(embed.Fields.FirstOrDefault(fld => fld.Name == CreatureResources.Environment).Value);
            creature.Scale               = embed.Fields.FirstOrDefault(fld => fld.Name == CreatureResources.Scale).Value;
            creature.BasicForm           = embed.Fields.FirstOrDefault(fld => fld.Name == CreatureResources.BasicForm).Value;
            creature.FirstLook           = embed.Fields.Where(fld => fld.Name == CreatureResources.FirstLook).Select(fld => fld.Value).ToList();
            creature.EncounteredBehavior = embed.Fields.FirstOrDefault(fld => fld.Name == CreatureResources.EncounteredBehavior).Value;
            creature.RevealedAspectsList = embed.Fields.Where(fld => fld.Name == CreatureResources.RevealedAspect).Select(fld => fld.Value).ToList();
            creature.IconUrl             = embed.Thumbnail?.Url;

            return(creature);
        }
Ejemplo n.º 27
0
        public Settlement FromEmbed(IEmbed embed)
        {
            if (!embed.Description.Contains(SettlementResources.Settlement))
            {
                throw new ArgumentException(SettlementResources.SettlementNotFoundError);
            }

            SpaceRegion region     = StarforgedUtilites.GetAnySpaceRegion(embed.Description);
            var         settlement = GenerateSettlement(Services, region, embed.Title.Replace("__", ""));

            settlement.FirstLooksToReveal = embed.Fields.Count(fld => fld.Name.Contains(SettlementResources.FirstLook));
            settlement.ProjectsRevealed   = embed.Fields.Count(fld => fld.Name.Contains(SettlementResources.SettlementProjects));

            return(settlement);
        }
Ejemplo n.º 28
0
        private static JSONContainer getFieldsJSON(IEmbed embed)
        {
            JSONContainer fieldsJSON = JSONContainer.NewArray();

            foreach (Discord.EmbedField embedField in embed.Fields)
            {
                JSONContainer fieldJSON = JSONContainer.NewObject();
                fieldJSON.TryAddField(NAME, embedField.Name);
                fieldJSON.TryAddField(VALUE, embedField.Value);
                fieldJSON.TryAddField(INLINE, embedField.Inline);
                fieldsJSON.Add(fieldJSON);
            }

            return(fieldsJSON);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Determins if a player answered correctly and accordingly colors the embedbuilder of the game and returns a string
        /// </summary>
        private string GuessingResponse(IEmbed emb, IReaction reaction)
        {
            // Get the embed field that matches the reaction (or null)
            var answered = emb.Fields.FirstOrDefault(field => field.Name == reaction.Emote.Name);

            if (_currentQuestion.correct_answer == answered.Value)
            {
                _emb.WithColor(Color.Green);
                _currentQuestion.correct = true;
                return($":white_check_mark: You guessed correct! The answer was \"{_currentQuestion.correct_answer}\"");
            }

            _emb.WithColor(Color.Red);
            _currentQuestion.correct = false;
            return($":x: **WRONG!** The correct answer would have been \"{_currentQuestion.correct_answer}\"");
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Attempts to recover <typeparamref name="TMetadata"/> from the provided <paramref name="embedMetadata"/>
        /// </summary>
        /// <typeparam name="TMetadata">The type of metadata to look for and restore.</typeparam>
        /// <param name="embed">The embed to search for serialized metadata.</param>
        /// <param name="embedMetadata">The recovered metadata.</param>
        /// <returns>Whether an instance of <typeparamref name="TMetadata"/> was found and recovered from the embed.</returns>
        static public bool TryParseMetadata <TMetadata>(this IEmbed embed, out TMetadata embedMetadata)
            where TMetadata : IEmbedMetadata, new()
        {
            embedMetadata = new TMetadata();

            NameValueCollection metadata;
            var sourceUrl = embed?.Author?.IconUrl ?? embed?.Image?.Url;

            if (sourceUrl != null)
            {
                metadata = HttpUtility.ParseQueryString(new UriBuilder(sourceUrl).Fragment.TrimStart('#'));
            }
            else if (embed?.Footer?.Text is string footerText && Regex.Match(footerText, @"^\S+") is Match match && match.Success)
            {
                metadata = HttpUtility.ParseQueryString(match.Groups[0].Value);
            }