Ejemplo n.º 1
0
    def modprobe(self, bot, args): #{{{
        '''modprobe <module>\nLoads module.\nSee also: load, rmmod, lsmod'''

        if len(args) != 1: return

        try:
            file, pathname, description = imp.find_module("modules/" + args[0])
            name = "modules/" + args[0]
        except:
            error = _('MODULE: %s not found') % args[0]
            logging.error(error)
            return error

        try:
            method = imp.load_module(name, file, pathname, description).info
        except:
            error = _('MODULE: can\'t load %s') % args[0]
            logging.error(error)
            return error
        else:
            info = method(bot)
            if info[0] == '':
                self.plaintext_dispatchers[args[0]] = info[1:]
            else:
                for command in info[0]:
                    self.commands[command] = info[1:]

        info = _('MODULE: %s loaded') % args[0]
        logging.info(info)
        return info
Ejemplo n.º 2
0
def main(bot, args):
	'''формат: rb <N> [M]
Удалить сообщение #N, либо с N по M.'''
	if len(args) < 1 or len(args) > 2:
		return
	try:
		rollback_to = int(args[0])
		if len(args) == 2:
			rollback_from = rollback_to
			rollback_to = int(args[1])
		else:
			rollback_from = rollback_to
	except:
		return

	if rollback_from < 1 or rollback_to > 10 or rollback_to < rollback_from:
		return
	
        soup = BeautifulSoup(open(bot.settings["ans_file"], "r"))
	posts = soup.findAll('p')
	if rollback_to > len(posts):
		return _("some of those posts don't exist.")
	for i in xrange(rollback_from - 1, rollback_to):
		posts[i].extract()

	f = open(bot.settings["ans_file"], "w")
	f.write(soup.prettify())
	f.close()
        
        return _("done.")
Ejemplo n.º 3
0
def main(bot, args):
	'''Ответить слушателю. Параметры: <user_id> <message>
Если в качестве user_id указать восклицательный знак, сообщение будет выглядеть как объявление.'''
	syl = { '0' : 'be', '1' : 'sa', '2' : 'ko', '3' : 'pa', '4' : 're', '5' : 'du', '6' : 'ma', '7' : 'ne', '8' : 'wa', '9' : 'si', 'a' : 'to', 'b' : 'za', 'c' : 'mi', 'd' : 'ka', 'e' : 'ga', 'f' : 'no' }
	salt = bot.settings["ans_salt"]
	message_limit = 250
	userpost = ""
	if len(args) < 2:
		return
	blacklisting = False
	if args[0] != "!":
		if args[0] == "?":
			blacklisting = True
			del args[0]
		if len(args[0]) != 12:
			return _("incorrect name entered, should be 12 symbols.")
		check = md5()
		check.update(args[0][:8].encode('utf-8') + salt)
		if check.hexdigest()[:4] != args[0][8:12]:
			return _("incorrect name entered (checksum invalid).")
	
		if blacklisting:
			bot.blacklist.append(args[0])
			return _("%s was added to blacklist.") % args[0]

		to = ">>" + args[0]
		if args[0] in bot.usersposts:
			userpost = "<span class=\"userpost\">&gt; " + escape(bot.usersposts[args[0]]) + "</span><br/>"
	else:
		to = "!"
        message = " ".join(args[1:])
	if len(message) > message_limit:
		return _("too long answer, should be less than %d symbols, you entered %d symbols.") % (message_limit, len(message))
        soup = BeautifulSoup(open(bot.settings["ans_file"], "r"))
	posts = soup.findAll('p')
	new_post = Tag(soup, 'p')
	user_id = Tag(soup, 'span', [('id', 'user_id')])
	if to != "!":
		user_id.insert(0, escape(to))
	else:
		user_id.insert(0, "<b>&gt;&gt;ОБЪЯВЛЕНИЕ&lt;&lt;</b>")
	new_post.insert(0, '[' + datetime.datetime.strftime(datetime.datetime.now(), "%H:%M:%S") + ']')
	new_post.insert(1, user_id)
	new_post.insert(2, userpost + escape(message))
	if len(posts) > 0:
		posts[0].parent.insert(2, new_post)
	else:
		soup.find('h1').parent.insert(1, new_post)
	if len(posts) > 9:

		posts[len(posts) - 1].extract()

	f = open(bot.settings["ans_file"], "w")
	f.write(soup.prettify())
	f.close()
        
        return _("sent.")
Ejemplo n.º 4
0
def set_next(client, *args):
    try:
        num = int(args[0])
        if num < 3:
            return _("track is protected.")
        to = int(client.status()['playlistlength']) - 1
        client.move(num, to)
        return _("moved track #%d to #%d.") % (num, to)
    except:
        return
Ejemplo n.º 5
0
def delete_pos(client, *args):
    if not args:
        print "Need an argument"
    try:
        if int(args[0]) < 3:
	    return _("track is protected.")
        client.delete(int(args[0]))
        return _("removed track #%s from playlist") % args
    except:
        return _("F**K YOU. I mean, error.")    
