Exemplo n.º 1
0
        public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args)
        {
            ServerSettings       serverSettings = senderDetail.ServerSettings;
            CultureInfo          cultureInfo    = languageHandler.GetCultureInfo(serverSettings.Language);
            CommandMessageHelper command        = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message);

            string[]      commandParams = command.CommandParams;
            Discord.Color responseColor = Discord.Color.Green;

            string[] typeStrings;

            if (command.CommandDetail.Contains('-'))
            {
                // User wrote e.g. normal-flying
                typeStrings = command.CommandDetail.Split('-');
            }
            else
            {
                typeStrings = command.CommandArgs.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
            }

            if (typeStrings.Length == 0)
            {
                // No types specified.
                return(Response.CreateArrayFromString("http://bulbapedia.bulbagarden.net/wiki/Type"));
            }

            List <string> incorrectTypes = new List <string>();
            List <string> duplicateTypes = new List <string>();

            var foundTypes = new HashSet <PokemonType>();

            // TODO - translate.
            if (typeStrings.Length == 1 && typeStrings[0].Equals("all", StringComparison.OrdinalIgnoreCase))
            {
                // Add all types.
                foreach (PokemonType t in PokemonTypeHandler.PokemonTypes)
                {
                    if (t != PokemonType.NumberOfTypes)
                    {
                        foundTypes.Add(t);
                    }
                }
            }
            else
            {
                foreach (string typeStr in typeStrings)
                {
                    bool found = PokemonTypeHandler.GetTypeFromLocalisedName(typeStr, cultureInfo, out PokemonType t);
                    if (found)
                    {
                        bool added = foundTypes.Add(t);
                        if (!added)
                        {
                            duplicateTypes.Add(typeStr);
                        }
                    }
                    else
                    {
                        incorrectTypes.Add(typeStr);
                    }
                }
            }

            bool foundAny = foundTypes.Any();

            if (!foundAny)
            {
                // Check if is actually a Pokémon.
                Pokemon pokemon = (KnowledgeBase.GetOrFetchPokémon(command.CommandDetail));
                if (pokemon != null)
                {
                    foundTypes.Add(pokemon.PrimaryType);
                    if (pokemon.SecondaryType != PokemonType.NumberOfTypes)
                    {
                        foundTypes.Add(pokemon.SecondaryType);
                    }

                    foundAny = true;

                    // Ignore the typing - it's a Pokémon.
                    incorrectTypes.Clear();
                    duplicateTypes.Clear();
                }
            }

            StringBuilder sb = new StringBuilder();

            // Incorrect types
            if (incorrectTypes.Any())
            {
                sb.Append($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}");
                sb.Append(": ");
                sb.AppendLine(string.Join(" ", incorrectTypes));
            }

            // Duplicate types
            if (duplicateTypes.Any())
            {
                sb.Append($"{Emojis.ExclamationSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Warning_SameType")}");
                sb.Append(": ");
                sb.AppendLine(string.Join(" ", duplicateTypes));
            }

            if (foundAny)
            {
                sb.AppendLine("```objectivec");
                sb.Append("// ");

                foreach (PokemonType foundType in foundTypes)
                {
                    string foundTypeName = PokemonTypeHandler.GetLocalisedName(foundType, cultureInfo);
                    sb.Append(foundTypeName);
                    sb.Append(" ");
                }
                sb.AppendLine();

                // Attacking
                if (foundTypes.Count < 3)
                {
                    sb.AppendLine($"# {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Attacking")}");
                    foreach (PokemonType foundType in foundTypes)
                    {
                        double[] attackingType1 = PokemonTypeHandler.GetAttacking(foundType);
                        for (int i = 0; i < attackingType1.Length; i++)
                        {
                            double eff = attackingType1[i];
                            if (eff != 1.0)
                            {
                                sb.Append(eff.ToString("G", cultureInfo.NumberFormat));
                                sb.Append($"x {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Against")} ");
                                sb.Append(PokemonTypeHandler.GetLocalisedName(PokemonTypeHandler.PokemonTypes[i], cultureInfo));
                                sb.Append($" {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "WhenAttackingWith")} ");
                                sb.Append(PokemonTypeHandler.GetLocalisedName(foundType, cultureInfo));
                                sb.AppendLine();
                            }
                        }
                    }
                }
                sb.AppendLine();

                // Defending
                sb.AppendLine($"# {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Defending")}");
                double[] defending = PokemonTypeHandler.GetDefending(foundTypes.ToArray());
                for (int i = 0; i < defending.Length; i++)
                {
                    double eff = defending[i];
                    if (eff != 1.0)
                    {
                        sb.Append(eff.ToString("G", cultureInfo.NumberFormat));
                        sb.Append($"x {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "DamageTakenFrom")} ");
                        sb.AppendLine(PokemonTypeHandler.GetLocalisedName(PokemonTypeHandler.PokemonTypes[i], cultureInfo));
                    }
                }

                // Add on status immunities.
                foreach (PokemonType foundType in foundTypes)
                {
                    string immunity = PokemonTypeHandler.GetTypeStatusImmunityString(foundType, cultureInfo);
                    if (immunity != string.Empty)
                    {
                        sb.AppendLine(immunity);
                    }
                }

                sb.Append("```");
            }

            return(Response.CreateArrayFromString(sb.ToString(), responseColor));
        }
