Show search result in google embed

pull/90/head
Stijn De Clercq 2021-09-03 18:05:23 +02:00
parent 831459a321
commit c47f908e57
2 changed files with 16 additions and 7 deletions

View File

@ -22,7 +22,6 @@ class GoogleSlash(commands.Cog):
return await interaction.reply("Er ging iets fout (Response {})".format(result.status_code)) return await interaction.reply("Er ging iets fout (Response {})".format(result.status_code))
embed = create_google_embed(result) embed = create_google_embed(result)
print("got here")
await interaction.reply(embed=embed) await interaction.reply(embed=embed)

View File

@ -1,17 +1,21 @@
from typing import Optional, List from typing import List
import discord import discord
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from dataclasses import dataclass from dataclasses import dataclass
from requests import get from requests import get
from urllib.parse import urlencode from urllib.parse import urlencode, unquote_plus
@dataclass @dataclass
class SearchResult: class SearchResult:
status_code: int status_code: int
query: str
results: List[str] results: List[str]
def __post_init__(self):
self.query = unquote_plus(self.query[2:])
def google_search(query) -> SearchResult: def google_search(query) -> SearchResult:
""" """
@ -27,7 +31,7 @@ def google_search(query) -> SearchResult:
resp = get("https://www.google.com/search?{}&num=20&hl=en".format(query), headers=headers) resp = get("https://www.google.com/search?{}&num=20&hl=en".format(query), headers=headers)
if resp.status_code != 200: if resp.status_code != 200:
return SearchResult(resp.status_code, []) return SearchResult(resp.status_code, query, [])
bs = BeautifulSoup(resp.text, "html.parser") bs = BeautifulSoup(resp.text, "html.parser")
@ -52,10 +56,10 @@ def google_search(query) -> SearchResult:
# Map to urls # Map to urls
links = [] links = []
for (link, title) in results: for (l, t) in results:
links.append(f"[{title}]({link})") links.append(f"[{t}]({l})")
return SearchResult(200, links[:10]) return SearchResult(200, query, links[:10])
def create_google_embed(result: SearchResult) -> discord.Embed: def create_google_embed(result: SearchResult) -> discord.Embed:
@ -76,4 +80,10 @@ def create_google_embed(result: SearchResult) -> discord.Embed:
embed.description = "\n".join(links) embed.description = "\n".join(links)
# Add query into embed
if len(result.query) > 256:
embed.title = result.query[:253] + "..."
else:
embed.title = result.query
return embed return embed