Ejemplo n.º 6
0
def set_next(client, *args):
    try:
        num = int(args[0])
	if num < 3:
	    return _("track is protected.")
	to = int(client.status()['playlistlength']) - 1
	client.move(num, to)
	return _("moved track #%d to #%d.") % (num, to)
    except:
        return
Ejemplo n.º 7
0
def delete_pos(client, *args):
    if not args:
        print "Need an argument"
    try:
        if int(args[0]) < 3:
            return _("track is protected.")
        client.delete(int(args[0]))
        return _("removed track #%s from playlist") % args
    except:
        return _("F**K YOU. I mean, error.")
Ejemplo n.º 8
0
def main(bot, args):
    """leave <room> [pass]\nПокинуть комнату <room>.\nСм. также: join, rooms"""

    if len(args) == 1: room = (args[0], '')
    elif len(args) == 2: room = (args[0], args[1])
    else: return

    if bot.leave(room):
        return _('done.')
    else:
        return _('I\'m not in that room.')
Ejemplo n.º 9
0
def wtf(client, *args):
    current_track = client.currentsong()
    if "pos" in current_track:
        if int(current_track["pos"]) < 2:
            return _("DJ is on air, doing nothing.")

        result = _("now playing track %s. %s (tags were set to keywords)") % (current_track["pos"], current_track["file"].replace("127.0.0.1", "radioanon.ru").decode("utf-8")) 
        set_tag(client, *current_track["file"].decode("utf-8").replace("http://127.0.0.1:8080/", "").split("+"))
    else:
        result = _("playing nothing.")
    return result
Ejemplo n.º 10
0
def main(bot, args):
    """leave <room> [pass]\nПокинуть комнату <room>.\nСм. также: join, rooms"""

    if len(args) == 1: room = (args[0], '')
    elif len(args) == 2: room = (args[0], args[1])
    else: return

    if bot.leave(room):
        return _('done.')
    else:
        return _('I\'m not in that room.')
Ejemplo n.º 11
0
Archivo: join.py Proyecto: rkfg/Talho
def main(bot, args):
    """join <room> [pass]\nJoin a room.\nSee also: leave, rooms"""

    room = ["", "", 10]
    room[: len(args)] = args
    room[2] = int(room[2])
    if not room[0]:
        return

    if bot.join(room):
        return _("done.")
    else:
        return _("I'm already in this room.")
Ejemplo n.º 12
0
def main(bot, args):
    """join <room> [pass]\nJoin a room.\nSee also: leave, rooms"""

    room = ['', '', 10]
    room[:len(args)] = args
    room[2] = int(room[2])
    if not room[0]:
        return

    if bot.join(room):
        return _('done.')
    else:
        return _('I\'m already in this room.')
Ejemplo n.º 13
0
def play(client, *args):
    msg = check_block()
    if msg:
        return msg

    if len(args) != 1:
        return
    try:
        client.play(int(args[0]))
        if int(args[0]) < 3:
	    client.random(0)
        return _("track #%s started.") % args[0]
    except (ValueError, TypeError):
        return _("unknown f*****g shit happened.")
Ejemplo n.º 14
0
def play(client, *args):
    msg = check_block()
    if msg:
        return msg

    if len(args) != 1:
        return
    try:
        client.play(int(args[0]))
        if int(args[0]) < 3:
            client.random(0)
        return _("track #%s started.") % args[0]
    except (ValueError, TypeError):
        return _("unknown f*****g shit happened.")
Ejemplo n.º 15
0
def set_tag(client, *args):
    if not args:
        return
    try:
        msg = check_block()
        if msg:
            return msg

        song_name = " ".join(args)[:100]
        metadata_opener = IcecastAdminOpener()
        update_query = urllib.urlencode({ "mount" : "/radio", "mode" : "updinfo", "song" : song_name.encode("utf-8") })
        metadata_opener.open("http://127.0.0.1:8000/admin/metadata?" + update_query).read()
        return _("new track name is '%s'.") % song_name
    except:
        return _("unknown f*****g shit happened.")
Ejemplo n.º 16
0
def wtf(client, *args):
    current_track = client.currentsong()
    if "pos" in current_track:
        if int(current_track["pos"]) < 2:
            return _("DJ is on air, doing nothing.")

        result = _("now playing track %s. %s (tags were set to keywords)") % (
            current_track["pos"], current_track["file"].replace(
                "127.0.0.1", "radioanon.ru").decode("utf-8"))
        set_tag(
            client, *current_track["file"].decode("utf-8").replace(
                "http://127.0.0.1:8080/", "").split("+"))
    else:
        result = _("playing nothing.")
    return result
Ejemplo n.º 17
0
Archivo: tr.py Proyecto: asukafag/Talho
def translate(from_l, to_l, text, bot):
    text = urllib.quote(text.encode("utf-8"))
    try:
        data = misc.readUrl(
            "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&langpair=%s%%7C%s"
            % (text, from_l, to_l),
            None,
            bot,
        )
        if not data:
            return "can't get data"
    except:
        return _("google is not available, sorry.")

    try:
        convert = loads(data)
        status = convert["responseStatus"]

        results = convert["responseData"]["translatedText"]
        if results:
            return results
    except:
        pass

    return "can't translate this shit!"
