• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python misc._函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中misc._函数的典型用法代码示例。如果您正苦于以下问题:Python _函数的具体用法?Python _怎么用?Python _使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了_函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: modprobe

    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
开发者ID:DuloT34,项目名称:Talho,代码行数:30,代码来源:jabberbot.py


示例2: main

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.")
开发者ID:DuloT34,项目名称:Talho,代码行数:30,代码来源:rb.py


示例3: main

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.")
开发者ID:asukafag,项目名称:Talho,代码行数:57,代码来源:ans.py


示例4: delete_pos

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 _("FUCK YOU. I mean, error.")    
开发者ID:DuloT34,项目名称:Talho,代码行数:10,代码来源:mpdmod.py


示例5: set_next

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
开发者ID:DuloT34,项目名称:Talho,代码行数:10,代码来源:mpdmod.py


示例6: wtf

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
开发者ID:DuloT34,项目名称:Talho,代码行数:11,代码来源:mpdmod.py


示例7: main

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.')
开发者ID:DuloT34,项目名称:Talho,代码行数:11,代码来源:leave.py


示例8: main

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.")
开发者ID:rkfg,项目名称:Talho,代码行数:13,代码来源:join.py


示例9: play

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 fucking shit happened.")
开发者ID:DuloT34,项目名称:Talho,代码行数:14,代码来源:mpdmod.py


示例10: set_tag

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 fucking shit happened.")
开发者ID:DuloT34,项目名称:Talho,代码行数:15,代码来源:mpdmod.py


示例11: google

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'
开发者ID:asukafag,项目名称:Talho,代码行数:28,代码来源:g.py


示例12: translate

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!"
开发者ID:asukafag,项目名称:Talho,代码行数:25,代码来源:tr.py


示例13: fancy_tracks

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
开发者ID:DuloT34,项目名称:Talho,代码行数:29,代码来源:mpdmod.py


示例14: main

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.")
开发者ID:rkfg,项目名称:Talho,代码行数:8,代码来源:news.py


示例15: rmmod

    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
开发者ID:DuloT34,项目名称:Talho,代码行数:19,代码来源:jabberbot.py


示例16: del_by_keyword

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)
开发者ID:asukafag,项目名称:Talho,代码行数:20,代码来源:mpdmod.py


示例17: shuffle

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.")
开发者ID:DuloT34,项目名称:Talho,代码行数:20,代码来源:mpdmod.py


示例18: main

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)
开发者ID:DuloT34,项目名称:Talho,代码行数:41,代码来源:weather.py


示例19: group

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)
开发者ID:DuloT34,项目名称:Talho,代码行数:21,代码来源:mpdmod.py


示例20: main

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
开发者ID:DuloT34,项目名称:Talho,代码行数:22,代码来源:block.py



注:本文中的misc._函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python misc._abort函数代码示例发布时间:2022-05-27
下一篇:
Python misaka.html函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap