Пример #1
0
def cmd(send, msg, args):
    """Gets info on a CVE id from MITRE's CVE database
    Syntax: !cve <cveid>
    """
    elements = msg.split('-')
    if len(elements) > 3 or len(elements) < 2:
        send("Invalid CVE format")
        return
    # If there are three fields, ignore the first (we don't actually need to send CVE-
    if len(elements) == 3:
        if not elements[0].upper() == 'CVE':
            send("Invalid CVE format")
            return
        elements.pop(0)
    # The first digit field should be exactly four digits long, the second is 4+
    if not re.search("^[\d]{4}$", elements[0]) or not re.search(
            "^[\d]{4,}$", elements[1]):
        send("Invalid CVE format")
        return
    search = "%s-%s" % (elements[0], elements[1])
    url = 'http://cve.mitre.org/cgi-bin/cvename.cgi?name=%s' % search
    html = fromstring(get(url).text)
    title = html.find(".//title").text.splitlines()[2]
    if title.startswith('ERROR'):
        output = 'Invalid CVE Number'
    else:
        key = args['config']['api']['googleapikey']
        output = "%s -- %s" % (title, get_short(url, key))
    send(output)
Пример #2
0
def handle(send, msg, args):
    """ Get titles for urls.

    | Generate a short url.
    | Get the page title.
    """
    worker = args['handler'].workers
    result = worker.run_pool(get_urls, [msg])
    try:
        urls = result.get(5)
    except multiprocessing.TimeoutError:
        worker.restart_pool()
        send('Url regex timed out.')
        return
    for url in urls:
        # Prevent botloops
        if args['db'].query(Urls).filter(Urls.url == url, Urls.time > time.time() - 10).count():
            return
        title = urlutils.get_title(url)
        key = args['config']['api']['googleapikey']
        short = urlutils.get_short(url, key)
        last = args['db'].query(Urls).filter(Urls.url == url).order_by(Urls.time.desc()).first()
        if args['config']['feature'].getboolean('linkread'):
            # 604800 is the number of seconds in a week.
            if last and (time.time() - last.time) < 604800:
                lasttime = time.strftime('at %H:%M:%S on %Y-%m-%d', time.localtime(last.time))
                send("Url %s previously posted %s by %s -- %s" % (short, lasttime, last.nick, title))
            else:
                send('** %s - %s' % (title, short))
        args['db'].add(Urls(url=url, title=title, nick=args['nick'], time=time.time()))
Пример #3
0
def cmd(send, msg, args):
    """Gets info on a CVE id from MITRE's CVE database
    Syntax: {command} <cveid>
    """
    elements = msg.split('-')
    if len(elements) > 3 or len(elements) < 2:
        send("Invalid CVE format")
        return
    # If there are three fields, ignore the first (we don't actually need to send CVE-
    if len(elements) == 3:
        if not elements[0].upper() == 'CVE':
            send("Invalid CVE format")
            return
        elements.pop(0)
    # The first digit field should be exactly four digits long, the second is 4+
    if not re.search(r"^[\d]{4}$", elements[0]) or not re.search(r"^[\d]{4,}$", elements[1]):
        send("Invalid CVE format")
        return
    search = "%s-%s" % (elements[0], elements[1])
    url = 'http://cve.mitre.org/cgi-bin/cvename.cgi?name=%s' % search
    html = fromstring(get(url).text)
    title = html.find(".//title").text.splitlines()[2]
    if title.startswith('ERROR'):
        output = 'Invalid CVE Number'
    else:
        key = args['config']['api']['googleapikey']
        output = "%s -- %s" % (title, get_short(url, key))
    send(output)