Ejemplo n.º 18
0
def google(query, bot):
    query = urllib.quote(query.encode('utf-8'))
    try:
        if "google_key" in bot.settings:
            google_key = "&key=" + bot.settings["google_key"]
        else:
            google_key = ""
        data = misc.readUrl(
            'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s&hl=ru%s'
            % (query, google_key), None, bot)
        if not data: return 'can\'t get data'
    except:
        return _("google is not available, sorry.")

    try:
        convert = loads(data)
        results = convert['responseData']['results']
        if not results: return 'not found'

        url = urllib.unquote(results[0]['url'])
        title = results[0]['titleNoFormatting']
        content = results[0]['content']
        text = '%s\n%s\n%s' % (title, content, url)

        text = re.sub('<b>|</b>', '', text)
        text = re.sub('   ', '\n', text)
        text = text.replace(u'\ufeff', '')

        return text
    except:
        return 'error'
Ejemplo n.º 19
0
Archivo: g.py Proyecto: asukafag/Talho
def google(query, bot):
    query = urllib.quote(query.encode('utf-8'))
    try:
        if "google_key" in bot.settings:
            google_key = "&key=" + bot.settings["google_key"]
        else:
            google_key = ""
        data = misc.readUrl('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s&hl=ru%s' % (query, google_key), None, bot)
        if not data: return 'can\'t get data'
    except:
        return _("google is not available, sorry.")

    try:
    	convert = loads(data)
	results = convert['responseData']['results']
	if not results: return 'not found'

    	url = urllib.unquote(results[0]['url'])
    	title = results[0]['titleNoFormatting']
    	content = results[0]['content']
    	text = '%s\n%s\n%s' %(title, content, url)

    	text = re.sub('<b>|</b>', '', text)
    	text = re.sub('   ', '\n', text)

    	return text
    except:
    	return 'error'
Ejemplo n.º 20
0
def main(bot, args):
    """установить уровень баттхёрта в диджейке (в процентах)."""
    if len(args) < 1:
        return
    try:
        bhlev = int(args[0])
    except ValueError:
        return
    if bhlev < 0 or bhlev > 100:
        return

    bhpage = open(bot.settings["bh_file"], 'w')

    if bhlev < 50:
        g = 255
        r = bhlev * 5
    else:
        g = 255 - (bhlev - 50) * 5
        r = 255

    bhpage.write(
        '<?php echo "<b><span style=\\"background-color: #333; color: #%02x%02x00; padding: 3px; border: 1px #eee dashed;\\">%d%%</span></b>"; ?>'
        % (r, g, bhlev))
    bhpage.close()

    return _("set.")
Ejemplo n.º 21
0
def fancy_tracks(tracks):
    result = "\n"
    if not tracks:
        return _("nothing found.")
    try:
      for track in tracks:
        result += track["pos"] + ". "
        title = ""
        #if "title" in track:
        #    title = track["title"]
        #    if isinstance(title, list):
        #        title = " ".join(title)

        #    title = decoder(title)

        #    if "artist" in track:
        #        artist = track["artist"]
        #        if isinstance(artist, list):
        #            artist = " ".join(artist)
        #        artist = decoder(artist)

        #        title = artist + u" — " + title
        #else:
        title = track["file"].decode("utf-8").replace("127.0.0.1", "radioanon.ru")
            
        result += title + u"\n"
    except:
        print str("".join(traceback.format_exception(*sys.exc_info())))
    return result
Ejemplo n.º 22
0
def fancy_tracks(tracks):
    result = "\n"
    if not tracks:
        return _("nothing found.")
    try:
        for track in tracks:
            result += track["pos"] + ". "
            title = ""
            #if "title" in track:
            #    title = track["title"]
            #    if isinstance(title, list):
            #        title = " ".join(title)

            #    title = decoder(title)

            #    if "artist" in track:
            #        artist = track["artist"]
            #        if isinstance(artist, list):
            #            artist = " ".join(artist)
            #        artist = decoder(artist)

            #        title = artist + u" — " + title
            #else:
            title = track["file"].decode("utf-8").replace(
                "127.0.0.1", "anon.fm")

            result += title + u"\n"
    except:
        print str("".join(traceback.format_exception(*sys.exc_info())))
    return result
Ejemplo n.º 23
0
Archivo: news.py Proyecto: rkfg/Talho
def main(bot, args):
    """сбросить кэш новостей."""
    try:
        os.unlink("/srv/radioanon.ru/htdocs/cache/cache.dat")
        os.unlink("/srv/radioanon.ru/htdocs/cache/cache.upd")
    except:
        pass
    return _("dropped cache.")
Ejemplo n.º 24
0
def main(bot, args):
    """сбросить кэш новостей."""
    try:
        os.unlink("/srv/radioanon.ru/htdocs/cache/cache.dat")
        os.unlink("/srv/radioanon.ru/htdocs/cache/cache.upd")
    except:
        pass
    return _("dropped cache.")
