Create a slash command for google search

pull/90/head
Stijn De Clercq 2021-08-30 23:21:34 +02:00
parent eb6fc6513c
commit 537111d357
5 changed files with 61 additions and 29 deletions

View File

@ -1,10 +1,37 @@
import discord import discord
from discord.ext import commands from discord.ext import commands
from dislash import slash_command, SlashInteraction, Option, OptionType
from decorators import help from decorators import help
from enums.help_categories import Category from enums.help_categories import Category
from functions.scrapers.google import google_search from functions.scrapers.google import google_search
def _create_google_embed(results) -> discord.Embed:
# Filter out all Nones
elements = list(filter(lambda x: x is not None, results))
embed = discord.Embed(colour=discord.Colour.blue())
embed.set_author(name="Google Search")
# Empty list of results
if len(elements) == 0:
embed.description = "Geen resultaten gevonden."
return embed
# Cut excess results out
if len(elements) > 10:
elements = elements[:10]
links = []
for index, (link, title) in enumerate(elements):
links.append("{}: [{}]({})".format(index + 1, title, link))
embed.description = "\n".join(links)
return embed
class Google(commands.Cog): class Google(commands.Cog):
def __init__(self, client): def __init__(self, client):
self.client = client self.client = client
@ -13,6 +40,26 @@ class Google(commands.Cog):
def cog_check(self, ctx): def cog_check(self, ctx):
return not self.client.locked return not self.client.locked
@slash_command(name="google",
description="Google search",
options=[
Option("query", "Search query", OptionType.STRING, required=True)
],
guild_ids=[880175869841277008]
)
async def _google_slash(self, interaction: SlashInteraction, query: str):
results, status = google_search(query)
if results is None:
return await interaction.reply("Er ging iets fout (Response {})".format(status))
embed = _create_google_embed(results)
await interaction.reply(embed=embed)
@slash_command(name="test", description="Test")
async def test(self, interaction):
await interaction.reply(":eyes:")
@commands.command(name="Google", aliases=["Gtfm", "Search"], usage="[Query]", case_insensitive=True) @commands.command(name="Google", aliases=["Gtfm", "Search"], usage="[Query]", case_insensitive=True)
@help.Category(Category.Other) @help.Category(Category.Other)
async def google(self, ctx, *query): async def google(self, ctx, *query):
@ -24,28 +71,7 @@ class Google(commands.Cog):
if results is None: if results is None:
return await ctx.send("Er ging iets fout (Response {})".format(status)) return await ctx.send("Er ging iets fout (Response {})".format(status))
# Filter out all Nones embed = _create_google_embed(results)
elements = list(filter(lambda x: x is not None, results))
embed = discord.Embed(colour=discord.Colour.blue())
embed.set_author(name="Google Search")
# Empty list of results
if len(elements) == 0:
embed.description = "Geen resultaten gevonden."
return await ctx.reply(embed=embed, mention_author=False)
# Cut excess results out
if len(elements) > 10:
elements = elements[:10]
links = []
for index, (link, title) in enumerate(elements):
links.append("{}: [{}]({})".format(index + 1, title, link))
embed.description = "\n".join(links)
await ctx.reply(embed=embed, mention_author=False) await ctx.reply(embed=embed, mention_author=False)

View File

@ -62,7 +62,7 @@ class School(commands.Cog):
return await ctx.send(embed=s.create_schedule().to_embed()) return await ctx.send(embed=s.create_schedule().to_embed())
@commands.command(name="Pin", usage="[Message]") @commands.command(name="Pin", usage="[Message]")
@help.Category(category=Category.School) @help.Category(category=Category.Other)
async def pin(self, ctx, message: discord.Message): async def pin(self, ctx, message: discord.Message):
# In case people abuse, check if they're blacklisted # In case people abuse, check if they're blacklisted
blacklist = [] blacklist = []

View File

@ -1,11 +1,8 @@
#!/usr/bin/env python3
import datetime import datetime
import requests import requests
import sys
def etenScript(weekDag): def etenScript(weekDag, resto: str = "sterre"):
# What day # What day
weekdagen = ('ma', 'di', 'wo', 'do', 'vr', 'za', 'zo') weekdagen = ('ma', 'di', 'wo', 'do', 'vr', 'za', 'zo')
deltas = {'morgen': 1, deltas = {'morgen': 1,
@ -26,7 +23,7 @@ def etenScript(weekDag):
# Fetch from API # Fetch from API
try: try:
menu = requests.get(f"https://zeus.ugent.be/hydra/api/2.0/resto/menu/nl-sterre/{d.year}/{d.month}/{d.day}.json").json() menu = requests.get(f"https://zeus.ugent.be/hydra/api/2.0/resto/menu/nl-{resto}/{d.year}/{d.month}/{d.day}.json").json()
if not menu["meals"]: if not menu["meals"]:
raise Exception() raise Exception()

View File

@ -18,4 +18,7 @@ Quart-CORS==0.5.0
attrs~=21.2.0 attrs~=21.2.0
dacite~=1.6.0 dacite~=1.6.0
pytest==6.2.4 pytest==6.2.4
markdownify==0.9.2 markdownify==0.9.2
# Experimental package for slash commands & menus
dislash.py==1.4.9

View File

@ -1,5 +1,6 @@
from data.snipe import Snipe from data.snipe import Snipe
from discord.ext import commands, ipc from discord.ext import commands, ipc
from dislash import InteractionClient
import os import os
from settings import HOST_IPC from settings import HOST_IPC
from startup.init_files import check_all from startup.init_files import check_all
@ -10,6 +11,8 @@ class Didier(commands.Bot):
""" """
Main Bot class for Didier Main Bot class for Didier
""" """
# Reference to interactions client
interactions: InteractionClient
# Dict to store the most recent Snipe info per channel # Dict to store the most recent Snipe info per channel
snipe: Dict[int, Snipe] = {} snipe: Dict[int, Snipe] = {}
@ -29,6 +32,9 @@ class Didier(commands.Bot):
# Remove default help command # Remove default help command
self.remove_command("help") self.remove_command("help")
# Create interactions client
self.interactions = InteractionClient(self, test_guilds=[728361030404538488, 880175869841277008])
# Load all extensions # Load all extensions
self.init_extensions() self.init_extensions()