private void Search_PreviewKeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Enter)
     {
         // On enter, copy to the clipboard and move on.
         GiphySearchResult local = null;
         lock (m_resultLock)
         {
             local = m_currentResults;
         }
         if (local != null && local.Data.Length > 0)
         {
             Clippy.SetClipboardContent(local.Data[m_currentResultShown]);
         }
         Close();
     }
     if (e.Key == Key.Right || e.Key == Key.Down)
     {
         ShowNextImage(true);
         e.Handled = true;
     }
     if (e.Key == Key.Left || e.Key == Key.Up)
     {
         ShowNextImage(false);
         e.Handled = true;
     }
 }
Beispiel #2
0
            public string getSearchQueryUrl(string search, string api_key, string arg)
            {
                string responseurl = "";
                string newUrl      = this.Url + "q=" + Uri.EscapeUriString(search);

                newUrl += "&api_key=" + api_key;

                string searchUrl = "https://api.giphy.com/v1/gifs/search?q=" + search + "&api_key=dc6zaTOxFJmzC";

                this.SendChatMessageEvent(searchUrl);
                var rawResponse            = new WebClient().DownloadString(searchUrl);
                GiphySearchResult response = JsonConvert.DeserializeObject <GiphySearchResult>(rawResponse);

                if (response.data.Count >= 1)
                {
                    Random rdm = new Random(Guid.NewGuid().GetHashCode());
                    GiphySearchResult.Images imagelist = response.data[rdm.Next(0, response.data.Count)].images;
                    if (arg.ToLower() == "original")
                    {
                        responseurl = imagelist.original.url;
                    }
                    else
                    {
                        responseurl = imagelist.fixed_height_small.url;
                    }

                    this.SendChatMessageEvent(responseurl);
                }

                return(responseurl);
            }
Beispiel #3
0
        public async Task OnGet()
        {
            Offset = Math.Max(0, Offset);

            if (HasSearch)
            {
                Result = await _giphy.GifSearch(new  SearchParameter
                {
                    Query  = Search,
                    Offset = Offset
                });
            }
        }
Beispiel #4
0
        public async Task Giphy([Remainder] string search = "")
        {
            if (string.IsNullOrWhiteSpace(Config.bot.Apis.ApiGiphyKey))
            {
                await Context.Channel.SendMessageAsync("Giphy search is disabled by the bot owner.");

                return;
            }

            if (string.IsNullOrWhiteSpace(search))
            {
                await Context.Channel.SendMessageAsync("The search input cannot be blank!");

                return;
            }

            EmbedBuilder embed = new EmbedBuilder();

            embed.WithTitle($"Giphy Search '{search}'");
            embed.WithDescription("Searching Giphy...");
            embed.WithFooter($"Search by {Context.User}", Context.User.GetAvatarUrl());
            embed.WithCurrentTimestamp();
            embed.WithColor(FunCmdsConfig.giphyColor);

            RestUserMessage message = await Context.Channel.SendMessageAsync("", false, embed.Build());

            GiphySearchResult results = GiphyService.Search(search);

            if (!results.IsSuccessful)
            {
                if (results.ErrorReason == ErrorReason.Error)
                {
                    await Context.Channel.SendMessageAsync(
                        "Sorry, but an error occured while searching Giphy, please try again in a moment!");

                    return;
                }
            }

            embed.WithDescription($"**By**: {results.Data.GifAuthor}\n**URL**: {results.Data.GifLink}");
            embed.WithImageUrl(results.Data.GifUrl);
            embed.WithCurrentTimestamp();

            await MessageUtils.ModifyMessage(message, embed);
        }
