Пример #1
0
def ddgsearch(query, prefix=""):
    try:
        res = search(to_utf8(query))
    except Exception as e:
        print e
        return u"Network Error"

    try:
        v = json.loads(res)
        typ = v["Type"]
        if typ == "D":
            topics = set()
            collect_topics(v, "RelatedTopics", topics)
            result = u"Did you mean %s" % orstr(sorted(topics))
            result = plugins.shorten(prefix + result, 350) + u"?"
        elif typ == "A" or typ == "E":
            result = v["AbstractText"]
            result = plugins.shorten(prefix + result, 350)
        else:
            if v["Answer"]:
                return plugins.shorten(prefix + v["Answer"], 350)

            print res
            result = prefix + u"I don't know what you mean."
    except Exception as e:
        print e
        return prefix + u"Parse Error"

    return result
Пример #2
0
    def command(self, connection, event, extra, dbconn):
        url = "http://api.urbandictionary.com/v0/define?%s"

        index = (self.pargs.nr or 1) - 1
        page = index / 10 + 1
        index %= 10
        term = " ".join(self.pargs.search_term)

        data = {"page": page, "term": plugins.to_utf8(term)}

        prefix = "\x0303[Urban Dictionary]\x03 "
        req = urllib2.Request(url % urllib.urlencode(data))

        try:
            all_entries = json.load(urllib2.urlopen(req))["list"]
            count = 10 * (page - 1) + len(all_entries)
            entry = all_entries[index]

            txt = "%s (%d/%d)\n" % (term, index + 1, count)
            definition = "\n".join(entry["definition"].splitlines())
            definition = re.sub(r'\[([^\[]*)\]', "\x02\\1\x0f", definition)
            txt += plugins.shorten(definition, 300)

            if entry.has_key("example"):
                example = "\n".join(entry["example"].splitlines())
                example = re.sub(r'\[([^\[]*)\]', "\x02\\1\x0f", example)
                txt += "\n\x02Example:\x0f " + plugins.shorten(example, 300)
        except Exception as e:
            print e
            if term == "dloser":
                return prefix + "The unstabliest D-System ever!"
            return prefix + "Definition not available."

        return prefix + txt
Пример #3
0
    def command(self, connection, event, extra, dbconn):
        txt = "\x0303[Wolfram|Alpha]\x03 "

        try:
            res = None
            misc = []
            for p in self.client.query(" ".join(map(to_utf8,
                                                    self.pargs.query))).pods:
                if p.id == "Input":
                    inp = " | ".join(p.text.splitlines())
                elif p.id == "Result" and p.text:
                    res = self.format_table(p.text)
                elif p.title and p.text:
                    misc.append("%s\n%s" %
                                (p.title, self.format_table(p.text)))

            txt += inp + "\n"

            if res:
                txt += res + "\n"
            elif misc:
                txt += "\n".join(misc)
            else:
                raise NameError
        except (NameError, AttributeError):
            txt += "No results."
        except Exception as e:
            txt = "Error: %s" % e

        return plugins.shorten(txt, 450)
Пример #4
0
    def execute(self):
        if not self.args:
            return

        txt = "\x0303[Wolfram|Alpha]\x03 "

        try:
            res = None
            misc = []
            for p in self.client.query(self.args).pods:
                if p.id == "Input":
                    inp = " | ".join(p.text.splitlines())
                elif p.id == "Result" and p.text:
                    res = self.format_table(p.text)
                elif p.title and p.text:
                    misc.append("%s\n%s" % (p.title, self.format_table(p.text)))

            txt += inp + "\n"

            if res:
                txt += res + "\n"
            elif misc:
                txt += "\n".join(misc)
            else:
                raise NameError
        except NameError:
            txt += "No results."
        except Exception as e:
            txt = "Error: %s" % e

        return plugins.shorten(txt, 450)
