From ccad084b2bd53be59b18410b2f4ff351b68bb2e3 Mon Sep 17 00:00:00 2001 From: aikaterna <20862007+aikaterna@users.noreply.github.com> Date: Sat, 26 Oct 2019 11:46:37 -0700 Subject: [PATCH] [Dictionary] Rewrite + antonyms and synonyms --- dictionary/dictionary.py | 101 ++++++++++++++++++++++++++++++++++----- dictionary/info.json | 12 ++--- 2 files changed, 94 insertions(+), 19 deletions(-) diff --git a/dictionary/dictionary.py b/dictionary/dictionary.py index 38dde5e..8af842d 100644 --- a/dictionary/dictionary.py +++ b/dictionary/dictionary.py @@ -1,38 +1,117 @@ +import aiohttp +from bs4 import BeautifulSoup +import re from redbot.core import commands -from PyDictionary import PyDictionary class Dictionary(commands.Cog): - """Word, yo""" + """Word, yo + Parts of this cog are adapted from the PyDictionary library.""" def __init__(self, bot): self.bot = bot - self.dictionary = PyDictionary() + self.session = aiohttp.ClientSession() + + def cog_unload(self): + self.bot.loop.create_task(self.session.close()) + + async def _get_soup_object(self, url): + try: + async with self.session.request("GET", url) as response: + return BeautifulSoup(await response.text(), "html.parser") + except Exception as e: + print(e) + return + + @commands.command() + async def antonym(self, ctx, *, word: str): + """Displays antonyms for a given word.""" + search_msg = await ctx.send("Searching...") + search_term = word.split(" ", 1)[0] + result = await self._antonym(ctx, search_term) + if not result: + return await search_msg.edit(content="This word is not in the dictionary.") + + result_text = "*, *".join(result) + await search_msg.edit(content=f"Antonyms for **{search_term}**: *{result_text}*") + + async def _antonym(self, ctx, word): + data = await self._get_soup_object(f"http://www.thesaurus.com/browse/{word}") + section = data.find_all("ul", {"class": "css-1lc0dpe et6tpn80"}) + try: + section[1] + except IndexError: + return + spans = section[1].findAll("li") + antonyms = [span.text for span in spans[:50]] + return antonyms @commands.command() async def define(self, ctx, *, word: str): """Displays definitions of a given word.""" search_msg = await ctx.send("Searching...") search_term = word.split(" ", 1)[0] - result = self.dictionary.meaning(search_term) + result = await self._definition(ctx, search_term) str_buffer = "" - if result is None: - await search_msg.edit(content="This word is not in the dictionary.") - return + if not result: + return await search_msg.edit(content="This word is not in the dictionary.") for key in result: - str_buffer += "\n**" + key + "**: \n" + str_buffer += f"\n**{key}**: \n" counter = 1 j = False for val in result[key]: if val.startswith("("): - str_buffer += str(counter) + ". *" + val + ")* " + str_buffer += f"{str(counter)}. *{val})* " counter += 1 j = True else: if j: - str_buffer += val + "\n" + str_buffer += f"{val}\n" j = False else: - str_buffer += str(counter) + ". " + val + "\n" + str_buffer += f"{str(counter)}. {val}\n" counter += 1 await search_msg.edit(content=str_buffer) + + async def _definition(self, ctx, word): + html = await self._get_soup_object(f"http://wordnetweb.princeton.edu/perl/webwn?s={word}") + types = html.findAll("h3") + length = len(types) + lists = html.findAll("ul") + out = {} + if not lists: + return + for a in types: + reg = str(lists[types.index(a)]) + meanings = [] + for x in re.findall(r">\s\((.*?)\)\s<", reg): + if "often followed by" in x: + pass + elif len(x) > 5 or " " in str(x): + meanings.append(x) + name = a.text + out[name] = meanings + return out + + async def _synonym(self, ctx, word): + data = await self._get_soup_object(f"http://www.thesaurus.com/browse/{word}") + section = data.find_all("ul", {"class": "css-1lc0dpe et6tpn80"}) + try: + section[1] + except IndexError: + return + spans = section[0].findAll("li") + synonyms = [span.text for span in spans[:50]] + return synonyms + + @commands.command() + async def synonym(self, ctx, *, word: str): + """Displays synonyms for a given word.""" + search_msg = await ctx.send("Searching...") + search_term = word.split(" ", 1)[0] + result = await self._synonym(ctx, search_term) + if not result: + return await search_msg.edit(content="This word is not in the dictionary.") + + result_text = "*, *".join(result) + await search_msg.edit(content=f"Synonyms for **{search_term}**: *{result_text}*") diff --git a/dictionary/info.json b/dictionary/info.json index a20fc04..bebd620 100644 --- a/dictionary/info.json +++ b/dictionary/info.json @@ -1,14 +1,10 @@ { "author": [ - "UltimatePancake" + "UltimatePancake", "aikaterna" ], - "description": "Gets definitions for given words", - "install_msg": "`[p]define ` to define a word after loading the cog with `[p]load dictionary`.", - - "requirements": [ - "PyDictionary" - ], - "short": "Gets definitions for given words", + "description": "Gets definitions, antonyms, or synonyms for given words", + "install_msg": "After loading the cog with `[p]load dictionary`, use [p]help Dictionary to view commands.", + "short": "Gets definitions, antonyms, or synonyms for given words", "tags": [ "dictionary" ],