aboutsummaryrefslogtreecommitdiff
path: root/modules/urbandictionary.py
blob: b71dc45be01dcc9a38a84fafeae61ebe7c0d63d0 (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
35
36
37
38
39
40
#--depends-on commands

from src import ModuleManager, utils

URL_URBANDICTIONARY = "http://api.urbandictionary.com/v0/define"

class Module(ModuleManager.BaseModule):
    _name = "UrbanDictionary"

    @utils.hook("received.command.ud", alias_of="urbandictionary")
    @utils.hook("received.command.urbandictionary", min_args=1)
    def ud(self, event):
        """
        :help: Get the definition of a provided term from Urban Dictionary
        :usage: <term> [#<number>]
        """
        number = 1
        term = event["args_split"]
        if (event["args_split"][-1].startswith("#") and
                len(event["args_split"]) > 1 and
                event["args_split"][-1][1:].isdigit()):
            number = int(event["args_split"][-1][1:])
            term = term[:-1]
        term = " ".join(term)

        page = utils.http.request(URL_URBANDICTIONARY,
            get_params={"term": term}, json=True)
        if page:
            if len(page.data["list"]):
                if number > 0 and len(page.data["list"]) > number-1:
                    definition = page.data["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:
            raise utils.EventResultsError()