Ejemplo n.º 25
0
def check_block():
    global globalbot
    if "block_time" in globalbot.settings and datetime.datetime.now(
    ) < globalbot.settings["block_time"]:
        return _("mpd control is blocked, %s left") % (
            globalbot.settings["block_time"] - datetime.datetime.now())
    else:
        return None
Ejemplo n.º 26
0
    def rmmod(self, bot, args): #{{{
        '''rmmod <module>\nRemove module.\nSee also: load, modprobe, lsmod'''

        if len(args) != 1: return

        if args[0] == 'load' or args[0] == 'modprobe' or args[0] == 'rmmod':
            return _('MODULE: can\'t remove %s') % args[0]

        if self.commands.has_key(args[0]):
            del self.commands[args[0]]
        else:
            if self.plaintext_dispatchers.has_key(args[0]):
                del self.plaintext_dispatchers[args[0]]
            else:
                return _('MODULE: %s not loaded') % args[0]

        info = _('MODULE: %s removed') % args[0]
        logging.info(info)
        return info
Ejemplo n.º 27
0
def shuffle(client, *args):
    
    msg = check_block()
    if msg:
        return msg

    if len(args) > 0:
        if args[0] == 'off' or args[0] == u'щаа':
            client.random(0)
            return _("random was switched off.")
        if args[0] == 'on' or args[0] == u'щт':
            client.random(1)
            return _("random was switched on.")
        if args[0] == 'st' or args[0] == u'ые':
            return _("random is currently " + ("on" if client.status()["random"] == "1" else "off"))
    else:
        client.random(1)
        client.next()
    
        return _("random started, next track is playing.")
Ejemplo n.º 28
0
def set_tag(client, *args):
    if not args:
        return
    try:
        msg = check_block()
        if msg:
            return msg

        song_name = " ".join(args)[:100]
        metadata_opener = IcecastAdminOpener()
        update_query = urllib.urlencode({
            "mount": "/radio",
            "mode": "updinfo",
            "song": song_name.encode("utf-8")
        })
        metadata_opener.open("http://127.0.0.1:8000/admin/metadata?" +
                             update_query).read()
        return _("new track name is '%s'.") % song_name
    except:
        return _("unknown f*****g shit happened.")
Ejemplo n.º 29
0
def del_by_keyword(client, *args):
    name = " ".join(args)
    if len(name) < 4:
        return _("minimum 4 letters allowed")

    tracks = client.playlistsearch("any", name.encode('utf-8'))
    if not len(tracks):
        return _("nothing found.")

    trackstr = fancy_tracks(tracks)
    if len(trackstr) > 1000:
        trackstr = trackstr[:1000] + "..."
    cnt = 0
    for t in reversed(tracks):
        p = int(t["pos"])
        if p > 2:
            client.delete(p)
            cnt += 1

    return _("%d tracks deleted:%s") % (cnt, trackstr)
Ejemplo n.º 30
0
def main(bot, args):
    '''Weather in the given city'''

    if not args:
        return
    
    city = " ".join(args).encode("utf-8")
    req_args = urllib.urlencode( { "where" : city } )
    handle = urllib2.urlopen("http://xoap.weather.com/search/search?" + req_args)
    response = parse(handle)
    loc = response.getElementsByTagName("loc")
    if loc:
        city = loc[0].attributes["id"].value
    else:
        return _("city not found.")

    handle = urllib2.urlopen("http://xoap.weather.com/weather/local/" + city + "?cc=*&unit=m&par=1121946239&key=3c4cd39ee5dec84f")
    try:
        response = parse(handle)
        cityname = response.getElementsByTagName("dnam")
        if not cityname:
            return _("city not found.")

	cityname = cityname[0].childNodes[0].nodeValue
	tags_cc = ( "lsup", "tmp", "t" )
	tags_wind = ( "s", "gust", "t" )
	cc = response.getElementsByTagName("cc")[0]
	for tag in tags_cc:
	    globals()["cc_" + tag] = cc.getElementsByTagName(tag)[0].childNodes[0].nodeValue

	wind = cc.getElementsByTagName("wind")[0]
	for tag in tags_wind:
	    globals()["wind_" + tag] = wind.getElementsByTagName(tag)[0].childNodes[0].nodeValue
	
	globals()["wind_s"] = kmhtomsec(globals()["wind_s"])
	if wind_gust != "N/A":
	    globals()["wind_s"] += "-" + kmhtomsec(globals()["wind_gust"])
    except IndexError:
        return _("error getting weather.")

    return _(u"weather for %s at %s: Temperature: %s°C, %s, Wind speed: %s m/sec, Wind direction: %s" ) % (cityname, cc_lsup.replace(" Local Time", ""), cc_tmp, cc_t, wind_s, wind_t)
Ejemplo n.º 31
0
def group(client, *args):
    name = " ".join(args)
    if len(name) < 4:
        return _("minimum 4 letters allowed")

    tracks = client.playlistsearch("any", name.encode('utf-8'))
    if not len(tracks):
        return _("nothing found.")

    trackstr = fancy_tracks(tracks)
    if len(trackstr) > 1000:
        trackstr = trackstr[:1000] + "..."
    cnt = 0
    to = int(client.status()['playlistlength']) - 1
    for t in reversed(tracks):
        p = int(t["pos"])
        if p > 2:
            client.move(p, to)
            cnt += 1

    return _("%d tracks grouped at the end of playlist:%s") % (cnt, trackstr)