Exemplo n.º 2
0
        public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args)
        {
            StringBuilder output = new StringBuilder();

            if ((Constants.IsBotOwner(args.UserId)) || (args.GuildOwnerId == args.UserId))
            {
                ServerSettings serverSettings = senderDetail.ServerSettings;
                IEnumerable <ScheduledMessageData> scheduledData = serverSettings.ScheduledMessages.Where(d => d.channelId == args.ChannelId);
                int scheduledDataLength            = scheduledData.Count();
                CommandMessageHelper command       = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message);
                string[]             commandParams = command.CommandParams;

                switch (commandParams.Length)
                {
                case 0:
                    // Should not occur.
                    output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_Oops")}");
                    break;

                case 1:
                    // Show help.
                    output.AppendLine(Help);
                    output.AppendLine(Examples);
                    output.AppendLine(BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language));
                    break;

                case 2:
                {
                    // Remove without an id?
                    if (commandParams[1].Equals("remove", StringComparison.OrdinalIgnoreCase))
                    {
                        switch (scheduledDataLength)
                        {
                        case 0:
                        {
                            // No messages set up
                            output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_NoResults")}");
                            break;
                        }

                        case 1:
                        {
                            // Only one, remove that
                            ScheduledMessageData matchedData = serverSettings.ScheduledMessages.Single(d => d.channelId == args.ChannelId);
                            AttemptDisable(serverSettings, matchedData, output, senderDetail.ServerSettings.Language);

                            // And remove
                            serverSettings.ScheduledMessages.Remove(matchedData);
                            serverSettingsHandler.WriteServerSettings(serverSettings);
                            break;
                        }

                        default:
                        {
                            // More than one, require an id.
                            output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}: {Constants.BotMention_Nick} {command.CommandLower} remove _id_");
                            output.AppendLine(BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language));
                            break;
                        }
                        }
                    }
                    else if (commandParams[1].Equals("enable", StringComparison.OrdinalIgnoreCase))
                    {
                        switch (scheduledDataLength)
                        {
                        case 0:
                        {
                            // No messages set up
                            output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_NoResults")}");
                            break;
                        }

                        case 1:
                        {
                            // Only one, try to enable that
                            ScheduledMessageData matchedData = serverSettings.ScheduledMessages.Single(d => d.channelId == args.ChannelId);
                            AttemptEnable(serverSettings, matchedData, output, serverSettings.Language);
                            break;
                        }

                        default:
                        {
                            // More than one, require an id.
                            output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}: {Constants.BotMention_Nick} {command.CommandLower} enable _id_");
                            output.AppendLine(BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language));
                            break;
                        }
                        }
                    }
                    else if (commandParams[1].Equals("disable", StringComparison.OrdinalIgnoreCase))
                    {
                        switch (scheduledDataLength)
                        {
                        case 0:
                        {
                            // No messages set up
                            output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_NoResults")}");
                            break;
                        }

                        case 1:
                        {
                            // Only one, disable that
                            ScheduledMessageData matchedData = serverSettings.ScheduledMessages.Single(d => d.channelId == args.ChannelId);
                            AttemptDisable(serverSettings, matchedData, output, senderDetail.ServerSettings.Language);
                            break;
                        }

                        default:
                        {
                            // More than one, require an id.
                            output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}: {Constants.BotMention_Nick} {command.CommandLower} enable _id_");
                            output.AppendLine(BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language));
                            break;
                        }
                        }
                    }
                    else if (commandParams[1].Equals("list", StringComparison.OrdinalIgnoreCase))
                    {
                        string list = BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language);
                        if (list == string.Empty)
                        {
                            output.AppendLine("<none>");
                        }
                        else
                        {
                            output.AppendLine(list);
                        }
                    }
                    else if (commandParams[1].Equals("set", StringComparison.OrdinalIgnoreCase))
                    {
                        output.AppendLine($"{Constants.BotMention_Nick} {command.CommandLower} set _id_ <Due|Repeating|Message|Enabled> <_value_>");
                        output.AppendLine(BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language));
                    }
                    else if (commandParams[1].Equals("new", StringComparison.OrdinalIgnoreCase))
                    {
                        ushort id       = 1;
                        var    takenIds = serverSettings.ScheduledMessages.Select(d => d.id).ToArray();
                        while (takenIds.Contains(id))
                        {
                            ++id;
                        }
                        serverSettings.ScheduledMessages.Insert(id - 1, new ScheduledMessageData(args.ChannelId, id));
                        output.AppendLine($"{Constants.BotMention_Nick} {command.CommandLower} set **{id}** <Due|Repeating|Message|Enabled> <_value_>");
                        output.AppendLine(BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language));
                    }

                    break;
                }

                case 3:
                {
                    bool idParsed = ushort.TryParse(commandParams[2], out ushort id);

                    if (!idParsed)
                    {
                        // Id not in range
                        output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}: {id}");
                        output.AppendLine(BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language));
                    }
                    else
                    {
                        var matchedData = serverSettings.ScheduledMessages.Find(m => m.id == id);
                        if (matchedData != default(ScheduledMessageData))
                        {
                            if (commandParams[1].Equals("set", StringComparison.OrdinalIgnoreCase))
                            {
                                output.AppendLine($"{Constants.BotMention_Nick} {command.CommandLower} set _id_ <Due|Repeating|Message|Enabled> <value>");
                                output.AppendLine(BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language));
                            }
                            else if (commandParams[1].Equals("enable", StringComparison.OrdinalIgnoreCase))
                            {
                                AttemptEnable(serverSettings, matchedData, output, serverSettings.Language);
                            }
                            else if (commandParams[1].Equals("disable", StringComparison.OrdinalIgnoreCase))
                            {
                                AttemptDisable(serverSettings, matchedData, output, serverSettings.Language);
                            }
                            else
                            {
                                // Remove with an id?
                                if (commandParams[1].Equals("remove", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!scheduledData.Any())
                                    {
                                        output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_NoResults")}");
                                    }
                                    else
                                    {
                                        if (id > 0 && id <= scheduledDataLength)
                                        {
                                            AttemptDisable(serverSettings, matchedData, output, senderDetail.ServerSettings.Language);

                                            // And remove
                                            serverSettings.ScheduledMessages.Remove(matchedData);
                                            serverSettingsHandler.WriteServerSettings(serverSettings);
                                            output.AppendLine(BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language));
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            // Id not found
                            output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}: {id}");
                            output.AppendLine(BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language));
                        }
                    }
                    break;
                }

                // 4 or more
                default:
                {
                    bool idParsed = uint.TryParse(commandParams[2], out uint id);

                    if (!idParsed)
                    {
                        // Id not in range
                        output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}: {id}");
                        output.AppendLine(BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language));
                    }
                    else
                    {
                        var matchedData = serverSettings.ScheduledMessages.Find(m => m.id == id);
                        if (matchedData != default(ScheduledMessageData))
                        {
                            if (commandParams[1].Equals("set", StringComparison.OrdinalIgnoreCase))
                            {
                                // Due|Repeating|Message|Enabled
                                if (commandParams[3].Equals("Due", StringComparison.OrdinalIgnoreCase))
                                {
                                    string dueStr = string.Join(" ", commandParams.Skip(4));
                                    if (string.IsNullOrWhiteSpace(dueStr))
                                    {
                                        output.AppendLine($"{Emojis.InfoSymbol} Due is the next time to send the message e.g. 5:30pm, 00:00");
                                    }
                                    else
                                    {
                                        bool success = DateTime.TryParse(dueStr, languageHandler.GetCultureInfo(serverSettings.Language), DateTimeStyles.AssumeUniversal, out matchedData.nextDue);
                                        if (success)
                                        {
                                            matchedData.nextDue = matchedData.nextDue.ToUniversalTime();
                                            while (matchedData.nextDue < DateTime.UtcNow)
                                            {
                                                matchedData.nextDue = matchedData.nextDue.AddDays(1);
                                            }
                                            string localisedToGo = languageHandler.GetLocalisedTimeSpan(serverSettings.Language, matchedData.nextDue - DateTime.UtcNow);
                                            output.AppendLine($"{Emojis.TimerSymbol} {matchedData.nextDue.ToString("t")} UTC ({localisedToGo})");
                                            serverSettingsHandler.WriteServerSettings(serverSettings);
                                        }
                                        else
                                        {
                                            output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}: {dueStr}");
                                        }
                                    }
                                }
                                else if (commandParams[3].Equals("Repeating", StringComparison.OrdinalIgnoreCase))
                                {
                                    string repeatingStr = string.Join(" ", commandParams.Skip(4));
                                    if (string.IsNullOrWhiteSpace(repeatingStr))
                                    {
                                        output.AppendLine($"{Emojis.InfoSymbol} Repeating is the period to wait between each message, or 0 to not repeat. In form _days_ or _days_._hours_:_minutes_:_seconds_ or _hours_:_minutes_:_seconds_");
                                    }
                                    else
                                    {
                                        bool success = TimeSpan.TryParse(repeatingStr, languageHandler.GetCultureInfo(senderDetail.ServerSettings.Language), out matchedData.repetitionTimeSpan);
                                        if (success)
                                        {
                                            TimeSpan ts          = matchedData.repetitionTimeSpan;
                                            string   localisedTs = languageHandler.GetLocalisedTimeSpan(serverSettings.Language, ts);
                                            output.AppendLine($"{Emojis.RepeatSymbol} {localisedTs}");
                                            serverSettingsHandler.WriteServerSettings(serverSettings);
                                        }
                                        else
                                        {
                                            output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}: {repeatingStr}");
                                        }
                                    }
                                }
                                else if (commandParams[3].Equals("Message", StringComparison.OrdinalIgnoreCase))
                                {
                                    string messageStr = string.Join(" ", commandParams.Skip(4));
                                    if (string.IsNullOrWhiteSpace(messageStr))
                                    {
                                        output.AppendLine($"{Emojis.InfoSymbol} Message is the message to write.");
                                    }
                                    else
                                    {
                                        matchedData.message = messageStr;
                                        output.AppendLine($"{Emojis.MessageUnicode} {messageStr}");
                                        serverSettingsHandler.WriteServerSettings(serverSettings);
                                    }
                                }
                                else if (commandParams[3].Equals("Enabled", StringComparison.OrdinalIgnoreCase))
                                {
                                    string enabledStr = string.Join(" ", commandParams.Skip(4));
                                    if (string.IsNullOrWhiteSpace(enabledStr))
                                    {
                                        output.AppendLine($"{Emojis.InfoSymbol} Enabled is if the message should be enabled (true/false). Long hand for the enable/disable command.");
                                    }
                                    else
                                    {
                                        if (enabledStr.Equals("true", StringComparison.OrdinalIgnoreCase) || enabledStr.Equals("yes", StringComparison.OrdinalIgnoreCase) || enabledStr.Equals("y", StringComparison.OrdinalIgnoreCase))
                                        {
                                            AttemptEnable(serverSettings, matchedData, output, senderDetail.ServerSettings.Language);
                                            serverSettingsHandler.WriteServerSettings(serverSettings);
                                        }
                                        else if (enabledStr.Equals("false", StringComparison.OrdinalIgnoreCase) || enabledStr.Equals("no", StringComparison.OrdinalIgnoreCase) || enabledStr.Equals("n", StringComparison.OrdinalIgnoreCase))
                                        {
                                            AttemptDisable(serverSettings, matchedData, output, senderDetail.ServerSettings.Language);
                                            serverSettingsHandler.WriteServerSettings(serverSettings);
                                        }
                                        else
                                        {
                                            output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}: {enabledStr}");
                                        }
                                    }
                                }
                                else
                                {
                                    output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}: {commandParams[3]}");
                                    output.AppendLine($"{Constants.BotMention_Nick} {command.CommandLower} set _id_ <Due|Repeating|Message|Enabled> [value]");
                                }
                            }
                        }
                        else
                        {
                            // Id not found
                            output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_IncorrectParameter")}: {id}");
                            output.AppendLine(BuildScheduledMessageInformation(scheduledData, languageHandler.GetCultureInfo(serverSettings.Language), serverSettings.Language));
                        }
                    }

                    break;
                }
                }
            }
            else
            {
                output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_ServerOwnerOnly")}");
            }

            return(new[] { new Response
                           {
                               Message = output.ToString(),
                               ResponseType = ResponseType.Default
                           } });
        }
