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!")
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)
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("'", "'") \ .replace("`", "'") \ .replace(""", "\"") link = story["unescapedUrl"] print("[{0}]: {1} - {2}".format(i, title, link), file=stdout) else: raise StopCommand("No news stories.")
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)
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)
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)
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)
def on_command(self, msg, stdin, stdout): plugin_name = None if len(msg["args"]) >= 2: plugin_name = msg["args"][1] else: plugin_name = stdin.read().strip() if plugin_name: plugin = self.bot.find_plugin(plugin_name) if plugin: print(plugin.on_help(), file=stdout) else: raise StopCommand("{} does not exist.".format(plugin_name)) else: names = itertools.chain.from_iterable( plugin.names for plugin in self.bot.plugins) plugin_names = ", ".join(sorted(names)) print("Help about:", plugin_names, file=stdout)
def _get_hash_func(algorithm, action): if algorithm == "base64" or algorithm == "b64": if "encode".startswith(action): return base64.b64encode elif "decode".startswith(action): return base64.b64decode elif algorithm == "base32" or algorithm == "b32": if "encode".startswith(action): return base64.b32encode elif "decode".startswith(action): return base64.b32decode elif algorithm == "base16" or algorithm == "b16": if "encode".startswith(action): return base64.b16encode elif "decode".startswith(action): return base64.b16decode raise StopCommand("{} is not a valid algorithm.".format(algorithm))
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)
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)
def on_command(self, msg, stdin, stdout): url = "https://www.humblebundle.com/" if "weekly" in msg["args"] or "weekly" in stdin.read().strip(): url = "https://www.humblebundle.com/weekly" page = requests.get(url) tree = lxml.html.fromstring(page.text) try: title = tree.cssselect("title")[0].text_content().strip() clock = tree \ .cssselect("#heading-time-remaining .mini-digit-holder")[0] c0 = clock.cssselect(".c0 .heading-num")[0].text_content() c1 = clock.cssselect(".c1 .heading-num")[0].text_content() c2 = clock.cssselect(".c2 .heading-num")[0].text_content() c3 = clock.cssselect(".c3 .heading-num")[0].text_content() c4 = clock.cssselect(".c4 .heading-num")[0].text_content() c5 = clock.cssselect(".c5 .heading-num")[0].text_content() c6 = clock.cssselect(".c6 .heading-num")[0].text_content() c7 = clock.cssselect(".c7 .heading-num")[0].text_content() print("{0} - {1}{2}:{3}{4}:{5}{6}:{7}{8} left".format( title, c0, c1, c2, c3, c4, c5, c6, c7), file=stdout) except IndexError: raise StopCommand("No sale.")
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)
def on_command(self, msg, stdin, stdout): contents = stdin.read().strip() if contents: print(sprunge(contents), file=stdout) else: raise StopCommand("Expected input on stdin.")