aboutsummaryrefslogtreecommitdiff
path: root/modules/urbandictionary.py
blob: 6151afb8b6aeca08bad163cb2559955908106478 (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import json, re
from src import ModuleManager, Utils

URL_URBANDICTIONARY = "http://api.urbandictionary.com/v0/define"
REGEX_DEFNUMBER = re.compile("-n(\d+) \S+")

class Module(ModuleManager.BaseModule):
    @Utils.hook("received.command.urbandictionary|ud", min_args=1,
        usage="<term>")
    def ud(self, event):
        """
        Get the definition of a provided term from Urban Dictionary
        """
        term = event["args"]
        number = 1
        match = re.match(REGEX_DEFNUMBER, term)
        if match:
            number = int(match.group(1))
            term = term.split(" ", 1)[1]
        page = Utils.get_url(URL_URBANDICTIONARY, get_params={"term": term},
            json=True)
        if page:
            if len(page["list"]):
                if number > 0 and len(page["list"]) > number-1:
                    definition = page["list"][number-1]
                    event["stdout"].write("%s: %s" % (definition["word"],
                        definition["definition"].replace("\n", " ").replace(
                        "\r", "").replace("  ", " ")))
                else:
                    event["stderr"].write("Definition number does not exist")
            else:
                event["stderr"].write("No results found")
        else:
            event["stderr"].write("Failed to load results")