Пример #5
0
    def command(self, connection, event, extra, dbconn):
        data = " ".join(self.pargs.data).lower()

        sock = socket()
        sock.connect(("wc3.wechall.net", 61221))
        data = data.replace("qd",
                            "05 00 FD 00 05 00 FD 03 FD FE FD 02 FD FE FD FE")
        #data = filter(lambda x: x in string.hexdigits, data)
        data = data.replace(" ", "")
        ret = "hmpf"
        try:
            data = data.decode("hex")
            if data[-1] != "\xff":
                data += "\xff"
            sock.send(data)
            data = ""
            while True:
                time.sleep(0.01)
                d = sock.recv(1024)
                if not d:
                    break
                data += d
            for c in data:
                if not c in string.printable:
                    ret = " ".join(x.encode("hex") for x in data)
                    break
            if ret == "hmpf":
                ret = data
        except Exception as e:
            return unicode(e)
        finally:
            sock.close()

        return plugins.shorten(ret, 450)
Пример #6
0
    def execute(self):
        try:
            pargs = self.parser.parse_args(shlex.split(plugins.to_utf8(self.args) or ""))
            if self.parser.help_requested:
                return self.parser.format_help().strip()
        except plugins.ArgumentParserError as e:
            return "error: %s" % str(e)
        except (SystemExit, NameError, ValueError):
            return self.help(self.cmd)

        url = "http://api.urbandictionary.com/v0/define?%s"

        index = (pargs.nr or 1) - 1
        page = index / 10 + 1
        index %= 10
        term = " ".join(pargs.search_term)

        data = {
            "page" : page,
            "term" : term
        }

        prefix = "\x0303[Urban Dictionary]\x03 "
        req = urllib2.Request(url % urllib.urlencode(data))

        try:
            all_entries = json.load(urllib2.urlopen(req))["list"]
            count = 10 * (page - 1) + len(all_entries)
            entry = all_entries[index]

            txt = "%s (%d/%d)\n" % (term, index + 1, count)
            definition = "\n".join(entry["definition"].splitlines())
            txt += plugins.shorten(definition, 300)

            if entry.has_key("example"):
                example = "\n".join(entry["example"].splitlines())
                txt += "\n\x02Example:\x0f " + plugins.shorten(example, 300)
        except:
            return prefix + "Definition not available."

        return prefix + txt
Пример #7
0
    def execute(self, connection, event, extra, dbconn):
        try:
            pargs = self.parser.parse_args(extra["args"])
            if self.parser.help_requested:
                return self.parser.format_help().strip()
            query = " ".join(pargs.query)
        except Exception as e:
            return u"Error: %s" % unicode(e)

        txt = u"\x0303[DuckDuckGo]\x03 "

        try:
            res = self.search(to_utf8(query))
        except Exception as e:
            print e
            return txt + u"Network Error"

        try:
            v = json.loads(res)
            typ = v["Type"]
            if typ == "D":
                topics = set()
                self.collect_topics(v, "RelatedTopics", topics)
                result = u"Did you mean %s" % self.orstr(sorted(topics))
                result = plugins.shorten(txt + result, 350) + u"?"
            elif typ == "A":
                result = v["AbstractText"]
                result = plugins.shorten(txt + result, 350)
            else:
                print res
                result = txt + u"I don't know what you mean."
        except Exception as e:
            print e
            return txt + u"Parse Error"

        return result
Пример #8
0
    def wolfram_handler(self, what):
        if not self.client:
            return

        for p in self.client.query(what).pods:
            if p.id == "Result" and p.text:
                txt = " ".join(p.text.splitlines())
                return plugins.shorten("%s: %s" % (event.source.nick, txt),
                                       350)

        for p in self.client.query(what).pods:
            if p.id == "Misc" and p.text:
                txt = " ".join(p.text.splitlines())
                print txt

        raise Exception("hm")
