bitbot-3.11-fork/modules/define.py

72 lines
2.4 KiB
Python
Raw Normal View History

#--require-config wordnik-api-key
import time
from src import Utils
2016-03-29 11:56:58 +00:00
URL_WORDNIK = "https://api.wordnik.com/v4/word.json/%s/definitions"
URL_WORDNIK_RANDOM = "https://api.wordnik.com/v4/words.json/randomWord"
RANDOM_DELAY_SECONDS = 3
2016-03-29 11:56:58 +00:00
class Module(object):
def __init__(self, bot, events, exports):
2016-03-29 11:56:58 +00:00
self.bot = bot
2018-09-24 12:24:36 +00:00
self._last_called = 0
2018-09-24 12:23:59 +00:00
def _get_definition(self, word):
word = event["args"] if "args" in event else event
page = Utils.get_url(URL_WORDNIK % word, get_params={
"useCanonical": "true", "limit": 1,
"sourceDictionaries": "wiktionary", "api_key": self.bot.config[
2018-09-24 12:23:59 +00:00
"wordnik-api-key"]}, json=True)
return page
@Utils.hook("received.command.define", usage="<phrase>")
2016-03-29 11:56:58 +00:00
def define(self, event):
"""
Define a provided term
"""
2016-03-29 11:56:58 +00:00
if event["args"]:
word = event["args"]
else:
word = event["buffer"].get(from_self=False)
2018-09-24 12:23:59 +00:00
page = self._get_definition(word)
2016-03-29 11:56:58 +00:00
if page:
if len(page):
event["stdout"].write("%s: %s" % (page[0]["word"],
page[0]["text"]))
else:
event["stderr"].write("No definitions found")
else:
event["stderr"].write("Failed to load results")
@Utils.hook("received.command.randomword")
def random_word(self, event):
"""
Define a random word
"""
2018-09-24 12:24:36 +00:00
if not self._last_called or (time.time()-self._last_called >=
2018-09-24 12:23:59 +00:00
RANDOM_DELAY_SECONDS):
2018-09-24 12:24:36 +00:00
self._last_called = time.time()
page = Utils.get_url(URL_WORDNIK_RANDOM, get_params={
"api_key":self.bot.config["wordnik-api-key"],
"min_dictionary_count":1},json=True)
2018-09-24 12:23:59 +00:00
if page and len(page):
definition = self._get_definition(page["word"])
if len(definition):
definition = definition[0]
else:
2018-09-24 12:23:59 +00:00
event["stderr"].write("Try again in a couple of "
"seconds")
return
event["stdout"].write("Random Word: %s - Definition: %s" % (
page["word"], definition["text"]))
else:
event["stderr"].write("Failed to load results")
else:
2018-09-24 12:23:59 +00:00
event["stderr"].write("Try again in a couple of seconds")