Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.6 KiB

  1. # Public domain, 2013 Legoktm; 2013, 2018 Ben Kurtovic
  2. import re
  3. from json import loads
  4. from urllib.parse import quote
  5. from urllib.request import urlopen
  6. from earwigbot.commands import Command
  7. class UrbanDictionary(Command):
  8. """Get the definition of a word or phrase using Urban Dictionary."""
  9. name = "urban"
  10. commands = ["urban", "urbandictionary", "dct", "ud"]
  11. @staticmethod
  12. def _normalize_term(term):
  13. return re.sub(r"\W", "", term.lower())
  14. @staticmethod
  15. def _normalize_text(text):
  16. return re.sub(r"\[(.*?)\]", "\\1", re.sub(r"\s+", " ", text))
  17. def process(self, data):
  18. if not data.args:
  19. self.reply(data, "What do you want to define?")
  20. return
  21. url = "http://api.urbandictionary.com/v0/define?term={0}"
  22. arg = " ".join(data.args)
  23. query = urlopen(url.format(quote(arg, safe=""))).read()
  24. res = loads(query)
  25. results = res.get("list")
  26. if not results:
  27. self.reply(data, "Sorry, no results found.")
  28. return
  29. result = results[0]
  30. definition = self._normalize_text(result["definition"])
  31. example = self._normalize_text(result["example"])
  32. url = result["permalink"].rsplit("/", 1)[0]
  33. if definition and definition[-1] not in (".", "!", "?"):
  34. definition += "."
  35. msg = "{} \x02Example\x0f: {} {}".format(
  36. definition.encode("utf8"), example.encode("utf8"), url
  37. )
  38. if self._normalize_term(result["word"]) != self._normalize_term(arg):
  39. msg = "\x02{}\x0f: {}".format(result["word"].encode("utf8"), msg)
  40. self.reply(data, msg)