Ejemplo n.º 1
0
    def _guide(name):
        game_id = name.lower().replace(" ", "-")
        session = requests_session()
        page = session.get(GUIDE_URL.format(game_id))
        tree = lxml.html.fromstring(page.text)

        li_elements = tree.cssselect(
            "#col_l .bl_la_main_guide .showhide ul li")
        if li_elements:
            return [x.text_content().strip() for x in li_elements[:5]]
        else:
            elements = tree.cssselect("#col_l .bl_la_main_guide .showhide p")
            if not elements:
                elements = tree.cssselect(
                    "#col_l .bl_la_main_guide .showhide div div")

            if elements:
                info = []
                html = lxml.html.tostring(elements[0])
                lines = html.decode("utf-8").split("<br>")
                for line in lines[1:6]:
                    span_str = "<span>{0}</span>".format(line)
                    span = lxml.html.fragment_fromstring(span_str)
                    s = span.text_content().strip()
                    if s.startswith("-"):
                        s = s[1:]
                    info.append(s)
                return info
Ejemplo n.º 2
0
    def on_command(self, msg, stdin, stdout):
        query = " ".join(msg["args"][1:])
        if not query:
            query = stdin.read().strip()

        if not query:
            raise StopCommandWithHelp(self)

        url = "https://www.googleapis.com/customsearch/v1"
        payload = {
            "key": self.key,
            "cx": self.cx,
            "q": query,
            "num": 4,
        }

        session = requests_session()
        res = session.get(url, params=payload).json()
        if "error" in res:
            raise StopCommand(res["error"]["message"])
        elif "items" in res:
            for i, item in enumerate(res["items"]):
                print("[{0}]: {1} - {2}".format(i, item["title"],
                                                item["link"]),
                      file=stdout)
        else:
            raise StopCommand("No results!")
Ejemplo n.º 3
0
    def on_command(self, msg, stdin, stdout):
        if len(msg["args"]) >= 3:
            url = "http://ojp.nationalrail.co.uk/service/ldb/liveTrainsJson"
            payload = {
                "liveTrainsFrom": msg["args"][1],
                "liveTrainsTo": msg["args"][2],
                "departing": "true",
            }

            session = requests_session()
            res = session.get(url, params=payload).json()
            if not res["trains"]:
                raise StopCommand("No trains.")

            for i, train in enumerate(res["trains"]):
                if train[4]:
                    print("[{}]: the {} to {} on platform {} ({}).".format(
                        i, train[1], train[2], train[4], train[3].lower()),
                          file=stdout)
                else:
                    print("[{}]: the {} to {} ({}).".format(
                        i, train[1], train[2], train[3].lower()),
                          file=stdout)
        else:
            raise StopCommandWithHelp(self)
Ejemplo n.º 4
0
    def on_command(self, msg, stdin, stdout):
        query = " ".join(msg["args"][1:])
        if not query:
            query = stdin.read().strip()

        if not query:
            raise StopCommandWithHelp(self)

        url = "https://www.googleapis.com/customsearch/v1"
        payload = {
            "key": self.key,
            "cx": self.cx,
            "q": query,
            "num": 4,
        }

        session = requests_session()
        res = session.get(url, params=payload).json()
        if "error" in res:
            raise StopCommand(res["error"]["message"])
        elif "items" in res:
            for i, item in enumerate(res["items"]):
                print("[{0}]: {1} - {2}".format(i, item["title"],
                                                item["link"]), file=stdout)
        else:
            raise StopCommand("No results!")
Ejemplo n.º 5
0
    def _search(self, query):
        url = "https://www.googleapis.com/youtube/v3/search"
        payload = {"key": self.key, "q": query, "maxResults": 3, "part": "snippet", "type": "video"}

        s = requests_session()
        res = s.get(url, params=payload).json()
        return res.get("items", [])
Ejemplo n.º 6
0
    def on_command(self, msg, stdin, stdout):
        if len(msg["args"]) >= 3:
            url = "http://ojp.nationalrail.co.uk/service/ldb/liveTrainsJson"
            payload = {
                "liveTrainsFrom": msg["args"][1],
                "liveTrainsTo": msg["args"][2],
                "departing": "true",
            }

            session = requests_session()
            res = session.get(url, params=payload).json()
            if not res["trains"]:
                raise StopCommand("No trains.")

            for i, train in enumerate(res["trains"]):
                if train[4]:
                    print("[{}]: the {} to {} on platform {} ({}).".format(
                        i, train[1], train[2], train[4], train[3].lower()
                    ), file=stdout)
                else:
                    print("[{}]: the {} to {} ({}).".format(
                        i, train[1], train[2], train[3].lower()
                    ), file=stdout)
        else:
            raise StopCommandWithHelp(self)