Beispiel #5
0
        /// <summary>
        /// Searches giphy for a a given gif name
        /// </summary>
        /// <param name="search">The gif name to search for</param>
        /// <returns></returns>
        public static GiphySearchResult Search(string search)
        {
            GiphySearchResult searchResult = new GiphySearchResult();

            try
            {
                //Check to see if the token is null or white space
                if (!string.IsNullOrWhiteSpace(Config.bot.Apis.ApiGiphyKey))
                {
                    string input = search.Replace(" ", "+");

                    string json = WebUtils.DownloadString(
                        $"http://api.giphy.com/v1/gifs/search?q={input}&api_key={Config.bot.Apis.ApiGiphyKey}");

                    dynamic dataObject = JsonConvert.DeserializeObject <dynamic>(json);

                    int choose = Global.RandomNumber(0, 25);

                    GiphyData item = new GiphyData
                    {
                        GifUrl    = dataObject.data[choose].images.fixed_height.url.ToString(),
                        GifTitle  = dataObject.data[choose].title.ToString(),
                        GifAuthor = dataObject.data[choose].username.ToString(),
                        GifLink   = dataObject.data[choose].bitly_gif_url.ToString()
                    };

                    searchResult.IsSuccessful = true;
                    searchResult.Data         = item;
                    return(searchResult);
                }

                searchResult.IsSuccessful = false;
                searchResult.ErrorReason  = ErrorReason.NoApiKey;
                return(searchResult);
            }
            catch
            {
                searchResult.IsSuccessful = false;
                searchResult.ErrorReason  = ErrorReason.Error;
                return(searchResult);
            }
        }
Beispiel #6
0
    private async Task WaitForNextMessage(CommandContext ctx, DiscordMessage oldmessage,
                                          InteractivityExtension interactivity, Language lang, int page, string formated, GiphySearchResult gifResult,
                                          DiscordEmbedBuilder b = null)
    {
        b ??= new DiscordEmbedBuilder();
        var msg = await oldmessage.WaitForButtonAsync(ctx.User, TimeSpan.FromSeconds(300));

        if (msg.Result != null)
        {
            page++;
            if (page >= gifResult.Data.Length)
            {
                page = 0;
            }

            b.WithDescription(
                $"{formated} : {gifResult.Data[page].Url} {string.Format(lang.PageGif, page + 1, gifResult.Data.Length)}")
            .WithImageUrl(gifResult.Data[page].Images.Original.Url).WithColor(await ColorUtils.GetSingleAsync());
            await msg.Result.Interaction.CreateResponseAsync(InteractionResponseType.UpdateMessage,
                                                             new DiscordInteractionResponseBuilder(new DiscordMessageBuilder().WithEmbed(b)
                                                                                                   .AddComponents(new DiscordButtonComponent(ButtonStyle.Primary, "nextgif",
                                                                                                                                             lang.PageGifButtonText))));
            await WaitForNextMessage(ctx, oldmessage, interactivity, lang, page, formated, gifResult, b);
        }
        else
        {
            await oldmessage.ModifyAsync(new DiscordMessageBuilder().WithEmbed(b).WithContent(lang.PeriodExpired)
                                         .AddComponents(new DiscordButtonComponent(ButtonStyle.Primary, "nextgif", lang.PageGifButtonText,
                                                                                   true)));
        }
    }
        void DoSearch(string query)
        {
            // Set current time as the last time we searched
            m_lastSearchTime = DateTime.Now;

            // Clean up the query
            query = query.Trim();

            // If we don't have anything close the results.
            if (String.IsNullOrWhiteSpace(query))
            {
                if (m_hasInitalQuery)
                {
                    ShowError("Go Forth And Search!");
                }
                return;
            }

            m_hasInitalQuery = true;
            m_currentSearchIndex++;
            int localIndex = m_currentSearchIndex;

            Thread t = new Thread(async() => {
                try
                {
                    // Run the web query.
                    var searchParameter = new SearchParameter()
                    {
                        Query = query
                    };
                    var gifResult = await m_giphy.GifSearch(searchParameter);

                    // If we didn't get results, show it.
                    if (gifResult.Data.Length == 0)
                    {
                        ShowError("No Results");
                        return;
                    }

                    // Jump back to the UI thread.
                    await Dispatcher.BeginInvoke(new Action(() => {
                        // Ensure we are still the current search.
                        if (localIndex == m_currentSearchIndex)
                        {
                            // Set the results.
                            lock (m_resultLock)
                            {
                                m_currentResults     = gifResult;
                                m_currentResultShown = 0;
                            }

                            // Hide any error UI.
                            HideIfVisible(ui_error);

                            // Show the first result.
                            ShowResult(gifResult.Data[0]);

                            // Ensure the results are showing.
                            EnsureWindowOpened();
                        }
                    }));
                }
                catch (Exception e)
                {
                    ShowError("Failed to query Giphy " + e.Message);
                }
            });

            t.Start();
        }