Ejemplo n.º 32
0
def group(client, *args):
    name = " ".join(args)
    if len(name) < 4:
        return _("minimum 4 letters allowed")

    tracks = client.playlistsearch("any", name.encode('utf-8'))
    if not len(tracks):
        return _("nothing found.")

    trackstr = fancy_tracks(tracks)
    if len(trackstr) > 1000:
        trackstr = trackstr[:1000] + "..."
    cnt = 0
    to = int(client.status()['playlistlength']) - 1
    for t in reversed(tracks):
        p = int(t["pos"])
        if p > 2:
            client.move(p, to)
            cnt += 1

    return _("%d tracks grouped at the end of playlist:%s") % (cnt, trackstr)
Ejemplo n.º 33
0
def shuffle(client, *args):

    msg = check_block()
    if msg:
        return msg

    if len(args) > 0:
        if args[0] == 'off' or args[0] == u'щаа':
            client.random(0)
            return _("random was switched off.")
        if args[0] == 'on' or args[0] == u'щт':
            client.random(1)
            return _("random was switched on.")
        if args[0] == 'st' or args[0] == u'ые':
            return _("random is currently " +
                     ("on" if client.status()["random"] == "1" else "off"))
    else:
        client.random(1)
        client.next()

        return _("random started, next track is playing.")
Ejemplo n.º 34
0
def main(bot, args):
    """блокировка управления mpd на указанное число минут"""

    if not len(args):
       if not "block_time" in bot.settings or bot.settings["block_time"] < datetime.datetime.now():
           return _("mpd isn't blocked.")
       return _("%s left.") % (bot.settings["block_time"] - datetime.datetime.now())

    try:
        block_time = int(args[0])
    except ValueError:
        return

    if block_time < 0 or block_time > 60:
        return

    if block_time == 0:
        bot.settings["block_time"] = datetime.datetime.now()
	return _("block was reset.")

    bot.settings["block_time"] = datetime.datetime.now() + datetime.timedelta(minutes = block_time)
    return _("block time was set to %d minutes.") % block_time
Ejemplo n.º 35
0
def del_by_keyword(client, *args):
    name = " ".join(args)
    if len(name) < 4:
        return _("minimum 4 letters allowed")

    tracks = client.playlistsearch("any", name.encode('utf-8'))
    if not len(tracks):
        return _("nothing found.")

    if len(tracks) > int(client.status()['playlistlength']) * 5 / 10:
        return _("too much to delete, refusing.")

    trackstr = fancy_tracks(tracks)
    if len(trackstr) > 1000:
        trackstr = trackstr[:1000] + "..."
    cnt = 0
    for t in reversed(tracks):
        p = int(t["pos"])
        if p > 2:
            client.delete(p)
            cnt += 1

    return _("%d tracks deleted:%s") % (cnt, trackstr)
Ejemplo n.º 36
0
def seek(client, *args):
    current_track = client.currentsong()
    if not "time" in current_track:
        return _("can't seek.")

    if len(args) > 1:
        return
    args = args[0]
    HMS = re.match(r'(\d+):(\d+):(\d+)', args)
    if HMS and int(HMS.group(2)) < 60 and int(HMS.group(3)) < 60:
        time = int(HMS.group(3)) + int(HMS.group(2)) * 60 + int(HMS.group(1)) * 3600
    else:
        MS = re.match(r'(\d+):(\d+)', args)
        if MS and int(MS.group(1)) < 60 and int(MS.group(2)) < 60:
            time = int(MS.group(2)) + int(MS.group(1)) * 60
        else:
            if args.isdigit():
                time = int(args)
            else:
                return

    client.seekid(current_track["id"], time)
    return _("moving to %d/%s seconds.") % (time, current_track["time"])
Ejemplo n.º 37
0
def mounts_info(client, *args):
    try:
        result = "\n"
        mounts_to_check = ( "/first", "/second" )
        admin_page_opener = IcecastAdminOpener()
        page = admin_page_opener.open("http://127.0.0.1:8000/admin/").read()
        for mount in mounts_to_check:
            if "<h3>Mount Point %s</h3>" % mount in page:
                result += "Маунт %s *занят*" % mount + "\n"
            else:
                result += "Маунт %s *свободен*" % mount + "\n"
                
        return result
    except:
        return _("unknown f*****g shit happened.")
Ejemplo n.º 38
0
def mounts_info(client, *args):
    try:
        result = "\n"
        mounts_to_check = ("/first", "/second")
        admin_page_opener = IcecastAdminOpener()
        page = admin_page_opener.open("http://127.0.0.1:8000/admin/").read()
        for mount in mounts_to_check:
            if "<h3>Mount Point %s</h3>" % mount in page:
                result += "Маунт %s *занят*" % mount + "\n"
            else:
                result += "Маунт %s *свободен*" % mount + "\n"

        return result
    except:
        return _("unknown f*****g shit happened.")