Ejemplo n.º 7
0
    def on_command(self, msg, stdin, stdout):
        topic = " ".join(msg["args"][1:])
        if not topic:
            topic = stdin.read().strip()

        url = "https://ajax.googleapis.com/ajax/services/search/news"
        payload = {
            "v": "1.0",
            "rsz": "5",
        }
        if topic:
            payload["q"] = topic
        else:
            payload["topic"] = "h"

        session = requests_session()
        res = session.get(url, params=payload).json()
        stories = res["responseData"]["results"][:3]
        if stories:
            for i, story in enumerate(stories):
                title = story["titleNoFormatting"].replace("&#39;", "'") \
                                                  .replace("`", "'") \
                                                  .replace("&quot;", "\"")
                link = story["unescapedUrl"]
                print("[{0}]: {1} - {2}".format(i, title, link), file=stdout)
        else:
            raise StopCommand("No news stories.")
Ejemplo n.º 8
0
    def _search_mid(self, query):
        url = "https://www.googleapis.com/freebase/v1/search"
        payload = {"query": query, "key": self.key, "limit": 1}

        session = requests_session()
        res = session.get(url, params=payload).json()
        if res["result"]:
            return res["result"][0]["mid"]
Ejemplo n.º 9
0
    def _search_mid(self, query):
        url = "https://www.googleapis.com/freebase/v1/search"
        payload = {"query": query, "key": self.key, "limit": 1}

        session = requests_session()
        res = session.get(url, params=payload).json()
        if res["result"]:
            return res["result"][0]["mid"]
Ejemplo n.º 10
0
    def _get_video_info(self, video_id):
        url = "http://vimeo.com/api/v2/video/{}.json".format(video_id)

        s = requests_session()
        res = s.get(url).json()
        try:
            return res[0]
        except IndexError:
            return None
Ejemplo n.º 11
0
    def _get_video_info(self, video_id):
        url = "http://vimeo.com/api/v2/video/{}.json".format(video_id)

        s = requests_session()
        res = s.get(url).json()
        try:
            return res[0]
        except IndexError:
            return None
Ejemplo n.º 12
0
    def _get_video_info(self, video_id):
        url = "https://www.googleapis.com/youtube/v3/videos"
        payload = {
            "key": self.key,
            "id": video_id,
            "part": ",".join(["contentDetails", "snippet", "statistics"])
        }

        s = requests_session()
        res = s.get(url, params=payload).json()
        if res["items"]:
            return res["items"][0]
Ejemplo n.º 13
0
 def on_command(self, msg, stdin, stdout):
     if len(msg["args"]) >= 2:
         action = msg["args"][1]
         if "status".startswith(action):
             session = requests_session()
             res = session.get(STATUS_URL).json()
             print("{0} - {1}".format(res["created_on"], res["body"]),
                   file=stdout)
         else:
             raise StopCommandWithHelp(self)
     else:
         raise StopCommandWithHelp(self)
Ejemplo n.º 14
0
 def on_command(self, msg, stdin, stdout):
     if len(msg["args"]) >= 2:
         action = msg["args"][1]
         if "status".startswith(action):
             session = requests_session()
             res = session.get(STATUS_URL).json()
             print("{0} - {1}".format(res["created_on"], res["body"]),
                   file=stdout)
         else:
             raise StopCommandWithHelp(self)
     else:
         raise StopCommandWithHelp(self)
Ejemplo n.º 15
0
    def _get_video_info(self, video_id):
        url = "https://www.googleapis.com/youtube/v3/videos"
        payload = {
            "key": self.key,
            "id": video_id,
            "part": ",".join(["contentDetails", "snippet", "statistics"])
        }

        s = requests_session()
        res = s.get(url, params=payload).json()
        if res["items"]:
            return res["items"][0]
Ejemplo n.º 16
0
    def on_command(self, msg, stdin, stdout):
        url = None
        if len(msg["args"]) >= 3:
            url = msg["args"][2]
        else:
            url = stdin.read().strip()

        if url:
            session = requests_session()
            page = session.get(url, timeout=15)
            print(page.text, file=stdout)
        else:
            raise StopCommandWithHelp(self)
Ejemplo n.º 17
0
    def _get_media_info(self, shortcode):
        url = "https://api.instagram.com/v1/media/shortcode/{}" \
              .format(shortcode)
        params = {
            "client_id": self.client_id,
        }

        s = requests_session()
        res = s.get(url, params=params).json()
        try:
            return res["data"]
        except KeyError:
            return None
Ejemplo n.º 18
0
    def _search(self, terms):
        session = requests_session()
        page = session.post(SEARCH_URL, data={"search": terms})
        tree = lxml.html.fromstring(page.text)

        results = []
        elements = tree.cssselect(".bl_la_main .linkT")
        for i, element in enumerate(elements[::2]):
            game_id = element.get("href")[6:-10]
            self.saved_items[i] = game_id
            results.append(element.text_content())

        return results
