Esempio n. 1
0
def get_video_description(vid_id, input):
    j = http.get_json(url % vid_id)
    if j.get('error'):
        return
    j = j['data']
    out = '\x02%s\x02' % j['title']
    if not j.get('duration'):
        return out

    out += ' - length \x02'
    length = j['duration']
    if length / 3600:  # > 1 hour
        out += '%dh ' % (length / 3600)
    if length / 60:
        out += '%dm ' % (length / 60 % 60)
    out += "%ds\x02" % (length % 60)

    if 'rating' in j:
        out += ' - rated \x02%.2f/5.0\x02 (%d)' % (j['rating'],
                j['ratingCount'])

    if 'viewCount' in j:
        out += ' - \x02%s\x02 views' % locale.format('%d',
                                                     j['viewCount'], 1)

    upload_time = time.strptime(j['uploaded'], "%Y-%m-%dT%H:%M:%S.000Z")
    out += ' - \x02%s\x02 on \x02%s\x02' % (j['uploader'],
                time.strftime("%Y.%m.%d", upload_time))

    if 'contentRating' in j:
        out += ' - \x034NSFW\x02'
    if perm.isignored(input):
        out=""
    return out
Esempio n. 2
0
def urlparser(match, say = None, input=None, bot=None):
    inpo = input.params.replace(input.chan+" :","")
    url = match.group().encode('utf-8')
    regexs = re.compile(r"(.+?)(\'|\"|\(|\)|\{|\}|\]|\[|\<|\>)")
    matchs = regexs.search(url)
    if matchs:
        url = matchs.group(0).replace(matchs.group(0)[-1:],"")
    url = urlnorm.normalize(url)
    url2 = urltest(url,match)
    if (not input.conn.conf['autotitle']==False) and (not (perm.isignored(input) or perm.isbot(input))) and not (inpo.startswith(",t") or inpo.startswith(",title") or inpo.startswith(",shor")) and not ("@" in url):
        #print "[debug] URL found"
        if url.startswith("www."):
            url = "http://"+url
        for x in ignored_urls:
            if x in url:
                return
        title = parse(url)
        title = multiwordReplace(title, wordDic)
        try:
            realurl = http.get_url(url)
        except Exception, msg:
            return("(Link) %s" % msg)
        api_user = bot.config.get("api_keys", {}).get("bitly_user", None)
        api_key = bot.config.get("api_keys", {}).get("bitly_api", None)
        if api_key is None:
            return "error: no api key set"
        realurl = isgd(realurl)
        if realurl == url:
            return("(Link) %s" % title)
        else:
            return("(Link) %s <=> %s" % (realurl, title))
Esempio n. 3
0
def auth_track(inp, command=None, input=None, users=None,bot=None, db_auth=None):
    if not auth_userlock.acquire(): raise Exception("Problem acquiring auth_userlock, probable thread crash. Abort.")
    try:
        if command == "NICK":
            if perm.isignored(input):
                userigntrack(input.nick, inp[0], input, bot)
            usernick(input.nick, inp[0], input.conn, bot)
        if command == "QUIT":
            userquit(input.nick, input.conn, bot)
    except:
        raise
    finally:
        auth_userlock.release()
Esempio n. 4
0
File: log.py Progetto: Red-M/frogbot
def log(paraml, input=None, bot=None):
    timestamp = gmtime(timestamp_format)

    fd = get_log_fd(bot.logs_dir, input.server, 'raw')
    fd.write(timestamp + ' ' + input.raw + '\n')

    if input.command == 'QUIT':  # these are temporary fixes until proper
        input.chan = 'quit'      # presence tracking is implemented
    if input.command == 'NICK':
        input.chan = 'nick'

    beau = beautify(input)

    if beau == '':  # don't log this
        return

    if input.chan:
        fd = get_log_fd(bot.logs_dir, input.server, input.chan)
        if input.bot.config["log"]==True and not perm.isignored(input) and input.nick not in input.conn.conf["owner"]:  #if the chan is ignored then dont log it and dont print anything that doesnt apply to the bot
            fd.write(timestamp + ' ' + beau + '\n')
Esempio n. 5
0
def kill(inp, me = None, nick = None, input=None, notice=None):
    ".kill <user> - kill a user"
    inuserhost = input.user+'@'+input.host
    if inp in input.conn.conf["admins"]: 
        return("I am not killing one of my admins!")
    if perm.isignored(input):
        return None
    inp = inp.strip()

    if not re.match("^[A-Za-z0-9_|.-\]\[]*$", inp.lower()):
        notice("Invalid username!")
        return

    if inp == input.conn.nick.lower() or inp == "itself":
        msg = 'kills ' + nick + ' and rakes their corpse (:3)'
    else:
        kill = random.choice(kills)
        kill = re.sub ('<who>', inp, kill)
        msg = re.sub ('<body>', random.choice(body), kill)

    me(msg)