Ejemplo n.º 39
0
def seek(client, *args):
    current_track = client.currentsong()
    if not "time" in current_track:
        return _("can't seek.")

    if len(args) > 1:
        return
    args = args[0]
    HMS = re.match(r'(\d+):(\d+):(\d+)', args)
    if HMS and int(HMS.group(2)) < 60 and int(HMS.group(3)) < 60:
        time = int(
            HMS.group(3)) + int(HMS.group(2)) * 60 + int(HMS.group(1)) * 3600
    else:
        MS = re.match(r'(\d+):(\d+)', args)
        if MS and int(MS.group(1)) < 60 and int(MS.group(2)) < 60:
            time = int(MS.group(2)) + int(MS.group(1)) * 60
        else:
            if args.isdigit():
                time = int(args)
            else:
                return

    client.seekid(current_track["id"], time)
    return _("moving to %d/%s seconds.") % (time, current_track["time"])
Ejemplo n.º 40
0
def add_vk(client, *args):
    if not args:
        return

    try:
        global globalbot
        global opener
        aftercurrent = (args[0] == "!"
                        and int(client.currentsong()["pos"]) > 1)
        if args[0] == "!":
            args = args[1:]

        req_args = urllib.urlencode({
            "c[q]": " ".join(args).encode('utf-8'),
            "c[section]": "audio"
        })
        req = urllib2.Request("http://vkontakte.ru/search?" + req_args)

        handle = opener.open(req)
        result = handle.read().decode("cp1251")

        match = re.search(ur"value=\"(http:[^,]+),", result)
        if match:
            playtime = re.search(
                ur"<div class=\"duration fl_r\" [^>]*>([0-9:]+)</div>", result)
            id = client.addid(
                ("http://127.0.0.1:8080/" + "+".join(args)).encode('utf-8'))
            if aftercurrent:
                client.move(
                    int(client.status()['playlistlength']) - 1,
                    int(client.currentsong()["pos"]) + 1)
                position = int(client.currentsong()["pos"]) + 1
            else:
                position = int(client.status()['playlistlength']) - 1
            title = re.search(
                ur"<b><a href=[^>]+><span [^>]+>([^<]+)</span></a></b> - <span id=\"title[^\"]+\"><a [^>]+><span [^>]+>([^<]+)</span>",
                result)
            if title:
                title = title.group(1) + u" — " + title.group(2)
            else:
                title = _("no title")

            if playtime:
                playtime = playtime.group(1)
                now = datetime.datetime.now()
            else:
                playtime = _("unknown")
                finish = _("unknown")

            return _("found new track #%s named \"%s\", duration is: %s") % (
                position, htmlunescape(title), playtime)
        else:
            return _("nothing found.")
    #except ValueError:
    except urllib2.URLError:
        return _("network error")
Ejemplo n.º 41
0
def track_list(client, *args):
    playlist = client.playlistinfo()
    n = 3
    last = 10
    try:
        if len(args) == 1:
            n = int(args[0])
            last = n + 11
        elif len(args) == 2:
            n = int(args[0])
            last = int(args[1]) + 1
            if last <= n:
                return
            if last - n > 20:
                return _("too many items in query, maximum 20 allowed.")
            
    except ValueError:
        return
    return fancy_tracks(playlist[n:last])
Ejemplo n.º 42
0
def track_list(client, *args):
    playlist = client.playlistinfo()
    n = 3
    last = 10
    try:
        if len(args) == 1:
            n = int(args[0])
            last = n + 11
        elif len(args) == 2:
            n = int(args[0])
            last = int(args[1]) + 1
            if last <= n:
                return
            if last - n > 20:
                return _("too many items in query, maximum 20 allowed.")

    except ValueError:
        return
    return fancy_tracks(playlist[n:last])
Ejemplo n.º 43
0
Archivo: tr.py Proyecto: DuloT34/Talho
def translate(from_l, to_l, text, bot):
    text = urllib.quote(text.encode('utf-8'))
    try:
        data = misc.readUrl('http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&key=%s&langpair=%s%%7C%s' %(text, bot.settings["google_key"], from_l, to_l), None, bot)
        if not data: return 'can\'t get data'
    except:
        return _("google is not available, sorry.")
   
    try:
        convert = loads(data)
        status = convert['responseStatus']

        results = convert['responseData']['translatedText']
        if results: 
            return results
    except:
        pass

    return 'can\'t translate this shit!'
Ejemplo n.º 44
0
def translate(from_l, to_l, text, bot):
    text = urllib.quote(text.encode('utf-8'))
    try:
        data = misc.readUrl(
            'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&key=%s&langpair=%s%%7C%s'
            % (text, bot.settings["google_key"], from_l, to_l), None, bot)
        if not data: return 'can\'t get data'
    except:
        return _("google is not available, sorry.")

    try:
        convert = loads(data)
        status = convert['responseStatus']

        results = convert['responseData']['translatedText']
        if results:
            return results
    except:
        pass

    return 'can\'t translate this shit!'