Пример #9
0
    def execute(self, connection, event, extra, dbconn):
        try:
            pargs = self.parser.parse_args(extra["args"])
            if self.parser.help_requested:
                return self.parser.format_help().strip()
        except Exception as e:
            return u"Error: %s" % str(e)

        data = {
            "action": "query",
            "list": "search",
            "srsearch": plugins.to_utf8(u" ".join(pargs.term)),
            "srlimit": 1,
            "srprop": "",
            "format": "json",
            "continue": ""
        }

        prefix = "\x0303[Wikipedia]\x03 "
        req = urllib2.Request(url % urllib.urlencode(data))

        try:
            title = json.load(
                urllib2.urlopen(req))["query"]["search"][0]["title"]
        except:
            return prefix + "Search didn't find anything."

        pageurl = "https://en.wikipedia.org/wiki/%s" % wikify(title)

        tree = lxml.html.parse(urllib2.urlopen(pageurl))
        title = get_text(tree, "//h1[@id='firstHeading']")
        content = get_text(tree, "//div[@id='mw-content-text']/div/p")

        if not title or not content:
            return prefix + "Something went wrong."

        if tree.xpath(
                "//div[@id='mw-content-text']//table[@id='disambigbox']"):
            content += " " + ", ".join(
                tree.xpath("//div[@id='mw-content-text']/ul/li//a[1]/@title"))

        txt = "%s (%s)\n%s" % (title, pageurl, plugins.shorten(content, 300))
        return prefix + txt
Пример #10
0
    def execute(self, connection, event, extra, dbconn):
        match = None
        try:
            match = self.regex.match(extra["msg"])
        except:
            pass

        if match is None:
            return

        search = match.group(1)
        replace = match.group(2)

        try:
            user = match.group(4).strip()
        except:
            user = ""

        if user == "":
            user = event.source.nick

        try:
            regex = re.compile(search, re.I)
        except:
            return

        c = dbconn.execute(
            "select message from Messages where server=? and channel=? and nick=? order by ts desc limit 2",
            (connection.name, event.target, user))
        res = c.fetchone()

        if user == event.source.nick:
            res = c.fetchone()

        if res is None:
            return

        msg = res[0]
        msg = regex.sub(replace, msg)
        msg = plugins.myfilter(msg)
        msg = plugins.shorten(msg, 450)
        return u"%s: %s" % (user, msg)
Пример #11
0
    def execute(self, connection, event, extra, dbconn):
        try:
            pargs = self.parser.parse_args(extra["args"])
            if self.parser.help_requested:
                return self.parser.format_help().strip()
        except Exception as e:
            return u"Error: %s" % unicode(e)

        sock = socket()
        sock.connect(("wc3.wechall.net", 61221))
        data = "".join(pargs.data[0]).lower()
        data = data.replace("qd", "05 00 FD 00 05 00 FD 03 FD FE FD 02 FD FE FD FE")
        #data = filter(lambda x: x in string.hexdigits, data)
        data = data.replace(" ", "")
        ret = "hmpf"
        try:
            data = data.decode("hex")
            if data[-1] != "\xff":
                data += "\xff"
            sock.send(data)
            data = ""
            while True:
                time.sleep(0.01)
                d = sock.recv(1024)
                if not d:
                    break
                data += d
            for c in data:
                if not c in string.printable:
                    ret = " ".join(x.encode("hex") for x in data)
                    break
            if ret == "hmpf":
                ret = data
        except Exception as e:
            return unicode(e)
        finally:
            sock.close()

        return plugins.shorten(ret, 450)
Пример #12
0
    def execute(self, connection, event, extra, dbconn):
        try:
            pargs = self.parser.parse_args(extra["args"])
            if self.parser.help_requested:
                return self.parser.format_help().strip()
        except Exception as e:
            return u"Error: %s" % str(e)

        txt = "\x0303[Wolfram|Alpha]\x03 "

        try:
            res = None
            misc = []
            for p in self.client.query(" ".join(pargs.query)).pods:
                if p.id == "Input":
                    inp = " | ".join(p.text.splitlines())
                elif p.id == "Result" and p.text:
                    res = self.format_table(p.text)
                elif p.title and p.text:
                    misc.append("%s\n%s" %
                                (p.title, self.format_table(p.text)))

            txt += inp + "\n"

            if res:
                txt += res + "\n"
            elif misc:
                txt += "\n".join(misc)
            else:
                raise NameError
        except (NameError, AttributeError):
            txt += "No results."
        except Exception as e:
            txt = "Error: %s" % e

        return plugins.shorten(txt, 450)