Esempio n. 6
0
def question(inp, chan='', say=None, db=None, input=None, nick="", me=None, bot=None, notice=None):
    "!factoid -- shows what data is associated with word"
    filterhistory = []  # loop detection, maximum recursion depth(s)
    #if "^" in inp:
    #    inp = inp.replace("^",bot.chanseen[input.conn.server][input.chan][0])
    def varreplace(orig, variables):
        for i in variables.keys():
            orig = orig.replace("$" + i, variables[i])
        return orig

    def filters(retrieved, variables, filterhistory):
        orig = retrieved[0]
        setternick = retrieved[1]
        if not orig:
            return ""
        if len(filterhistory) + 1 > 10:
            return "Hit max recursion depth: [" + orig[:30] + "...]"
        if orig in filterhistory:
            return "Going in a circle: [" + orig[:30] + "...]"
        filterhistory.append(orig)
        filtermatch = filter_re.search(orig)
        if filtermatch:
            filtername = filtermatch.group(1).lower()
            filterinp = filtermatch.group(2)
            if filtername == "alias":
                return filters(retrieve(varreplace(filterinp, variables), chan), variables, filterhistory)
            elif filtername == "reply":
                return varreplace(filterinp, variables)
            elif filtername == "action":
                return (varreplace(filterinp, variables), me)
            elif filtername == "notice":
                return (filters([filterinp, setternick], variables, filterhistory), notice)
            elif filtername == "noreply":
                return ""
            elif len(filtername) == 3 and filtername.startswith("no"):
	        if inp.group(0).startswith(filtername[2]):
                    return ""
		else:
		    filterhistory.remove(orig)
		    return filters([filterinp, setternick], variables, filterhistory)
            elif filtername == "pyexec":
                preargs = ""
                for i in variables.keys():
                    preargs += i + "=" + repr(unicode(variables[i]).encode('utf8')) + ";"
                return filters([pyexec.python(preargs + filterinp), setternick], variables, filterhistory)
            elif filtername.startswith("locked"):
		filterhistory.remove(orig)
                return filters([filterinp, setternick], variables, filterhistory)
            cmd = cmdfilter_re.search(filtername)
            if cmd:
                trigger = cmd.group(1).lower()
                cmdfunc, cmdargs = bot.commands[trigger]
                if trigger in ["no", "remember", "forget", "unforget", "python"]:
                    return "I'm sorry, I can't let you do that, dave"
                outputlines = []

                def cmdsay(o):
                    print "cmdsay out:", repr(o)
                    if filter_re.search(o):
                        outputlines.append(o)
                    else:
                        outputlines.append("<reply>" + o)

                def cmdme(o):
                    outputlines.append("<action>" + o)

                newinput = bot.Input(input.conn, input.raw, input.prefix, input.command, input.params,
                    setternick, "user", "host", input.paraml, input.msg)
                newinput.say = cmdsay
                newinput.reply = cmdsay
                newinput.me = cmdme
                newinput.inp = varreplace(filterinp, variables)
                newinput.trigger = trigger
                mutex = bot.dispatch(newinput, "command", cmdfunc, cmdargs, autohelp=False)
                mutex.acquire()
                mutex.release()
                outputlines = [filters([line, setternick], variables, filterhistory) for line in outputlines]
                return outputlines
        else:
            return variables["word"] + " is " + varreplace(orig, variables)

    def retrieve(word, chan):
        ret = db.execute("select data, nick from memory where chan=? and word=lower(?)",
                      (chan, word)).fetchone()
        if ret and not forgotten_re.match(ret[0]):
            return ret
        ret = db.execute("select data, nick from memory where chan=? and word=lower(?)",
                      (defaultchan, word)).fetchone()
        if ret and not forgotten_re.match(ret[0]):
            return ret
        return ["", ""]

    db_init(db)
    whole = False

    groups = inp.groups()
    if len(groups) == 2:
        if groups[0] == input.conn.nick and (not "command_handled" in input or not input.command_handled):
            groups = [groups[1]]
        else:
            return
    def splitgroups(words):
        "returns (mode, word, args, redir, redirto)"
        ret = []
        wordmatch = word_re.search(words)
        if not wordmatch==None:
            words = words[wordmatch.end():]
            ret.append(wordmatch.group(1))
            ret.append(wordmatch.group(2).lower())

            redirect = ''
            redirectto = ''
            redirectmatch = redirect_re.search(words)
            if redirectmatch:
                redirect = redirectmatch.group(1)
                redirectto = redirectmatch.group(2)
                words = words[:redirectmatch.start()]
            ret.append(words.strip())
            ret.append(redirect)
            ret.append(redirectto)
            return ret
        else:
            return ('/', '/', '/', '/', '/') #lets just fill it with stuff so we can exit out if we cant get a word for cases like "? <stuff>"
    (mode, word, args, redir, redirto) = splitgroups(groups[0])
    if ("/" in word) or (word==None):
        return


    def finaloutput(s, redir, redirto, input, special=None):
        if not s:
            return
        if redirto.startswith("#") and (not(perm.isadmin(input))):
            redirto = nick
            s = "I am not sending factoids into channels. I am not that stupid and only bot admins can do this."
        if redir == ">" and not special:
            input.conn.cmd('PRIVMSG', [redirto, s])
        elif redir == "|" and not special:
            input.say(redirto + ": " + s)
        elif redir == "<" and not special:
            input.notice(s)
        elif special:
            special(s)
        else:
            input.say(s)

    def output(data):
        if type(data) == list:
            for i in data:
                output(i)
        elif type(data) == tuple:
            finaloutput(data[0], redir, redirto, input, data[1])  # special for things like /me
        else:
            finaloutput(data, redir, redirto, input)

    variables = {"chan": chan or "",
                 "user": nick or "",
                 "nick": input.conn.nick or "",
                 "target": redirto or "",
                 "inp": args or "",
                 "ioru": args or nick,
                 "word": word or ""}
    variables["inp"] = unicode(variables["inp"])
    variables["ioru"] = unicode(variables["ioru"])
    if "^" in (variables["inp"]):
        variables["inp"]=str(variables["inp"]).replace("^",bot.chanseen[input.conn.name][input.chan][0])
    if "^" in (variables["ioru"]):
        variables["ioru"]=str(variables["ioru"]).replace("^",bot.chanseen[input.conn.name][input.chan][0])
    if mode == "-":   # information
        message = word + " is "
        local = db.execute("select nick from memory where chan=? and word=lower(?)", (chan, word)).fetchone()
        if local:
            message += "locally set by " + local[0]
        default = db.execute("select nick from memory where chan=? and word=lower(?)", (defaultchan, word)).fetchone()
        if local and default:
            message += " and "
        if default:
            message += "globally set by " + default[0]
        if local or default:
            output(message)
    elif mode == "+":  # raw
        local = get_memory(db, chan, word)
        default = get_memory(db, defaultchan, word)
        if local:
              if perm.isignored(input) and (not(perm.isadmin(input))):
                   return None
              else:
                   output("[local] " + local)
        if default:
              if perm.isignored(input) and (not(perm.isadmin(input))):
                   return None
              else:
                   output("[global] " + default)
    else:
         if perm.isignored(input) and (not(perm.isadmin(input))):
              return None
         else:
              output(filters(retrieve(word, chan), variables, filterhistory))