Exemplo n.º 3
0
        public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args)
        {
            ServerSettings       serverSettings = senderDetail.ServerSettings;
            CultureInfo          cultureInfo    = languageHandler.GetCultureInfo(serverSettings.Language);
            CommandMessageHelper command        = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message);

            Discord.Color responseColor = Discord.Color.Green;
            // First, check the cache if we already have this pokémon.
            string query = command.CommandDetail;

            if (args.URLs.Length > 0)
            {
                var response = new[] { waitHandler.CreatePleaseWaitResponse(senderDetail.ServerSettings.Language) };

                Task.Run(async() =>
                {
                    Response asyncResponse = await CorrelatePokemonAsync(senderDetail.ServerSettings.Language, args);
                    if (asyncResponse == null)
                    {
                        string err    = ($"{Emojis.NoEntry} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_NoImageMessages")}");
                        asyncResponse = new Response
                        {
                            Embed        = EmbedUtility.ToEmbed(err),
                            Message      = err,
                            ResponseType = ResponseType.Default
                        };
                    }
                    await asyncResponder.SendResponseAsync(args, asyncResponse);
                    waitHandler.PopPleaseWaitMessage();
                });

                return(response);
            }

            query = query.Replace("(Pokemon)", "").Replace("(Pokémon)", "").Trim();
            query = query.Replace("(move)", "").Trim();

            StringBuilder output   = new StringBuilder();
            Pokemon       pokemon  = KnowledgeBase.GetPokémon(query);
            string        imageUrl = null;
            bool          isCached = (pokemon != null);

            try
            {
                // For now, assume that it is a Pokémon.
                string url    = "https://bulbapedia.bulbagarden.net/wiki/" + query.Capitalize() + "_(Pokémon)";
                string urlRaw = url + "?action=raw";

                if (!isCached)
                {
                    // Assume correct URL
                    pokemon = Pokemon.ParsePage(urlRaw);
                }

                if (pokemon != null)
                {
                    string  p         = pokemon.Name + "_(Pokémon)";
                    dynamic imageJson = null;
                    output
                    .Append("https://bulbapedia.bulbagarden.net/wiki/")
                    .Append(p)
                    .AppendLine("#") // # is for mobile where () is not correctly parsed in the URL parser
                    .AppendLine(MakeAPokemonString(pokemon, cultureInfo, serverSettings.Language));

                    try
                    {
                        cancellationTokenSource.CancelAfter(300000);
                        Task.Run(async() =>
                        {
                            imageJson = await JSONHelper.GetJsonAsync(Uri.EscapeUriString("https://bulbapedia.bulbagarden.net/w/api.php?action=query&format=json&prop=pageimages&titles=" + p)).ConfigureAwait(false);
                        }, cancellationTokenSource.Token).Wait();
                        JToken token = imageJson["query"]["pages"];
                        token    = token.First.First;
                        imageUrl = token["thumbnail"]["source"]?.ToString();
                    }
                    catch (TaskCanceledException tcex)
                    {
                        errorLogger.LogDebug("Did not query Bulbapedia in time to retrieve the Pokemon image.", true);
                        errorLogger.LogException(tcex, ErrorSeverity.Warning);
                    }
                    catch (Exception ex)
                    {
                        errorLogger.LogDebug($"Exception occurred retrieving the Pokemon image for {pokemon?.Name}.\n" +
                                             $"imageUrl: {imageUrl}\n" +
                                             $"imageJson: {imageJson}", true);
                        errorLogger.LogException(ex, ErrorSeverity.Error);
                    }
                }
                else
                {
                    output.AppendLine($"{Emojis.ExclamationSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_PokemonNotFound")}: {urlRaw}");
                }
            }
            catch (WebException)
            {
                output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_PokemonNotFound")}: {query}");
            }
            catch (Exception ex)
            {
                output.AppendLine($"{languageHandler.GetPhrase(senderDetail.ServerSettings.Language, "Error_Oops")}: {ex.Message}");
            }

            return(Response.CreateArrayFromString(output.ToString(), responseColor, pokemon.Name, imageUrl));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Roll x dice of y sides. Translatable.
        /// </summary>
        /// <param name="rolls"></param>
        /// <param name="diceType"></param>
        /// <param name="localisation"></param>
        /// <param name="adjustDice">Adjust total by amount (or 0)</param>
        /// <returns></returns>
        private static void RollDice(ushort rolls, byte diceType, int adjustDice, LanguageHandler languageHandler, Languages language, ref StringBuilder output)
        {
            if (diceType == 0)
            {
                output.AppendLine($"{Emojis.CrossSymbol} {languageHandler.GetPhrase(language, Errors.ErrorCode.IncorrectParameter)}: {diceType}");
            }
            else
            {
                output.AppendLine($"{Emojis.Dice} {languageHandler.GetPhrase(language, "Rolled")}: {rolls}d{diceType}:");

                string resultsStr;
                int    total;

                if (rolls == 1)
                {
                    // Simplify everything for a single roll.
                    total      = (rand.Next(diceType) + 1);
                    resultsStr = total.ToString();
                    output.Append(resultsStr);
                }
                else
                {
                    int[] results = new int[diceType];

                    for (int i = 0; i < rolls; i++)
                    {
                        int rolled0base = (rand.Next(diceType));
                        results[rolled0base]++;
                    }

                    total = results.Select((rolled, index) => (index + 1) * rolled).Sum();
                    double average = (double)total / rolls;
                    resultsStr = string.Join("", results.Select((rolled, index) => (rolled > 0 ? ($"`{(index + 1)}: {rolled}x` ") : ("")))).Trim();
                    output.AppendLine(resultsStr);
                    output.Append($"{languageHandler.GetPhrase(language, "Average")}: {average.ToString("N2", languageHandler.GetCultureInfo(language))}, {languageHandler.GetPhrase(language, "Total")}: {total}");
                }

                if (adjustDice != 0)
                {
                    output.Append(adjustDice.ToString("+#;-#;0") + " = " + (total + adjustDice));
                }
                output.AppendLine();
            }
        }