예제 #1
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)
예제 #2
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)
예제 #3
0
    def on_command(self, msg, stdin, stdout):
        if len(msg["args"]) >= 2:
            algorithm = msg["args"][1]
            value = " ".join(msg["args"][2:])
            if not value:
                value = stdin.read().strip()

            try:
                h = hashlib.new(algorithm)
            except (ValueError, TypeError):
                raise StopCommandWithHelp(self)
            else:
                h.update(bytes(value, "utf-8"))
                print(h.hexdigest(), file=stdout)
        else:
            raise StopCommandWithHelp(self)
예제 #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!")
예제 #5
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)
예제 #6
0
    def on_command(self, msg, stdin, stdout):
        args = msg["args"][1:]
        if not args:
            args = shlex.split(stdin.read().strip())

        if not args:
            raise StopCommandWithHelp(self)

        print(random.choice(args), file=stdout)
예제 #7
0
    def on_command(self, msg, stdin, stdout):
        pattern_str = " ".join(msg["args"][1:])
        if not pattern_str:
            raise StopCommandWithHelp(self)

        pattern = re.compile(pattern_str)
        for line in map(str.strip, stdin):
            if pattern_str in line or re.match(pattern, line):
                print(line, file=stdout)
예제 #8
0
    def on_command(self, msg, stdin, stdout):
        if len(msg["args"]) >= 3:
            algorithm = msg["args"][1]
            action = msg["args"][2]
            value = " ".join(msg["args"][3:])
            if not value:
                value = stdin.read().strip()

            if action not in ["encode", "decode"]:
                raise StopCommandWithHelp(self)

            if not value:
                raise StopCommandWithHelp(self)

            func = self._get_hash_func(algorithm, action)
            result = str(func(bytes(value, "utf-8")), "utf-8")
            print(result, file=stdout)
        else:
            raise StopCommandWithHelp(self)
예제 #9
0
    def on_command(self, msg, stdin, stdout):
        if len(msg["args"]) >= 2:
            user = msg["args"][1]
            message = " ".join(msg["args"][2:])
            if not message:
                message = stdin.read().strip()

            print("{0}: {1}".format(user, message), file=stdout)
        else:
            raise StopCommandWithHelp(self)
예제 #10
0
파일: http.py 프로젝트: adisubagja/smartbot
    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)
예제 #11
0
 def on_command(self, msg, stdin, stdout):
     if len(msg["args"]) >= 2:
         user = msg["args"][1]
         try:
             info = self.bot.storage["seen." + user]
             datetime_str = info["datetime"].strftime("%a %d %b %H:%M %Z") \
                 .strip()
             print("{0} {1} on {2}.".format(user, info["action"],
                                            datetime_str),
                   file=stdout)
         except KeyError:
             raise StopCommand(
                 "I don't know anything about {0}.".format(user))
     else:
         raise StopCommandWithHelp(self)
예제 #12
0
    def on_command(self, msg, stdin, stdout):
        person = None
        if len(msg["args"]) >= 2:
            person = msg["args"][1]
        else:
            person = stdin.read().strip()

        if not person:
            raise StopCommandWithHelp(self)

        tweets = self.twitter.get_user_timeline(screen_name=person)
        for i, tweet in enumerate(tweets[:3]):
            text = tweet["text"].replace("\n", " ").replace("\r", "").strip()
            text = html.parser.HTMLParser().unescape(text)
            print("[{0}]: {1}".format(i, text), file=stdout)
예제 #13
0
파일: wait.py 프로젝트: adisubagja/smartbot
 def on_command(self, msg, stdin, stdout):
     if len(msg["args"]) >= 2:
         cmd = msg["args"][1]
         if cmd == "in" or cmd == "at":
             try:
                 date = parse_datetime(" ".join(msg["args"][1:]))
             except ValueError:
                 raise smartbot.StopCommand("I don't understand that date.")
             else:
                 duration = (date - datetime.datetime.now()).total_seconds()
                 time.sleep(max(0, duration))
         else:
             raise StopCommand("‘{}’ is not a valid command.".format(cmd))
     else:
         raise StopCommandWithHelp(self)
예제 #14
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)
예제 #15
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)
예제 #16
0
    def on_command(self, msg, stdin, stdout):
        query = " ".join(msg["args"][1:])
        if not query:
            query = stdin.read().strip()

        if query:
            mid = self._search_mid(query)
            if mid:
                topic = self._topic(mid)
                short_text, long_text = self._look_for_text(topic)
                if short_text and long_text:
                    url = sprunge(long_text)
                    print("{} {}".format(short_text, url), file=stdout)
                else:
                    raise StopCommand(
                        "There isn't much information about this.")
            else:
                raise StopCommand("I don't know what you're on about.")
        else:
            raise StopCommandWithHelp(self)
예제 #17
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)
예제 #18
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)
예제 #19
0
 def on_command(self, msg, stdin, stdout):
     if len(msg["args"]) >= 2:
         action = msg["args"][1]
         if "deal".startswith(action):
             page = requests.get("http://store.steampowered.com")
             tree = lxml.html.fromstring(page.text)
             if tree.cssselect(".dailydeal"):
                 url = tree.cssselect(".dailydeal a")[0].get("href")
                 original_price = tree.cssselect(
                     ".dailydeal_content .discount_original_price")[0].text
                 final_price = tree.cssselect(
                     ".dailydeal_content .discount_final_price")[0].text
                 print("{0} - {1} - from {2} to {3}".format(url,
                                                            get_title(url),
                                                            original_price,
                                                            final_price),
                       file=stdout)
             else:
                 raise StopCommand("No daily deal.")
         else:
             raise StopCommand("{} is not a valid action.".format(action))
     else:
         raise StopCommandWithHelp(self)
예제 #20
0
파일: ach.py 프로젝트: adisubagja/smartbot
    def on_command(self, msg, stdin, stdout):
        game = " ".join(msg["args"][1:])
        if not game:
            game = stdin.read().strip()

        if game:
            try:
                game = self.saved_items[int(game)]
            except (IndexError, ValueError):
                pass

            guide = self._guide(game)
            if guide:
                for g in guide:
                    print(g, file=stdout)
            else:
                results = self._search(game)
                if results:
                    for i, r in enumerate(results):
                        print("[{0}]: {1}".format(i, r), file=stdout)
                else:
                    raise StopCommand("Can't find any games.")
        else:
            raise StopCommandWithHelp(self)