Esempio n. 7
0
def sieve_suite(bot, input, func, kind, args):
    inuserhost = input.user+'@'+input.host
    
    if perm.isignored(input) and not (perm.isvoiced(input)):
        if not (input.paraml[0].startswith("\x01ACTION ")):
            return None
        else:
            return input
    
    if perm.isbot(input):
        if not (input.paraml[0].startswith("\x01ACTION ")):
            return None
        else:
            return input

    if (input.chan in input.conn.conf["ignore"]) and not (perm.isvoiced(input)):
        if not (input.paraml[0].startswith("\x01ACTION ")):
            return None
        else:
            return input
            
    ignored = input.conn.conf['ignore']
    if kind == "command":
        if "^" in input.paraml[1]:
            input.inp = input.inp.replace("^",bot.chanseen[input.conn.name][input.chan][0])
            input.paraml[1] = input.paraml[1].replace("^",bot.chanseen[input.conn.name][input.chan][0])
        if input.trigger in bot.config["disabled_commands"]:
            return None
    
    connitem = input.conn
    for xconn in bot.conns:
        if connitem==bot.conns[xconn]:
            server=bot.conns[xconn].name
    if input.nick in bot.cooldown[str(server)]:
        bot.cooldown[str(server)][input.nick]+=1
        return None
    
    if input.paraml[0].startswith("\x01PING "):
		input.conn.send("NOTICE "+input.nick+" :"+input.inp[1])

    fn = re.match(r'^plugins.(.+).py$', func._filename)
    disabled = bot.config.get('disabled_plugins', [])
    if fn and fn.group(1).lower() in disabled:
        return None
    acl = bot.config.get('acls', {}).get(func.__name__)
    if acl:
        if 'deny-except' in acl:
            allowed_channels = map(unicode.lower, acl['deny-except'])
            if input.chan.lower() not in allowed_channels:
                return None
        if 'allow-except' in acl:
            denied_channels = map(unicode.lower, acl['allow-except'])
            if input.chan.lower() in denied_channels:
                return None

#the extended permissions were moved here.
    if args.get('adminonly', False):
        if not perm.isadmin(input):
            return None
    if args.get('superadminonly', False):
        if not perm.issuperadmin(input):
            return None
    if args.get('owneronly', False):
        if not perm.isowner(input):
            return None
#extended permissions end here.
    return input 
Esempio n. 8
0
def joins(paraml, conn=None, input=None, bot=None):
    repchan = input.conn.conf["reportchan"]
    if not perm.isowner(input) and not perm.isignored(input) and not perm.isbot(input) and input.nick==conn.nick:
        input.conn.send("PRIVMSG "+repchan+" :I have joined "+paraml[-1])
Esempio n. 9
0
def invite(paraml, conn=None, input=None, bot=None):
    repchan = input.conn.conf["reportchan"]
    nickf = munge.munge(0, input, bot, 0, "")
    if not perm.isowner(input) and not perm.isignored(input) and not perm.isbot(input):
        input.conn.send("PRIVMSG "+repchan+" :I have been invited to "+paraml[-1]+" by "+nickf)