Ejemplo n.º 1
0
        public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args)
        {
            Response response = new Response
            {
                Embed        = EmbedUtility.ToEmbed(Help),
                Message      = Help,
                ResponseType = ResponseType.Default
            };

            ServerSettings       serverSettings = senderDetail.ServerSettings;
            CommandMessageHelper command        = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message);

            string commandDetail = command.CommandDetail;

            response = waitHandler.CreatePleaseWaitResponse(senderDetail.ServerSettings.Language);

            Task.Run(async() =>
            {
                Response asyncResponse = await BuildMemeAsync(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(new[] { response });
        }
Ejemplo n.º 2
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));
        }
Ejemplo n.º 3
0
        public override IList <Response> Execute(SenderSettings senderDetail, IMessageDetail args)
        {
            Response response = new Response
            {
                Message      = "https://www.youtube.com",
                ResponseType = ResponseType.Default
            };

            ServerSettings       serverSettings = senderDetail.ServerSettings;
            CommandMessageHelper command        = new CommandMessageHelper(serverSettings.CommandSymbol, args.Message);

            string keywords = command.CommandDetail;

            if (!string.IsNullOrWhiteSpace(keywords))
            {
                if (keywords.Length > 150)
                {
                    response.Message = $"{Emojis.CrossSymbol} {languageHandler.GetPhrase(serverSettings.Language, "Error_IncorrectParameter")}: {languageHandler.GetPhrase(serverSettings.Language, "Text")} < 150";
                }
                else
                {
                    // Already a YouTube URL? Extract the id and prepend it with youtube.com?v=
                    var match = youtubeRegex.Match(keywords);
                    if (match.Length > 1)
                    {
                        response.Message = $"https://www.youtube.com/watch?v={match.Groups["id"].Value}";
                    }
                    else
                    {
                        response = waitHandler.CreatePleaseWaitResponse(senderDetail.ServerSettings.Language);

                        Task.Run(async() =>
                        {
                            string asyncRetVal;
                            string query = $"https://www.googleapis.com/youtube/v3/search?" +
                                           $"part=snippet&maxResults=8" +
                                           $"&q={Uri.EscapeDataString(keywords)}" +
                                           $"&key={Tokens.GoogleAPIKey}";
                            string json  = await GetResponseStringAsync(query);
                            dynamic data = JsonConvert.DeserializeObject(json);

                            if (data.items.Count > 0)
                            {
                                // Attempt to get the first item that is a video.
                                int itemIndex = 0;
                                string videoId;

                                do
                                {
                                    videoId = (data.items[itemIndex].id.videoId);
                                    itemIndex++;
                                }while (itemIndex < data.items.Count && string.IsNullOrWhiteSpace(videoId));

                                if (string.IsNullOrWhiteSpace(videoId))
                                {
                                    asyncRetVal = ($"{Emojis.Warning} {languageHandler.GetPhrase(serverSettings.Language, "Error_NoResults")}");
                                }
                                else
                                {
                                    string youTubeURL = ("https://www.youtube.com/watch?v=" + videoId);
                                    switch (youTubeCommandType)
                                    {
                                    case YouTubeCommandType.YouTube:
                                        asyncRetVal = youTubeURL;
                                        break;

                                    case YouTubeCommandType.SaveFrom:
                                        asyncRetVal = ("http://en.savefrom.net/#url=" + youTubeURL);
                                        break;

                                    case YouTubeCommandType.Repeat:
                                        asyncRetVal = ("http://www.youtubeonrepeat.com/watch?v=" + videoId);
                                        break;

                                    default:
                                        asyncRetVal = $"{Emojis.CrossSymbol} {languageHandler.GetPhrase(serverSettings.Language, "Error_Oops")}: {youTubeCommandType}";
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                asyncRetVal = $"{Emojis.Warning} {languageHandler.GetPhrase(serverSettings.Language, "Error_NoResults")}";
                            }

                            Response asyncResponse = new Response
                            {
                                Message      = asyncRetVal,
                                ResponseType = ResponseType.Default
                            };

                            await asyncResponder.SendResponseAsync(args, asyncResponse);
                            waitHandler.PopPleaseWaitMessage();
                        });
                    }
                }
            }

            response.Embed = EmbedUtility.ToEmbed(response.Message);
            return(new[] { response });
        }