Пример #13
0
    def execute(self):
        if not self.args:
            return

        data = {
            "action" : "query",
            "list" : "search",
            "srsearch" : plugins.to_utf8(self.args),
            "srlimit" : 1,
            "srprop" : "",
            "format" : "json",
            "continue" : ""
        }

        prefix = "\x0303[Wikipedia]\x03 "
        req = urllib2.Request(url % urllib.urlencode(data))

        try:
            title = json.load(urllib2.urlopen(req))["query"]["search"][0]["title"]
        except:
            return prefix + "Search didn't find anything."

        pageurl = "https://en.wikipedia.org/wiki/%s" % wikify(title)

        tree = lxml.html.parse(urllib2.urlopen(pageurl))
        title = get_text(tree, "//h1[@id='firstHeading']")
        content = get_text(tree, "//div[@id='mw-content-text']/p")

        if not title or not content:
            return prefix + "Something went wrong."

        if tree.xpath("//div[@id='mw-content-text']//table[@id='disambigbox']"):
            content += " " + ", ".join(tree.xpath("//div[@id='mw-content-text']/ul/li//a[1]/@title"))

        txt = "%s (%s)\n%s" % (title, pageurl, plugins.shorten(content, 300))
        return prefix + txt
Пример #14
0
    def execute(self, connection, event, extra, dbconn):
        botname = self.tehbot.settings.value("botname", connection)
        decide_regex = [
            re.compile(
                r'''^(?:ok(?:ay)?|hey)\s+%s,?\s*(?:is|are|has|was|were)\s+\w[\s\w]*\?'''
                % botname, re.I),
        ]
        regex = [
            re.compile(
                r'''^(?:ok(?:ay)?|hey)\s+%s,?\s*(?P<what>.*?)\s*\??$''' %
                botname, re.I),
        ]
        solved_regex = [
            re.compile(
                r'''^(?:ok(?:ay)?|hey)\s+%s,?\s*has\s+(?P<who>\w+)\s+solved\s+(?P<chall>\w[\s\w]*?|"[^"]+"|'[^']+')(?:\s+on\s+(?P<site>\w[\s\w]*?|"[^"]+"|'[^']+'))?\s*\??$'''
                % botname, re.I),
            re.compile(
                r'''^(?:ok(?:ay)?|hey)\s+%s,?\s*did\s+(?P<who>\w+)\s+solve\s+(?P<chall>\w[\s\w]*?|"[^"]+"|'[^']+')(?:\s+on\s+(?P<site>\w[\s\w]*?|"[^"]+"|'[^']+'))?\s*\??$'''
                % botname, re.I)
        ]

        for r in solved_regex:
            match = r.search(extra["msg"])
            if match is not None:
                user = match.group(1)
                chall = match.group(2)
                site = match.group(3)

                plugin = self.tehbot.cmd_handlers["solvers"]
                chall = " ".join(plugins.mysplit(chall))
                args = '-u %s %s' % (user, pipes.quote(chall))
                if site is not None:
                    site = " ".join(plugins.mysplit(site))
                    args = args + " -s %s" % pipes.quote(site)
                plugin.handle(connection, event, {"args": args}, dbconn)
                return

        if not self.ai_enabled:
            return

        for r in decide_regex:
            match = r.search(extra["msg"])
            if match is not None:
                return random.choice(AiHandler.decision_answers())

        for r in regex:
            match = r.search(extra["msg"])
            if match is not None:
                what = match.group(1)

                try:
                    for p in self.client.query(what).pods:
                        if p.id == "Result" and p.text:
                            txt = " ".join(p.text.splitlines())
                            return plugins.shorten(
                                "%s: %s" % (event.source.nick, txt), 350)

                    for p in self.client.query(what).pods:
                        if p.id == "Misc" and p.text:
                            txt = " ".join(p.text.splitlines())
                            print txt

                    raise Exception("hm")
                except:
                    return [("me", "shrugs")]