Пример #4
0
def handle(send, msg, args):
    """ Get titles for urls.

    | Generate a short url.
    | Get the page title.
    """

    # FIXME: don't hardcode.
    if "http://git.io" in msg:
        return
    #FIXME: also, don't hardcode.
    if "polr" in msg and "http" in msg:
        return
    # crazy regex to match urls
    match = re.search(r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.]
                          [a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()
                          <>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*
                          \)|[^\s`!()\[\]{};:'\".,<>?....]))""", msg)
    if match:
        url = match.group(1)
        if "!" + url in msg:
            return
        title = get_title(url)
        short = get_short(url, polr.api(apikey =  args['config']['api']['polrkey']))
        if args['config']['feature'].getboolean('linkread'):
           send('** %s - %s' % (title, short))
Пример #5
0
def handle(send, msg, args):
    """ Get titles for urls.

    | Generate a short url.
    | Get the page title.
    """

    # FIXME: don't hardcode.
    if "http://git.io" in msg:
        return
    # crazy regex to match urls
    match = re.search(
        r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.]
                          [a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()
                          <>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*
                          \)|[^\s`!()\[\]{};:'\".,<>?....]))""", msg)
    if match:
        url = match.group(1)
        title = get_title(url)
        short = get_short(url)
        last = args['db'].query(Urls).filter(Urls.url == url).order_by(
            Urls.time.desc()).first()
        if args['config']['feature'].getboolean('linkread'):
            if last:
                lasttime = strftime('at %H:%M:%S on %Y-%m-%d',
                                    localtime(last.time))
                send("Url %s previously posted %s by %s -- %s" %
                     (short, lasttime, last.nick, title))
            else:
                send('** %s - %s' % (title, short))
        args['db'].add(
            Urls(url=url, title=title, nick=args['nick'], time=time()))
Пример #6
0
def handle(send, msg, args):
    """ Get titles for urls.

    | Generate a short url.
    | Get the page title.
    """
    worker = args['handler'].workers
    result = worker.run_pool(get_urls, [msg])
    try:
        urls = result.get(5)
    except multiprocessing.TimeoutError:
        worker.restart_pool()
        send('Url regex timed out.')
        return
    for url in urls:
        # Prevent botloops
        if args['db'].query(Urls).filter(Urls.url == url,
                                         Urls.time > time.time() - 10).count():
            return
        title = urlutils.get_title(url)
        key = args['config']['api']['googleapikey']
        short = urlutils.get_short(url, key)
        last = args['db'].query(Urls).filter(Urls.url == url).order_by(
            Urls.time.desc()).first()
        if args['config']['feature'].getboolean('linkread'):
            # 604800 is the number of seconds in a week.
            if last and (time.time() - last.time) < 604800:
                lasttime = time.strftime('at %H:%M:%S on %Y-%m-%d',
                                         time.localtime(last.time))
                send("Url %s previously posted %s by %s -- %s" %
                     (short, lasttime, last.nick, title))
            else:
                send('** %s - %s' % (title, short))
        args['db'].add(
            Urls(url=url, title=title, nick=args['nick'], time=time.time()))
Пример #7
0
def handle(send, msg, args):
    """ Get titles for urls.

    | Generate a short url.
    | Get the page title.
    """

    #FIXME: don't hardcode.
    if "http://git.io" in msg:
        return
    # crazy regex to match urls
    match = re.search(r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.]
                          [a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()
                          <>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*
                          \)|[^\s`!()\[\]{};:'\".,<>?....]))""", msg)
    if match:
        url = match.group(1)
        title = get_title(url)
        short = get_short(url)
        last = args['db'].query(Urls).filter(Urls.url == url).order_by(Urls.time.desc()).first()
        if args['config']['feature'].getboolean('linkread'):
            if last:
                lasttime = strftime('at %H:%M:%S on %Y-%m-%d', localtime(last.time))
                send("Url %s previously posted %s by %s -- %s" % (short, lasttime, last.nick, title))
            else:
                send('** %s - %s' % (title, short))
        args['db'].add(Urls(url=url, title=title, nick=args['nick'], time=time()))
Пример #8
0
def cmd(send, msg, args):
    """Gets a random movie.
    Syntax: !movie
    """

    req = get('http://www.imdb.com/random/title')
    html = fromstring(req.text)
    name = html.find('head/title').text.split('-')[0].strip()
    send("%s -- %s" % (name, get_short(req.url)))
Пример #9
0
def cmd(send, msg, args):
    """Gets a random movie.
    Syntax: {command}
    """

    req = get('http://www.imdb.com/random/title')
    html = fromstring(req.text)
    name = html.find('head/title').text.split('-')[0].strip()
    key = args['config']['api']['googleapikey']
    send("%s -- %s" % (name, get_short(req.url, key)))
Пример #10
0
def cmd(send, msg, args):
    """Gets a random movie.
    Syntax: !movie
    """

    req = get('http://www.imdb.com/random/title')
    html = fromstring(req.text)
    name = html.find('head/title').text.split('-')[0].strip()
    key = args['config']['api']['googleapikey']
    send("%s -- %s" % (name, get_short(req.url, key)))
Пример #11
0
def cmd(send, msg, args):
    """Explain things.
    Syntax: !explain <text>
    """
    if not msg:
        send("Explain What?")
        return
    msg = msg.replace(' ', '+')
    msg = 'http://lmgtfy.com/?q=%s' % msg
    send(get_short(msg))
Пример #12
0
def cmd(send, msg, args):
    """Explain things.
    Syntax: {command} <text>
    """
    if not msg:
        send("Explain What?")
        return
    msg = msg.replace(' ', '+')
    msg = 'http://lmgtfy.com/?q=%s' % msg
    key = args['config']['api']['googleapikey']
    send(get_short(msg, key))
Пример #13
0
def cmd(send, msg, args):
    """Gets a random Reddit post.
    Syntax: {command} <subreddit>
    """
    if args['name'] == 'srepetsk':
        msg = 'nottheonion'
    if msg and not check_exists(msg):
        send("Non-existant subreddit.")
        return
    subreddit = '/r/%s' % msg if msg else ''
    url = get('http://reddit.com%s/random' % subreddit, headers={'User-Agent': 'CslBot/1.0'}).url
    send('** %s - %s' % (get_title(url), get_short(url)))
Пример #14
0
def cmd(send, msg, args):
    """Gets a random Reddit post.
    Syntax: !reddit <subreddit>
    """
    if args["name"] == "srepetsk":
        msg = "nottheonion"
    if msg and not check_exists(msg):
        send("Non-existant subreddit.")
        return
    subreddit = "/r/%s" % msg if msg else ""
    url = get("http://reddit.com%s/random" % subreddit, headers={"User-Agent": "CslBot/1.0"}).url
    send("** %s - %s" % (get_title(url), get_short(url)))
Пример #15
0
def cmd(send, msg, args):
    """Gets a random Reddit post.
    Syntax: !reddit <subreddit>
    """
    if args['name'] == 'srepetsk':
        msg = 'nottheonion'
    if msg and not check_exists(msg):
        send("Non-existant subreddit.")
        return
    subreddit = '/r/%s' % msg if msg else ''
    urlstr = 'http://reddit.com%s/random?%s' % (subreddit, time.time())
    url = get(urlstr, headers={'User-Agent': 'CslBot/1.0'}).url
    key = args['config']['api']['googleapikey']
    send('** %s - %s' % (get_title(url), get_short(url, key)))
Пример #16
0
def handle(send, msg, args):
    match = re.search(r'(?:^|\s)/r/([\w|^/]*)\b', msg)
    if not match:
        return
    subreddit = match.group(1)
    if not check_exists(subreddit):
        return
    data = get('http://reddit.com/r/%s/about.json' % subreddit, headers={'User-Agent': 'CslBot/1.0'}).json()['data']
    output = ''
    if data['public_description']:
        for line in data['public_description'].splitlines():
            output += line + " "
    elif data['description']:
        output += data['description'].splitlines()[0]
    else:
        output += data['display_name']
    output = "%s -- %s" % (output.strip(), get_short('http://reddit.com/r/%s' % (subreddit)))
    send(output)
Пример #17
0
def handle(send, msg, args):
    match = re.search(r'(?:^|\s)/r/([\w|^/]*)\b', msg)
    if not match:
        return
    subreddit = match.group(1)
    if not check_exists(subreddit):
        return
    data = get('http://reddit.com/r/%s/about.json' % subreddit, headers={'User-Agent': 'CslBot/1.0'}).json()['data']
    output = ''
    if data['public_description']:
        for line in data['public_description'].splitlines():
            output += line + " "
    elif data['description']:
        output += data['description'].splitlines()[0]
    else:
        output += data['display_name']
    output = output.strip()
    if len(output) > 256:
        output = output[:253] + "..."
    output = "%s -- %s" % (output, get_short('http://reddit.com/r/%s' % (subreddit)))
    send(output)
Пример #18
0
def cmd(send, msg, args):
    """Queries WolframAlpha.
    Syntax: !wolf <expression>
    """
    if not msg:
        send("Evaluate what?")
        return
    params = {'format': 'plaintext', 'reinterpret': 'true', 'input': msg, 'appid': args['config']['api']['wolframapikey']}
    xml = get('http://api.wolframalpha.com/v2/query', params=params)
    xml = etree.fromstring(xml.text.encode())
    output = xml.findall('./pod')
    url = get_short("http://www.wolframalpha.com/input/?i=%s" % msg)
    text = "No output found."
    for x in output:
        if 'primary' in x.keys():
            text = x.find('./subpod/plaintext').text
    if text is None:
        send("No Output parsable")
    else:
        for t in text.splitlines():
            send(t)
    send("See %s for more info" % url)
Пример #19
0
def cmd(send, msg, args):
    """Returns the first wikipedia result for the argument.
    Syntax: {command} <term>
    """
    if not msg:
        send("Need a article.")
        return
    #setting up values
    wiki_list = args['config']['wiki']['list'].split(", ")
    api_url = args['config']['wiki']['api'].split(", ")
    names = args['config']['wiki']['names'].split(", ")
    if not msg.split(" ")[0] in wiki_list:
        msg = args['config']['wiki']['default'] + " " + msg
    msg = msg.split(" ", maxsplit=1)
    wiki_num = wiki_list.index(msg[0])  # check if the article exits, or find the closest redirect.
    article = find_article(wiki_num, api_url, wiki_list, msg, names)
    state = article[0]
    if state == "none":
        send(str(article[1]))
        return
    else:
        article = article[1]  # okay it exists. now let's find out what's really in it
    blurb = get_blurb(wiki_num, api_url, wiki_list, article)
    if blurb == "nothing":
        send("%s isn't important enough to have a %s article." % (titlecase(msg[1]), names[wiki_num]))
        return
    if blurb.startswith("Coordinates"):  # fixes issues with articles with extra stuff (i.e. location)
        send(blurb)
        blurb = blurb.split("\n", maxsplit=1)
        send(str(blurb))
    try:
        blurb = blurb.split("'''", maxsplit=1)[1].replace("\n", " ").replace("'''", "")
    except IndexError:
        blurb = blurb.replace("\n", " ")
    if len(blurb) > 256:
        blurb = blurb[:253] + "..."
    send("Info on %s from %s: %s" % (titlecase(article), names[wiki_num], blurb))
    send(get_short(args['config']['wiki']['article_url'].split(", ")[wiki_num] + article.replace(" ", "_")))
Пример #20
0
def cmd(send, msg, args):
    """Queries WolframAlpha.
    Syntax: {command} <expression>
    """
    if not msg:
        send("Evaluate what?")
        return
    params = {'format': 'plaintext', 'reinterpret': 'true', 'input': msg, 'appid': args['config']['api']['wolframapikey']}
    xml = get('http://api.wolframalpha.com/v2/query', params=params)
    xml = etree.fromstring(xml.text.encode())
    output = xml.findall('./pod')
    key = args['config']['api']['googleapikey']
    url = get_short("http://www.wolframalpha.com/input/?i=%s" % msg, key)
    text = "No output found."
    for x in output:
        if 'primary' in x.keys():
            text = x.find('./subpod/plaintext').text
    if text is None:
        send("No Output parsable")
    else:
        for t in text.splitlines():
            send(t)
    send("See %s for more info" % url)
Пример #21
0
def random_post(subreddit, apikey):
    """ Gets a random post from a subreddit and returns a title and shortlink to it """
    urlstr = 'http://reddit.com%s/random?%s' % ('/r/' + subreddit, time.time())
    url = get(urlstr, headers={'User-Agent': 'CslBot/1.0'}).url
    return '** %s - %s' % (get_title(url), get_short(url, apikey))
Пример #22
0
def random_post(subreddit, apikey):
    """ Gets a random post from a subreddit and returns a title and shortlink to it """
    urlstr = 'http://reddit.com%s/random?%s' % ('/r/' + subreddit, time.time())
    url = get(urlstr, headers={'User-Agent': 'CslBot/1.0'}).url
    return '** %s - %s' % (get_title(url), get_short(url, apikey))