Ejemplo n.º 19
0
    def on_command(self, msg, stdin, stdout):
        if len(msg["args"]) <= 1:
            raise StopCommandWithHelp(self)

        action = msg["args"][1]
        if "status".startswith(action):
            session = requests_session()
            res = session.get(STATUS_URL).json()
            status = res["status"]
            print("Production: {}".format(status["Production"]), file=stdout)
            print("Development: {}".format(status["Development"]), file=stdout)
        else:
            raise StopCommandWithHelp(self)
Ejemplo n.º 20
0
    def _get_media_info(self, shortcode):
        url = "https://api.instagram.com/v1/media/shortcode/{}" \
              .format(shortcode)
        params = {
            "client_id": self.client_id,
        }

        s = requests_session()
        res = s.get(url, params=params).json()
        try:
            return res["data"]
        except KeyError:
            return None
Ejemplo n.º 21
0
    def _search(self, query):
        url = "https://www.googleapis.com/youtube/v3/search"
        payload = {
            "key": self.key,
            "q": query,
            "maxResults": 3,
            "part": "snippet",
            "type": "video"
        }

        s = requests_session()
        res = s.get(url, params=payload).json()
        return res.get("items", [])
Ejemplo n.º 22
0
    def on_command(self, msg, stdin, stdout):
        if len(msg["args"]) <= 1:
            raise StopCommandWithHelp(self)

        action = msg["args"][1]
        if "status".startswith(action):
            session = requests_session()
            res = session.get(STATUS_URL).json()
            status = res["status"]
            print("Production: {}".format(status["Production"]), file=stdout)
            print("Development: {}".format(status["Development"]), file=stdout)
        else:
            raise StopCommandWithHelp(self)
Ejemplo n.º 23
0
    def on_command(self, msg, stdin, stdout):
        url = None
        if len(msg["args"]) >= 2:
            url = msg["args"][1]
        else:
            url = stdin.read().strip()

        if not url:
            raise StopCommandWithHelp(self)

        url = "http://isitup.org/{0}.json".format(urllib.parse.quote(url))
        session = requests_session()
        res = session.get(url).json()
        if res["status_code"] == 1:
            print("{0} is up from here.".format(res["domain"]), file=stdout)
        else:
            print("{0} is down from here.".format(res["domain"]), file=stdout)
Ejemplo n.º 24
0
    def on_command(self, msg, stdin, stdout):
        short_urls = msg["args"][1:]
        if not short_urls:
            short_urls = stdin.read().strip().split()

        if not short_urls:
            raise StopCommandWithHelp(self)

        url = "http://api.unshorten.it/"
        session = requests_session()
        for i, short_url in enumerate(short_urls):
            payload = {"shortURL": short_url, "apiKey": self.api_key}

            text = session.get(url, params=payload).text
            print("{}: {}".format(
                self.bot.format("[{}]".format(i), Style.bold), text),
                  file=stdout)
Ejemplo n.º 25
0
    def on_command(self, msg, stdin, stdout):
        short_urls = msg["args"][1:]
        if not short_urls:
            short_urls = stdin.read().strip().split()

        if not short_urls:
            raise StopCommandWithHelp(self)

        url = "http://api.unshorten.it/"
        session = requests_session()
        for i, short_url in enumerate(short_urls):
            payload = {
                "shortURL": short_url,
                "apiKey": self.api_key
            }

            text = session.get(url, params=payload).text
            print("{}: {}".format(
                self.bot.format("[{}]".format(i), Style.bold),
                text), file=stdout)
Ejemplo n.º 26
0
    def on_command(self, msg, stdin, stdout):
        query = " ".join(msg["args"][1:])
        if not query:
            query = stdin.read().strip()

        if query:
            payload = {"q": query, "output": "toolbar"}
            session = requests_session()
            page = session.get(URL, params=payload)
            tree = lxml.etree.fromstring(page.text)

            suggestions = []
            for suggestion in tree.xpath("//suggestion"):
                suggestions.append(suggestion.get("data"))

            if suggestions:
                print(", ".join(suggestions[:5]), file=stdout)
            else:
                raise StopCommand("No suggestions.")
        else:
            raise StopCommandWithHelp(self)
Ejemplo n.º 27
0
    def on_command(self, msg, stdin, stdout):
        query = " ".join(msg["args"][1:])
        if not query:
            query = stdin.read().strip()

        if query:
            payload = {"q": query, "output": "toolbar"}
            session = requests_session()
            page = session.get(URL, params=payload)
            tree = lxml.etree.fromstring(page.text)

            suggestions = []
            for suggestion in tree.xpath("//suggestion"):
                suggestions.append(suggestion.get("data"))

            if suggestions:
                print(", ".join(suggestions[:5]), file=stdout)
            else:
                raise StopCommand("No suggestions.")
        else:
            raise StopCommandWithHelp(self)