Ejemplo n.º 45
0
def mounts_info(client, *args):
    try:
        result = "\n"
        mounts_to_check = ( "/first", "/second" )
        admin_page_opener = IcecastAdminOpener()
        page = admin_page_opener.open("http://127.0.0.1:8000/admin/").read()
        status = etree.fromstring(page.decode('utf-8'))
        for mount in mounts_to_check:
            node = status.xpath("/icestats/source[@mount='%s']" % mount)
            if len(node) > 0:
                n = node[0].xpath("dj_nick")
                if len(n):
                    nick = n[0].text
                else:
                    nick = "?unknown?"
                result += ("Маунт %s *занят* %s" % (mount, nick.encode('utf-8'))) + "\n"
            else:
                result += "Маунт %s *свободен*" % mount + "\n"

        return result
    except:
        return _("unknown f*****g shit happened.")
Ejemplo n.º 46
0
def mounts_info(client, *args):
    try:
        result = "\n"
        mounts_to_check = ("/first", "/second")
        admin_page_opener = IcecastAdminOpener()
        page = admin_page_opener.open("http://127.0.0.1:8000/admin/").read()
        status = etree.fromstring(page.decode('utf-8'))
        for mount in mounts_to_check:
            node = status.xpath("/icestats/source[@mount='%s']" % mount)
            if len(node) > 0:
                n = node[0].xpath("dj_nick")
                if len(n):
                    nick = n[0].text
                else:
                    nick = "?unknown?"
                result += ("Маунт %s *занят* %s" %
                           (mount, nick.encode('utf-8'))) + "\n"
            else:
                result += "Маунт %s *свободен*" % mount + "\n"

        return result
    except:
        return _("unknown f*****g shit happened.")
Ejemplo n.º 47
0
def add_vk(client, *args):
    if not args:
        return

    try:
        global globalbot
        global opener
        aftercurrent = (args[0] == "!" and int(client.currentsong()["pos"]) > 1)
        if args[0] == "!":
            args = args[1:]

        req_args = urllib.urlencode({ "c[q]" : " ".join(args).encode('utf-8'), "c[section]" : "audio" })
        req = urllib2.Request("http://vkontakte.ru/search?" + req_args)

        handle = opener.open(req)
        result = handle.read().decode("cp1251")

        match = re.search(ur"value=\"(http:[^,]+),", result)
        if match:
            playtime = re.search(ur"<div class=\"duration fl_r\" [^>]*>([0-9:]+)</div>", result)
            id = client.addid(("http://127.0.0.1:8080/" + "+".join(args)).encode('utf-8'))
            if aftercurrent:
                client.move(int(client.status()['playlistlength']) - 1, int(client.currentsong()["pos"]) + 1)
	        position = int(client.currentsong()["pos"]) + 1
            else:
	        position = int(client.status()['playlistlength']) - 1
	    title = re.search(ur"<b><a href=[^>]+><span [^>]+>([^<]+)</span></a></b> - <span id=\"title[^\"]+\"><a [^>]+><span [^>]+>([^<]+)</span>", result)
	    if title:
	        title = title.group(1) + u" — " + title.group(2)
            else:
	        title = _("no title")

            if playtime:
                playtime = playtime.group(1)
                now = datetime.datetime.now()
            else:
                playtime = _("unknown")
                finish = _("unknown")

            return _("found new track #%s named \"%s\", duration is: %s") % (position, htmlunescape(title), playtime)
        else:
            return _("nothing found.")
    #except ValueError:
    except urllib2.URLError:
        return _("network error")
Ejemplo n.º 48
0
Archivo: bh.py Proyecto: DuloT34/Talho
def main(bot, args):
    """установить уровень баттхёрта в диджейке (в процентах)."""
    if len(args) < 1:
        return
    try:
        bhlev = int(args[0])
    except ValueError:
        return
    if bhlev < 0 or bhlev > 100:
        return

    bhpage = open(bot.settings["bh_file"], 'w')

    if bhlev < 50:
        g = 255
	r = bhlev * 5
    else:
        g = 255 - (bhlev - 50) * 5
	r = 255

    bhpage.write('<?php echo "<b><span style=\\"background-color: #333; color: #%02x%02x00; padding: 3px; border: 1px #eee dashed;\\">%d%%</span></b>"; ?>' % (r, g, bhlev))
    bhpage.close()

    return _("set.")
Ejemplo n.º 49
0
        client.connect(**bot.settings["mpd_addr"])
    except socket.error, msg:
        return "ошибка соединения: " + msg
    try:
        client.password(bot.settings['mpd_password'])
    except mpd.CommandError:
        client.disconnect()
        return "неверный пароль!"

    if args:
        cmd = args[0]
        if cmd in commands:
            try:
                result = commands[cmd](client, *args[1:])
            except mpd.CommandError:
                result = _("unknown shit happend")
        else:
            result = _("unknown command")
    else:
        current_track = client.currentsong()
        if "pos" in current_track:
            status = client.status()
            result = _("now playing track #%s @ %s seconds") % (
                current_track["pos"].decode("utf-8"),
                status["time"] if "time" in status else "???")
        else:
            result = _("playing nothing.")
    client.disconnect()
    return result

