aboutsummaryrefslogtreecommitdiff
path: root/modules/google.py
blob: f525fc613b96114f02bb3fb9e1a37114adadb291 (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
# --require-config google-api-key
# --require-config google-search-id

import Utils

URL_GOOGLESEARCH = "https://www.googleapis.com/customsearch/v1"


class Module(object):
    def __init__(self, bot):
        self.bot = bot
        bot.events.on("received").on("command").on("google",
                                                   "g").hook(self.google,
                                                             help="Google feeling lucky",
                                                             usage="[search term]")

    def google(self, event):
        phrase = event["args"] or event["buffer"].get()
        if phrase:
            page = Utils.get_url(URL_GOOGLESEARCH, get_params={
                "q": phrase, "key": self.bot.config[
                    "google-api-key"], "cx": self.bot.config[
                    "google-search-id"], "prettyPrint": "true",
                "num": 1, "gl": "gb"}, json=True)
            if page:
                if "items" in page and len(page["items"]):
                    event["stdout"].write(page["items"][0][
                                              "link"])
                else:
                    event["stderr"].write("No results found")
            else:
                event["stderr"].write("Failed to load results")
        else:
            event["stderr"].write("No phrase provided")