53 lines
1.7 KiB
Python
53 lines
1.7 KiB
Python
from bot import IRCLine
|
|
BOT = None
|
|
|
|
# html utility function
|
|
from bs4 import BeautifulSoup
|
|
import requests
|
|
|
|
def get_html(url):
|
|
r = requests.get(url)
|
|
r.raise_for_status()
|
|
return BeautifulSoup(r.content,"html.parser")
|
|
# end html utility function
|
|
|
|
URL = "https://randomword.com/"
|
|
|
|
def get(generator=""):
|
|
try:
|
|
soup = get_html(URL+generator)
|
|
ret = dict()
|
|
ret["word"]=soup.find("div",dict(id="random_word")).text if soup.find("div",dict(id="random_word")) else ""
|
|
ret["definition"]=soup.find("div",dict(id="random_word_definition")).text if soup.find("div",dict(id="random_word_definition")) else ""
|
|
return ret
|
|
except:
|
|
return dict(word="",definition="")
|
|
|
|
# event response utility
|
|
def respond(event,msg):
|
|
if not BOT: return
|
|
target = event.target if event.target.startswith("#") else event.hostmask.nick
|
|
BOT.socket.send(IRCLine("PRIVMSG",target,":"+(event.hostmask.nick+": " if event.target.startswith("#") else "")+msg).line)
|
|
# end event response utility
|
|
|
|
def on_cmd_randomword(event):
|
|
if not BOT: return
|
|
gen = ""
|
|
if len(event.parts)>=1: gen=event.parts[0].lower()
|
|
if gen and gen not in "noun sentence question adjective idiom verb letter paragraph vocabulary".split():
|
|
respond(event,"Invalid generator! Must be one of the generators on RandomWord.com.")
|
|
return
|
|
resp = get(gen)
|
|
if resp["word"] and resp["definition"]:
|
|
respond(event,f"{resp['word']} - {resp['definition']}")
|
|
elif resp["definition"] and not resp["word"]:
|
|
respond(event,resp["definition"])
|
|
else:
|
|
respond(event,"Something went wrong. Please try again later.")
|
|
|
|
def register(bot):
|
|
global BOT
|
|
BOT=bot
|
|
bot.event_manager.on("command_randomword",on_cmd_randomword)
|
|
bot.event_manager.on("command_rw",on_cmd_randomword)
|