Ejemplo n.º 50
0
def main(bot, args):
	'''Ответить слушателю. Параметры: <user_id> <message>
Если в качестве user_id указать восклицательный знак, сообщение будет выглядеть как объявление.
Если в качестве user_id указать символ @ (или " в русской раскладке), будет использован идентификатор последнего поста. Использовать ОСТОРОЖНО!
? user_id — заблеклистить юзера user_id, его сообщения перестанут поступать в диджейку.
?? — показать блеклист.
?! — очистить блеклист.'''
	syl = { '0' : 'be', '1' : 'sa', '2' : 'ko', '3' : 'pa', '4' : 're', '5' : 'du', '6' : 'ma', '7' : 'ne', '8' : 'wa', '9' : 'si', 'a' : 'to', 'b' : 'za', 'c' : 'mi', 'd' : 'ka', 'e' : 'ga', 'f' : 'no' }
	salt = bot.settings["ans_salt"]
	message_limit = 250
	userpost = ""
	if len(args) == 1 and args[0] != "??" and args[0] != "?!" or not len(args):
		return
	blacklisting = False
	if args[0] != "!":
		if args[0] == "??":
			return _("blacklist:\n%s") % "\n".join(bot.blacklist)
		if args[0] == "?!":
			bot.blacklist = []
			return _("blacklist cleared.")
		if args[0] == "?":
			blacklisting = True
			del args[0]
		if args[0] == "@" or args[0] == '"':
			sender = bot.last_user_id
		elif args[0].isdigit() and int(args[0]) >= 10 and int(args[0]) < 100:
			sender = bot.num2uid[int(args[0])]
		else:
			sender = args[0]
		if len(sender) != 12:
			return _("incorrect name entered, should be 12 symbols.")
		check = md5()
		check.update(sender[:8].encode('utf-8') + salt)
		if check.hexdigest()[:4] != sender[8:12]:
			return _("incorrect name entered (checksum invalid).")
	
		if blacklisting:
			bot.blacklist.append(sender)
			return _("%s was added to blacklist.") % sender

		to = ">>" + sender
		if sender in bot.usersposts:
			userpost = "<span class=\"userpost\">&gt; " + escape(bot.usersposts[sender]) + "</span><br/>"
	else:
		to = "!"
        message = " ".join(args[1:])
	if len(message) > message_limit:
		return _("too long answer, should be less than %d symbols, you entered %d symbols.") % (message_limit, len(message))
        soup = BeautifulSoup(open(bot.settings["ans_file"], "r"))
	posts = soup.findAll('p')
	new_post = Tag(soup, 'p')
	user_id = Tag(soup, 'span', [('id', 'user_id')])
	if to != "!":
		user_id.insert(0, escape(to))
	else:
		user_id.insert(0, "<b>&gt;&gt;ОБЪЯВЛЕНИЕ&lt;&lt;</b>")
	new_post.insert(0, '<span class="timestamp">[' + datetime.datetime.strftime(datetime.datetime.now(), "%H:%M:%S") + ']</span>')
	new_post.insert(1, user_id)
	message = re.sub(r'\[([^]]*)\]', lambda x: '<a href="' + x.group(1).replace("&amp;", "&") + '" target="_blank">' + x.group(1) + '</a>', escape(message))
	message = re.sub(r'\{([^}]*)\}', lambda x: '<a href="' + x.group(1).replace("&amp;", "&") + '" target="_blank"><img style="max-width: 200px; max-height: 200px;display: inline;" src="' + x.group(1).replace("&amp;", "&") + '"/></a>', message)
	new_post.insert(2, userpost + message)
	if len(posts) > 0:
		posts[0].parent.insert(2, new_post)
	else:
		soup.find('h1').parent.insert(1, new_post)
	if len(posts) > 9:

		posts[len(posts) - 1].extract()

	f = open(bot.settings["ans_file"], "w")
	f.write(soup.prettify())
	f.close()
        
        return _("sent.")
Ejemplo n.º 51
0
def check_block():
    global globalbot
    if "block_time" in globalbot.settings and datetime.datetime.now() < globalbot.settings["block_time"]:
        return _("mpd control is blocked, %s left") % (globalbot.settings["block_time"] - datetime.datetime.now())
    else:
        return None
Ejemplo n.º 52
0
        client.connect(**bot.settings["mpd_addr"])
    except socket.error, msg:
        return "ошибка соединения: " + msg
    try:
        client.password(bot.settings['mpd_password'])
    except mpd.CommandError:
        client.disconnect()
        return "неверный пароль!"

    if args:
        cmd = args[0]
        if cmd in commands:
            try:
                result = commands[cmd](client, *args[1:])
	    except mpd.CommandError:
	        result = _("unknown shit happend")
	else:
	    result = _("unknown command")
    else:
        current_track = client.currentsong()
        if "pos" in current_track:
            status = client.status()
            result = _("now playing track #%s @ %s seconds") % (current_track["pos"].decode("utf-8"), status["time"] if "time" in status else "???")
        else:
            result = _("playing nothing.")
    client.disconnect()
    return result

if __name__ == "__main__":
	print main(None, None)