Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
from discord.ext import commands
from botClient import client, colorCode, weatherKey, timeKey, dictionaryId, dictionaryKey
from datetime import datetime
from pprint import pprint
import asyncio
import discord
import aiohttp
import json
import urllib
import urllib.parse
"""Module for various API based functions, such as finding the weather and/or time in any city, searching the
meaning of any word that exists in the Oxford Dictionaries, as well as synonyms/antonyms and example sentences
for said word(s)."""
class ApiFunctions:
def __init__(self, client):
self.client = client
"""Command for WEATHER INFORMATION in any City requested by the user"""
@commands.command(name='weather')
@commands.cooldown(2, 4, commands.BucketType.user)
async def weather_command(self, ctx, f_arg=' ', *args):
"""Shows current weather for any city chosen by the user"""
try:
await ctx.message.delete()
except discord.HTTPException:
pass
"""If the user doesn't specify a city"""
if f_arg == ' ':
await ctx.send('Please specify city. (``>weather city_name``)', delete_after=5)
return
"""If the city is separated into more words, e.g. New York, combine them so that the user doesn't have to type
"New York" or New_York """
loc = f_arg
for arg in args:
loc = str(loc) + " " + str(arg)
"""Fetches the data from the openweathermap.org api"""
async with aiohttp.ClientSession() as session:
async with session.get(f'http://api.openweathermap.org/data/2.5/weather?q={loc}&APPID={weatherKey}')\
as weatherReq:
weatherResp = json.loads(await weatherReq.text())
"""Try to get information about the time as well"""
try:
async with session.get(f'http://api.timezonedb.com/v2.1/get-time-zone?key={timeKey}'
f'&format=json&by=position&lat={weatherResp["coord"]["lat"]}'
f'&lng={weatherResp["coord"]["lon"]}') as timeReq:
"""If it works (and it always should unless the API site is offline), formats the date
and time so it's easier to read for the user"""
if timeReq.status == 200:
timeResp = json.loads(await timeReq.text())
timeRespDatetime = datetime.strptime(timeResp['formatted'], '%Y-%m-%d %H:%M:%S')
timeFormat = "%X, %A"
except KeyError:
pass
if weatherReq.status == 200:
"""Converts temperature to celsius and start building the discord embed then send it."""
celsius = round(weatherResp['main']['temp'] - 273.15, 2)
embed = discord.Embed(
title=f'Weather in {weatherResp["name"]}, {weatherResp["sys"]["country"]}',
description=f'**{weatherResp["weather"][0]["main"]}** '
f'({weatherResp["weather"][0]["description"]})',
color= colorCode[0]
)
embed.add_field(name='Temperature',
value=f'{celsius} °C',
inline=True)
embed.add_field(name='Humidity',
value='≈' + str(weatherResp['main']['humidity']) + '%',
inline=True)
embed.add_field(name='Winds',
value='≈' + str(weatherResp['wind']['speed']) + ' m/s',
inline=True)
try:
embed.add_field(name='Timezone',
value=f'{timeResp["abbreviation"]} ({timeRespDatetime.strftime(timeFormat)})',
inline=True)
except UnboundLocalError:
pass
embed.set_thumbnail(url=f'http://openweathermap.org/img/w/{weatherResp["weather"][0]["icon"]}.png')
embed.set_footer(text="Requested by " + ctx.message.author.name + '.',
icon_url=ctx.message.author.avatar_url)
await ctx.send(embed=embed)
else:
await ctx.send(f"``{weatherReq.status}``: Couldn't get weather info for ``{loc}``.", delete_after=5)
print(f'Request failed: Weather status:{weatherReq.status}')
"""Command for TIME INFORMATION in any City requested by the user"""
@commands.command(name='time', aliases=['timezone', 'date', 'clock', 'worldtime', 'citytime', 'worldclock'])
@commands.cooldown(2, 4, commands.BucketType.user)
async def time_command(self, ctx, f_arg=' ', *args):
"""Shows current time for any city chosen by the user"""
try:
await ctx.message.delete()
except discord.HTTPException:
pass
"""If the user doesn't specify a city"""
if f_arg == ' ':
await ctx.send('Please specify city. (``>time city_name``)', delete_after=5)
return
"""If the city is separated into more words, e.g. New York, combine them so that the user doesn't have to type
"New York" or New_York """
loc = f_arg
for arg in args:
loc = str(loc) + " " + str(arg)
"""The free version of the time API doesn't allow search by city names, so in order to bypass this limitation
we use the weather API to find the latitude and longitude of the desired city, then input them into the
time API request."""
async with aiohttp.ClientSession() as session:
async with session.get(f'http://api.openweathermap.org/data/2.5/weather?q={loc}&APPID={weatherKey}') \
as weatherReq:
weatherResp = json.loads(await weatherReq.text())
try:
async with session.get(f'http://api.timezonedb.com/v2.1/get-time-zone?key={timeKey}'
f'&format=json&by=position&lat={weatherResp["coord"]["lat"]}'
f'&lng={weatherResp["coord"]["lon"]}') as timeReq:
timeResp = json.loads(await timeReq.text())
except KeyError:
await ctx.send(f'City with name or position ``{loc}`` not found.', delete_after=5)
return
"""If both requests are successful, we do some more time conversions then start building the
discord embed using the data, after which we send it."""
if weatherReq.status == 200 and timeReq.status == 200:
timeRespDatetime = datetime.strptime(timeResp['formatted'], '%Y-%m-%d %H:%M:%S')
if timeResp["gmtOffset"] > 0:
greenwich = f'+{int(timeResp["gmtOffset"] / 3600)}'
else:
greenwich = int(timeResp["gmtOffset"] / 3600)
embed = discord.Embed(
title=f'Time in {weatherResp["name"]}, {timeResp["countryCode"]} '
f'**{timeRespDatetime.strftime("%H:%M %p")}**',
description=f'{timeResp["zoneName"]}, {timeResp["countryName"]}',
color=colorCode[0]
)
embed.add_field(name='Current time', value=timeRespDatetime.strftime('%X %p'), inline=True)
embed.add_field(name='Date', value=timeRespDatetime.strftime('%a, %d %B %Y'), inline=True)
embed.add_field(name='Timezone', value=f'{timeResp["abbreviation"]}', inline=True)
embed.add_field(name='GMT/UTC Offset', value=f'GMT {greenwich}', inline=True)
embed.add_field(name='Latitude', value=weatherResp["coord"]["lat"], inline=True)
embed.add_field(name='Longitude', value=weatherResp["coord"]["lon"], inline=True)
embed.set_footer(text="Requested by " + ctx.message.author.name + '.',
icon_url=ctx.message.author.avatar_url)
embed.set_thumbnail(url=f'http://openweathermap.org/img/w/{weatherResp["weather"][0]["icon"]}.png')
await ctx.send(embed=embed)
else:
await ctx.send(f"``{timeReq.status}``: Couldn't get time info for ``{loc}``.", delete_after=5)
print(f'API request failed: Weather status:{weatherReq.status}, Time status: {timeReq.status}')
"""Command for WORD DEFINITION/MEANING for any word chosen by the user"""
@commands.command(name='word', aliases=['worddef', 'definition', 'def', 'wordmeaning', 'meaning', 'wdef', 'w'])
@commands.cooldown(2, 4, commands.BucketType.user)
async def word_definition(self, ctx, f_arg=" ", *args):
"""Returns a detailed word definition from OxfordDictionaries
Expected inputs: Uppercase or lowercase English word, with or with no space between.
Examples: water, swim, hard disk.
Expected outputs: Name (of word), phonetic spelling, type and meaning, an example, origin of the word
and a source link for more definitions and examples (e.g https://en.oxforddictionaries.com/definition/hard_disk)
"""
"""
How the API request check works:
CHECKS if the API request failed
If it's because the word isn't found (404):
We use the API to search for similar words and alternatives.
If at least 1 similar word is found, return it to the user (max 5).
If no similar word is found, give up and tell the user to try another word.
If the API request failed not because of a 404 Not Found error,
return the error name and code to the user.
"""
try:
await ctx.message.delete()
except discord.HTTPException:
pass
"""If no parameters are given, ask the user to type a word. If nothing is given in the next 5 seconds, return"""
if f_arg == " ":
await ctx.send("Please input the word you're searching for.", delete_after=5)
def pred(m):
return m.author == ctx.message.author and m.channel == ctx.message.channel
try:
f_arg = await client.wait_for('message', check=pred, timeout=5)
word_id = f_arg.content
if f_arg.content == '>':
return
except asyncio.TimeoutError:
return
else:
word_id = f_arg
"""Combines inputs separated by spaces into a single word.
Selects the language as English, converts the word in URL format in case it is needed for special characters"""
for arg in args:
word_id = str(word_id) + " " + str(arg)
lang = 'en'
urllib.parse.quote(word_id)
"""Starts the ClientSession with the API authentication Id and Key (from botClient) in the headers"""
async with aiohttp.ClientSession(headers={'app_id': dictionaryId, 'app_key': dictionaryKey}) as session:
async with session.get(f'https://od-api.oxforddictionaries.com/api/v1/entries/{lang}/{word_id.lower()}') \
as wordReq:
"""===============START OF API REQUEST CHECK==============="""
if wordReq.status != 200 and wordReq.status == 404:
async with session.get(f'https://od-api.oxforddictionaries.com:443/api/v1'
f'/search/{lang}?q={word_id.lower()}&prefix=false') as searchReq:
searchResp = json.loads(await searchReq.text())
try:
altWord = f"[{searchResp['results'][0]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][0]['id']}) \n"
except IndexError:
embed = discord.Embed(title=f'Could not find the word "{word_id.lower()}."',
description=f'No similar words found. \n'
f'Check that **"{word_id.lower()}"** is a valid word.',
color=colorCode[2]
)
await ctx.send(embed=embed)
return
"""Try to get 4 more similar words"""
for i in range(1, 5):
try:
altWord += f"[{searchResp['results'][i]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][i]['id']}) \n"
except IndexError:
break
embed = discord.Embed(title=f'Could not find the word "{word_id.lower()}."',
description='Did you mean: \n' + str(altWord),
color=colorCode[1]
)
await ctx.send(embed=embed)
return
elif wordReq.status != 200:
embed = discord.Embed(title='Something went wrong',
description=f'Error: {wordReq.reason} \nCode: {wordReq.status}',
color=colorCode[2])
await ctx.send(embed=embed)
return
"""================END OF API REQUEST CHECK================"""
wordResp = json.loads(await wordReq.text())
"""
CHECK IF DEFINITION IS FOUND
If not, search the original form of the word instead (and API Req. check it)
Example: Inflection of "swim" is "swimming" or "swam"
"""
"""if no definition is found"""
if not wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['definitions'][0]:
"""search for the non-inflected version"""
async with session.get(
f'https://od-api.oxforddictionaries.com/api/v1/inflections/{lang}/{word_id.lower()}') \
as wordLemmaReq:
"""===============START OF API REQUEST CHECK==============="""
if wordLemmaReq.status != 200 and wordLemmaReq.status == 404:
async with session.get(f'https://od-api.oxforddictionaries.com:443/api/v1'
f'/search/{lang}?q={word_id.lower()}&prefix=false') as searchReq:
searchResp = json.loads(await searchReq.text())
try:
altWord = f"[{searchResp['results'][0]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][0]['id']}) \n"
except IndexError:
embed = discord.Embed(title=f'Could not find the word "{word_id.lower()}."',
description=f'No similar words found. \n'
f'Check that **"{word_id.lower()}"** '
f'is a valid word.',
color=colorCode[2]
)
await ctx.send(embed=embed)
return
for i in range(1, 5):
try:
altWord += f"[{searchResp['results'][i]['id']}]" \
f"(https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][i]['id']}) \n"
except IndexError:
break
# print(altWord) #testing
embed = discord.Embed(title=f'Could not find the word "{word_id.lower()}."',
description='Did you mean: \n' + str(altWord),
color=colorCode[1]
)
await ctx.send(embed=embed)
return
elif wordLemmaReq.status != 200:
embed = discord.Embed(title='Something went wrong',
description=f'Error: {wordLemmaReq.reason} \n'
f'Code: {wordLemmaReq.status}',
color=colorCode[2])
await ctx.send(embed=embed)
return
"""================END OF API REQUEST CHECK================"""
wordLemmaResp = json.loads(await wordLemmaReq.text())
wordLemmaId = wordLemmaResp['results'][0]['lexicalEntries'][0]['inflectionOf'][0]['id']
async with session.get(
f'https://od-api.oxforddictionaries.com/api/v1/entries/{lang}/{wordLemmaId.lower()}') \
as wordReq:
wordResp = json.loads(await wordReq.text())
"""=================BUILDING THE DISCORD EMBED START=================
If field data isn't found (e.g. word origin), skip the field.
If definition is still not found, even after trying the inflection of the word,
return a cross reference instead (if found)"""
wordName = wordResp['results'][0]['word']
wordType = wordResp['results'][0]['lexicalEntries'][0]['lexicalCategory']
try:
wordPron = wordResp['results'][0]['lexicalEntries'][0]['pronunciations'][0]['phoneticSpelling']
embed = discord.Embed(title=wordName,
description= f"/{wordPron}/",
color = colorCode[0])
except KeyError:
embed = discord.Embed(title=wordName,
description= "n/a",
color = colorCode[0])
try:
wordDef = wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['definitions'][0]
embed.add_field(name=f'{wordType} meaning', value=wordDef, inline=False)
except KeyError:
try:
wordRefer = wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['crossReferenceMarkers'][0]
embed.add_field(name='Cross Reference', value=wordRefer, inline=False)
except KeyError:
pass
try:
wordExmple = wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['examples'][0][
'text']
embed.add_field(name='Example ', value=wordExmple, inline=False)
except KeyError:
pass
try:
wordOrigin = wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['etymologies'][0]
embed.add_field(name='Origin', value=wordOrigin, inline=False)
except KeyError:
pass
embed.add_field(name='Source Link (more definitions and examples)',
value=f'https://en.oxforddictionaries.com/definition/{wordName.replace(" ", "_")}',
inline=False)
embed.set_footer(text=f'Meaning of "{word_id}" requested by {ctx.message.author.name}.',
icon_url=ctx.message.author.avatar_url)
"""==================BUILDING THE DISCORD EMBED END=================="""
await ctx.send(embed=embed)
"""Command for WORD SYNONYM for any word chosen by the user"""
@commands.command(aliases=['synonym', 'wordsynonym', 'ws', 'syn'])
@commands.cooldown(2, 4, commands.BucketType.user)
async def word_synonym(self, ctx, f_arg="word", *args):
"""Returns a list of synonyms for the inputted word."""
try:
await ctx.message.delete()
except discord.HTTPException:
pass
word_id = f_arg
for arg in args:
word_id = str(word_id) + " " + str(arg)
lang = 'en'
urllib.parse.quote(word_id)
async with aiohttp.ClientSession(headers={'app_id': dictionaryId, 'app_key': dictionaryKey}) as session:
async with session.get(f'https://od-api.oxforddictionaries.com/api/v1/inflections/{lang}/{word_id.lower()}') \
as wordLemmaReq:
"""==============START OF API REQUEST CHECK=============="""
if wordLemmaReq.status != 200 and wordLemmaReq.status == 404:
async with session.get(f'https://od-api.oxforddictionaries.com:443/api/v1'
f'/search/{lang}?q={word_id.lower()}&prefix=false') as searchReq:
searchResp = json.loads(await searchReq.text())
try:
altWord = f"[{searchResp['results'][0]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][0]['id']}) \n"
except IndexError:
embed = discord.Embed(title=f'Could not find the word "{word_id.lower()}."',
description=f'No similar words found. \n'
f'Make sure that **"{word_id.lower()}"** is a valid word.',
color=colorCode[2]
)
await ctx.send(embed=embed)
return
for i in range(1, 5):
try:
altWord += f"[{searchResp['results'][i]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][i]['id']}) \n"
except IndexError:
break
embed = discord.Embed(title=f'Could not find synonyms for the word "{word_id.lower()}."',
description='Similar words: \n' + str(altWord),
color=colorCode[1]
)
await ctx.send(embed=embed)
return
elif wordLemmaReq.status != 200:
embed = discord.Embed(title='Something went wrong',
description=f'Error: {wordLemmaReq.reason} \nCode: {wordLemmaReq.status}',
color=colorCode[2])
await ctx.send(embed=embed)
return
"""===============END OF API REQUEST CHECK==============="""
wordLemmaResp = json.loads(await wordLemmaReq.text())
wordLemmaId = wordLemmaResp['results'][0]['lexicalEntries'][0]['inflectionOf'][0]['id']
async with session.get(f'https://od-api.oxforddictionaries.com/api/v1/entries/'
f'{lang}/{wordLemmaId.lower()}/synonyms') \
as wordReq:
"""==============START OF API REQUEST CHECK=============="""
if wordReq.status != 200 and wordReq.status == 404:
async with session.get(f'https://od-api.oxforddictionaries.com:443/api/v1'
f'/search/{lang}?q={wordLemmaId.lower()}&prefix=false') as searchReq:
searchResp = json.loads(await searchReq.text())
try:
altWord = f"[{searchResp['results'][0]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][0]['id']}) \n"
except IndexError:
embed = discord.Embed(title=f'Could not find the word "{wordLemmaId.lower()}."',
description=f'No similar words found. \n'
f'Make sure that **"{wordLemmaId.lower()}"**'
f' is a valid word.',
color=colorCode[2]
)
await ctx.send(embed=embed)
return
for i in range(1, 5):
try:
altWord += f"[{searchResp['results'][i]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][i]['id']}) \n"
except IndexError:
break
embed = discord.Embed(title=f'Could not find synonyms for the word "{wordLemmaId.lower()}."',
description='You could try these words instead: \n' + str(altWord),
color=colorCode[1]
)
await ctx.send(embed=embed)
return
elif wordReq.status != 200:
embed = discord.Embed(title='Something went wrong',
description=f'Error: {wordReq.reason} \nCode: {wordReq.status}',
color=colorCode[2])
await ctx.send(embed=embed)
return
"""===============END OF API REQUEST CHECK==============="""
wordResp = json.loads(await wordReq.text())
"""=================BUILDING THE DISCORD EMBED START================="""
"""Will attempt to give two different contexts (with an example sentence) with 3 synonyms each"""
try:
wordSyn1 = f"{wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['synonyms'][0]['text']}\n"
except IndexError:
embed = discord.Embed(title=f'Could not find any synonyms for "{word_id.lower()}."',
description="Huh, that's weird.",
color=colorCode[2]
)
await ctx.send(embed=embed)
return
embed = discord.Embed(title=f"Synonyms for {wordResp['results'][0]['word']}",
description=wordResp['results'][0]['lexicalEntries'][0]['lexicalCategory'],
color=colorCode[0])
for i in range(1,3):
try:
wordSyn1 += f"{wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['synonyms'][i]['text']}\n"
except IndexError:
break
try:
wordExample1 = wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['examples'][0]['text']
embed.add_field(name=wordSyn1,
value=f'"{str(wordExample1)}"', inline=False)
except KeyError:
embed.add_field(name=wordSyn1,
value='example n/a', inline=False)
try:
wordSyn2 = f"{wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][1]['synonyms'][0]['text']}\n"
for i in range(1,3):
try:
wordSyn2 += f"{wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][1]['synonyms'][i]['text']}\n"
except IndexError:
break
try:
wordExample2 = wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][1]['examples'][0]['text']
embed.add_field(name=wordSyn2,
value=f'"{str(wordExample2)}"', inline=False)
except KeyError:
embed.add_field(name=wordSyn2,
value='example n/a', inline=False)
except (IndexError, KeyError):
pass
embed.set_footer(text=f'Synonyms for "{word_id}" requested by {ctx.message.author.name}.',
icon_url=ctx.message.author.avatar_url)
"""=================BUILDING THE DISCORD EMBED END================="""
await ctx.send(embed=embed)
"""Command for WORD ANTONYM for any word chosen by the user"""
@commands.command(aliases=['antonym', 'wordantonym', 'wa', 'ant'])
@commands.cooldown(2, 4, commands.BucketType.user)
async def word_antonym(self, ctx, f_arg="identical", *args):
"""Returns a list of antonyms for the inputted word."""
try:
await ctx.message.delete()
except discord.HTTPException:
pass
word_id = f_arg
for arg in args:
word_id = str(word_id) + " " + str(arg)
lang = 'en'
urllib.parse.quote(word_id)
async with aiohttp.ClientSession(headers={'app_id': dictionaryId, 'app_key': dictionaryKey}) as session:
async with session.get(f'https://od-api.oxforddictionaries.com/api/v1/inflections/{lang}/{word_id.lower()}') \
as wordLemmaReq:
"""==============START OF API REQUEST CHECK=============="""
if wordLemmaReq.status != 200 and wordLemmaReq.status == 404:
async with session.get(f'https://od-api.oxforddictionaries.com:443/api/v1'
f'/search/{lang}?q={word_id.lower()}&prefix=false') as searchReq:
searchResp = json.loads(await searchReq.text())
try:
altWord = f"[{searchResp['results'][0]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][0]['id']}) \n"
except IndexError:
embed = discord.Embed(title=f'Could not find the word "{word_id.lower()}."',
description=f'No similar words found. \n'
f'Make sure that **"{word_id.lower()}"** is a valid word.',
color=colorCode[2]
)
await ctx.send(embed=embed)
return
for i in range(1, 5):
try:
altWord += f"[{searchResp['results'][i]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][i]['id']}) \n"
except IndexError:
break
embed = discord.Embed(title=f'Could not find antonyms for the word "{word_id.lower()}."',
description='Similar words: \n' + str(altWord),
color=colorCode[1]
)
await ctx.send(embed=embed)
return
elif wordLemmaReq.status != 200:
embed = discord.Embed(title='Something went wrong',
description=f'Error: {wordLemmaReq.reason} \nCode: {wordLemmaReq.status}',
color=colorCode[2])
await ctx.send(embed=embed)
return
"""===============END OF API REQUEST CHECK==============="""
wordLemmaResp = json.loads(await wordLemmaReq.text())
wordLemmaId = wordLemmaResp['results'][0]['lexicalEntries'][0]['inflectionOf'][0]['id']
async with session.get(f'https://od-api.oxforddictionaries.com/api/v1/entries/'
f'{lang}/{wordLemmaId.lower()}/antonyms') \
as wordReq:
"""==============START OF API REQUEST CHECK=============="""
if wordReq.status != 200 and wordReq.status == 404:
async with session.get(f'https://od-api.oxforddictionaries.com:443/api/v1'
f'/search/{lang}?q={wordLemmaId.lower()}&prefix=false') as searchReq:
searchResp = json.loads(await searchReq.text())
try:
altWord = f"[{searchResp['results'][0]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][0]['id']}) \n"
except IndexError:
embed = discord.Embed(title=f'Could not find the word "{wordLemmaId.lower()}."',
description=f'No similar words found. \n'
f'Make sure that **"{wordLemmaId.lower()}"** '
f'is a valid word.',
color=colorCode[2]
)
await ctx.send(embed=embed)
return
for i in range(1, 5):
try:
altWord += f"[{searchResp['results'][i]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][i]['id']}) \n"
except IndexError:
break
embed = discord.Embed(title=f'Could not find antonyms for the word "{wordLemmaId.lower()}."',
description='Similar words: \n' + str(altWord),
color=colorCode[1]
)
await ctx.send(embed=embed)
return
elif wordReq.status != 200:
embed = discord.Embed(title='Something went wrong',
description=f'Error: {wordReq.reason} \nCode: {wordReq.status}',
color=colorCode[2])
await ctx.send(embed=embed)
return
"""===============END OF API REQUEST CHECK==============="""
wordResp = json.loads(await wordReq.text())
#pprint(wordResp) #testing
"""=================BUILDING THE DISCORD EMBED START================="""
"""Will attempt to give two different contexts (with an example sentence) with 3 antonyms each"""
try:
wordAnt1 = f"{wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['antonyms'][0]['text']}\n"
except KeyError:
embed = discord.Embed(title=f'Could not find any antonyms for "{word_id.lower()}."',
description="Huh, that's weird.",
color=colorCode[2]
)
await ctx.send(embed=embed)
return
embed = discord.Embed(title=f"Antonyms for {wordResp['results'][0]['word']}",
description=wordResp['results'][0]['lexicalEntries'][0]['lexicalCategory'],
color=colorCode[0])
for i in range(1,3):
try:
wordAnt1 += f"{wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['antonyms'][i]['text']}\n"
except IndexError:
break
try:
wordExample1 = wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['examples'][0]['text']
embed.add_field(name=wordAnt1,
value=f'"{str(wordExample1)}"', inline=False)
except KeyError:
embed.add_field(name=wordAnt1,
value='example n/a', inline=False)
try:
wordAnt2 = f"{wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][1]['antonyms'][0]['text']}\n"
for i in range(1,3):
try:
wordAnt2 += f"{wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][1]['antonyms'][i]['text']}\n"
except IndexError:
break
try:
wordExample2 = wordResp['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][1]['examples'][0]['text']
embed.add_field(name=wordAnt2,
value=f'"{str(wordExample2)}"', inline=False)
except KeyError:
embed.add_field(name=wordAnt2,
value='example n/a', inline=False)
except (KeyError, IndexError):
pass
embed.set_footer(text=f'Antonyms for "{word_id}" requested by {ctx.message.author.name}.',
icon_url=ctx.message.author.avatar_url)
"""=================BUILDING THE DISCORD EMBED END================="""
await ctx.send(embed=embed)
"""Command for EXAMPLE SENTENCES with a word chosen by the user"""
@commands.command(aliases=['sentence', 'sentences', 'wsen', 'sen', 'wordsentence', 'example', 'wordexample'])
@commands.cooldown(2, 4, commands.BucketType.user)
async def word_sentences(self, ctx, f_arg="word", *args):
"""Returns a list of example sentences for the inputted word."""
try:
await ctx.message.delete()
except discord.HTTPException:
pass
word_id = f_arg
for arg in args:
word_id = str(word_id) + " " + str(arg)
lang = 'en'
urllib.parse.quote(word_id)
async with aiohttp.ClientSession(headers={'app_id': dictionaryId, 'app_key': dictionaryKey}) as session:
async with session.get(f'https://od-api.oxforddictionaries.com/api/v1/inflections/{lang}/{word_id.lower()}') \
as wordLemmaReq:
"""==============START OF API REQUEST CHECK=============="""
if wordLemmaReq.status != 200 and wordLemmaReq.status == 404:
async with session.get(f'https://od-api.oxforddictionaries.com:443/api/v1'
f'/search/{lang}?q={word_id.lower()}&prefix=false') as searchReq:
searchResp = json.loads(await searchReq.text())
try:
altWord = f"[{searchResp['results'][0]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][0]['id']}) \n"
except IndexError:
embed = discord.Embed(title=f'Could not find the word "{word_id.lower()}."',
description=f'No similar words found. \n'
f'Make sure that **"{word_id.lower()}"** is a valid word.',
color=colorCode[2]
)
await ctx.send(embed=embed)
return
for i in range(1, 5):
try:
altWord += f"[{searchResp['results'][i]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][i]['id']}) \n"
except IndexError:
break
embed = discord.Embed(title=f'Could not find any sentences for the word "{word_id.lower()}."',
description='You can try searching for: \n' + str(altWord),
color=colorCode[1]
)
await ctx.send(embed=embed)
return
elif wordLemmaReq.status != 200:
embed = discord.Embed(title='Something went wrong',
description=f'Error: {wordLemmaReq.reason} \nCode: {wordLemmaReq.status}',
color=colorCode[2])
await ctx.send(embed=embed)
return
"""===============END OF API REQUEST CHECK==============="""
wordLemmaResp = json.loads(await wordLemmaReq.text())
wordLemmaId = wordLemmaResp['results'][0]['lexicalEntries'][0]['inflectionOf'][0]['id']
async with session.get(
f'https://od-api.oxforddictionaries.com/api/v1/entries/{lang}/{wordLemmaId.lower()}/sentences') \
as wordReq:
"""==============START OF API REQUEST CHECK=============="""
if wordReq.status != 200 and wordReq.status == 404:
async with session.get(f'https://od-api.oxforddictionaries.com:443/api/v1'
f'/search/{lang}?q={wordLemmaId.lower()}&prefix=false') as searchReq:
searchResp = json.loads(await searchReq.text())
try:
altWord = f"[{searchResp['results'][0]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][0]['id']}) \n"
except IndexError:
embed = discord.Embed(title=f'Could not find the word "{wordLemmaId.lower()}."',
description=f'No similar words found. \n'
f'Make sure that **"{wordLemmaId.lower()}"** '
f'is a valid word.',
color=colorCode[2]
)
await ctx.send(embed=embed)
return
for i in range(1, 5):
try:
altWord += f"[{searchResp['results'][i]['id']}](https://en.oxforddictionaries.com" \
f"/definition/{searchResp['results'][i]['id']}) \n"
except IndexError:
break
embed = discord.Embed(title=f'Could not find any sentences for the word "{wordLemmaId.lower()}."',
description='You can try searching for: \n' + str(altWord),
color=colorCode[1]
)
await ctx.send(embed=embed)
return
elif wordReq.status != 200:
embed = discord.Embed(title='Something went wrong',
description=f'Error: {wordReq.reason} \nCode: {wordReq.status}',
color=colorCode[2])
await ctx.send(embed=embed)
return
"""===============END OF API REQUEST CHECK==============="""
wordResp = json.loads(await wordReq.text())
#pprint(wordResp) #testing
"""=================BUILDING THE DISCORD EMBED START================="""
"""Will attempt to give two different contexts (with an example sentence) with 3 synonyms each"""
try:
wordSen1 = f"1. {wordResp['results'][0]['lexicalEntries'][0]['sentences'][0]['text']}\n"
except (IndexError, KeyError):
embed = discord.Embed(title=f'Could not find any sentences for "{word_id.lower()}."',
description="Huh, that's weird.",
color=colorCode[2]
)
await ctx.send(embed=embed)
return
embed = discord.Embed(title=wordResp['results'][0]['word'],
description=f"Sentence examples for {wordResp['results'][0]['word']}",
color=colorCode[0])
for i in range(1, 2):
try:
wordSen1 += f"{i+1}. {wordResp['results'][0]['lexicalEntries'][0]['sentences'][i]['text']}\n"
except IndexError:
break
try:
wordType1 = \
wordResp['results'][0]['lexicalEntries'][0]['lexicalCategory']
embed.add_field(name=wordType1,
value=wordSen1, inline=False)
except KeyError:
embed.add_field(name='Sentence 1',
value=wordSen1, inline=False)
try:
wordSen2 = f"1. {wordResp['results'][0]['lexicalEntries'][1]['sentences'][0]['text']}\n"
for i in range(1, 2):
try:
wordSen2 += f"{i+1}. {wordResp['results'][0]['lexicalEntries'][1]['sentences'][i]['text']}\n"
except IndexError:
break
try:
wordType2 = \
wordResp['results'][0]['lexicalEntries'][1]['lexicalCategory']
embed.add_field(name=wordType2,
value=wordSen2, inline=False)
except KeyError:
embed.add_field(name='Sentence 2',
value=wordSen2, inline=False)
except (IndexError, KeyError):
pass
embed.set_footer(text=f'Sentence examples for "{word_id}" requested by {ctx.message.author.name}.',
icon_url=ctx.message.author.avatar_url)
"""=================BUILDING THE DISCORD EMBED END================="""
await ctx.send(embed=embed)
def setup(client):
client.add_cog(ApiFunctions(client))