Ejemplo n.º 28
0
    def on_command(self, msg, stdin, stdout):
        session = requests_session()
        url = "http://oeis.org/search"
        payload = {
            "fmt": "text",
            "q": " ".join(msg["args"][1:]),
        }

        response = session.get(url, params=payload)
        if response.status_code == 200:
            self.i = -1
            # only process lines starting with a percent symbol
            for line in filter(lambda l: l.startswith("%"),
                               response.text.split("\n")):
                # content default is set to None
                flag, identifier, content, *_ = line.split(" ", 2) + [None]
                # process the line
                self.process(flag, identifier, content, stdout)
                # stop when limit is reached
                if self.i >= self.limit:
                    print("...", file=stdout)
                    break
Ejemplo n.º 29
0
    def on_command(self, msg, stdin, stdout):
        query = " ".join(msg["args"][1:])
        if not query:
            query = stdin.read().strip()

        if query:
            url = "http://api.wolframalpha.com/v2/query"
            payload = {
                "input": query,
                "appid": self.appid,
            }

            session = requests_session()
            page = session.get(url, params=payload, timeout=15)
            if page.status_code == 200:
                tree = lxml.etree.fromstring(page.content)
                pods = []
                for pod in tree.xpath("//pod"):
                    pods.append(pod)

                if len(pods) >= 2:
                    small_result = '{} -> {}'.format(self.format_pod(pods[0]),
                                                     self.format_pod(pods[1]))
                    if len(small_result) <= 100 and "\n" not in small_result:
                        print(small_result, file=stdout)
                    else:
                        for pod in pods[:2]:
                            print("# {0}".format(pod.get("title")),
                                  file=stdout)
                            for subpod in pod.findall("subpod"):
                                if subpod.get("title"):
                                    print("## {0}".format(subpod.get("title")),
                                          file=stdout)
                                print(self.format_subpod(subpod), file=stdout)
                else:
                    raise StopCommand("Nothing more to say.")
        else:
            raise StopCommandWithHelp(self)
Ejemplo n.º 30
0
    def on_command(self, msg, stdin, stdout):
        query = " ".join(msg["args"][1:])
        if not query:
            query = stdin.read().strip()

        if query:
            url = "http://api.wolframalpha.com/v2/query"
            payload = {
                "input": query,
                "appid": self.appid,
            }

            session = requests_session()
            page = session.get(url, params=payload, timeout=15)
            if page.status_code == 200:
                tree = lxml.etree.fromstring(page.content)
                pods = []
                for pod in tree.xpath("//pod"):
                    pods.append(pod)

                if len(pods) >= 2:
                    small_result = '{} -> {}'.format(self.format_pod(pods[0]),
                                                     self.format_pod(pods[1]))
                    if len(small_result) <= 100 and "\n" not in small_result:
                        print(small_result, file=stdout)
                    else:
                        for pod in pods[:2]:
                            print("# {0}".format(pod.get("title")),
                                  file=stdout)
                            for subpod in pod.findall("subpod"):
                                if subpod.get("title"):
                                    print("## {0}".format(subpod.get("title")),
                                          file=stdout)
                                print(self.format_subpod(subpod), file=stdout)
                else:
                    raise StopCommand("Nothing more to say.")
        else:
            raise StopCommandWithHelp(self)
Ejemplo n.º 31
0
 def get_bad_joke(self):
     url = "http://jokels.com/random_joke"
     session = requests_session()
     res = session.get(url).json()
     return (res["joke"]["question"], res["joke"]["answer"])
Ejemplo n.º 32
0
 def _topic(self, mid):
     url = "https://www.googleapis.com/freebase/v1/topic{}".format(mid)
     session = requests_session()
     return session.get(url).json()
Ejemplo n.º 33
0
 def _get_channel_info(self, channel_id):
     url = "https://api.twitch.tv/kraken/channels/{}".format(channel_id)
     s = requests_session()
     res = s.get(url).json()
     if res.get("error", None) is None:
         return res
Ejemplo n.º 34
0
 def _topic(self, mid):
     url = "https://www.googleapis.com/freebase/v1/topic{}".format(mid)
     session = requests_session()
     return session.get(url).json()
Ejemplo n.º 35
0
 def _get_channel_info(self, channel_id):
     url = "https://api.twitch.tv/kraken/channels/{}".format(channel_id)
     s = requests_session()
     res = s.get(url).json()
     if res.get("error", None) is None:
         return res