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

Python tools.Identifier类代码示例

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

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



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

示例1: bomb_glue

def bomb_glue(bot, trigger):
    old = trigger.nick
    new = Identifier(trigger)
    with lock:
        if old.lower() in BOMBS:
            BOMBS[new.lower()] = BOMBS.pop(old.lower())
            bot.notice(STRINGS['BOMB_STILL'] % new, new)
开发者ID:piagetbot,项目名称:sopel,代码行数:7,代码来源:bombbot.py


示例2: get_nick_or_channel_value

 def get_nick_or_channel_value(self, name, key):
     """Gets the value `key` associated to the nick or channel  `name`."""
     name = Identifier(name)
     if name.is_nick():
         return self.get_nick_value(name, key)
     else:
         return self.get_channel_value(name, key)
开发者ID:sopel-irc,项目名称:sopel,代码行数:7,代码来源:db.py


示例3: cutwire

def cutwire(bot, trigger):
    """
    Tells sopel to cut a wire when you've been bombed.
    """
    global bombs, colors
    target = Identifier(trigger.nick)
    if target.lower() != bot.nick.lower() and target.lower() not in bombs:
        bot.say('You can\'t cut a wire till someone bombs you')
        return
    if not trigger.group(2):
        bot.say('You have to choose a wire to cut.')
        return
    color, code = bombs.pop(target.lower())  # remove target from bomb list
    wirecut = trigger.group(2).rstrip(' ')
    if wirecut.lower() in ('all', 'all!'):
        sch.cancel(code)  # defuse timer, execute premature detonation
        kmsg = ('KICK %s %s : Cutting ALL the wires! *boom* (You should\'ve picked the %s wire.)'
                % (trigger.sender, target, color))
        bot.write([kmsg])
    elif wirecut.capitalize() not in colors:
        bot.say('I can\'t seem to find that wire, ' + target + '! You sure you\'re picking the right one? It\'s not here!')
        bombs[target.lower()] = (color, code)  # Add the target back onto the bomb list,
    elif wirecut.capitalize() == color:
        bot.say('You did it, ' + target + '! I\'ll be honest, I thought you were dead. But nope, you did it. You picked the right one. Well done.')
        sch.cancel(code)  # defuse bomb
    else:
        sch.cancel(code)  # defuse timer, execute premature detonation
        kmsg = 'KICK ' + trigger.sender + ' ' + target + \
               ' : No! No, that\'s the wrong one. Aww, you\'ve gone and killed yourself. Oh, that\'s... that\'s not good. No good at all, really. Wow. Sorry. (You should\'ve picked the ' + color + ' wire.)'
        bot.write([kmsg])
开发者ID:johnlage,项目名称:BombBot,代码行数:30,代码来源:bomb.py


示例4: kickban

def kickban(bot, trigger):
    """
    This gives admins the ability to kickban a user.
    The bot must be a Channel Operator for this command to work.
    .kickban [#chan] user1 user!*@* get out of here
    """
    if bot.privileges[trigger.sender][bot.nick] < HALFOP:
        return bot.reply("I'm not a channel operator!")
    text = trigger.group().split()
    argc = len(text)
    if argc < 4:
        return
    opt = Identifier(text[1])
    nick = opt
    mask = text[2]
    channel = trigger.sender
    reasonidx = 3
    if not opt.is_nick():
        if argc < 5:
            return
        channel = opt
        nick = text[2]
        mask = text[3]
        reasonidx = 4
    reason = ' '.join(text[reasonidx:])
    mask = configureHostMask(mask)
    if mask == '':
        return
    bot.write(['MODE', channel, '+b', mask])
    bot.write(['KICK', channel, nick], reason)
开发者ID:Cnwauche,项目名称:sopel,代码行数:30,代码来源:adminchannel.py


示例5: start

def start(bot, trigger):
    """
    Put a bomb in the specified user's pants. They will be kicked if they
     don't guess the right wire fast enough.
    """
    if not trigger.group(3):
        bot.say('Who do you want to Bomb?')
        return
    if not trigger.sender.startswith('#'):
        bot.say('Tell me this in a channel')
        return
    global bombs
    global sch
    target = Identifier(trigger.group(3))
    if target == bot.nick:
        bot.say('I will NOT BOMB MYSELF!')
        return
    if target.lower() in bombs:
        bot.say('I can\'t fit another bomb in ' + target + '\'s pants!')
        return
    if target == trigger.nick:
        bot.say('I will not LET YOU BOMB YOURSELF!')
        return
    if target.lower() not in bot.privileges[trigger.sender.lower()]:
        bot.say('Please Bomb someone WHO IS HERE!')
        return
    message = 'Hey, ' + target + '! Don\'t look but, I think there\'s a bomb in your pants. 2 minute timer, 5 wires: Red, Yellow, Blue, White and Black. Which wire should I cut? Don\'t worry, I know what I\'m doing! (respond with .cutwire color)'
    bot.say(message)
    color = choice(colors)
    bot.msg(trigger.nick,
               "Hey, don\'t tell %s, but the %s wire? Yeah, that\'s the one."
               " But shh! Don\'t say anything!" % (target, color))
    code = sch.enter(fuse, 1, explode, (bot, trigger))
    bombs[target.lower()] = (color, code)
    sch.run()
开发者ID:johnlage,项目名称:BombBot,代码行数:35,代码来源:bomb.py


示例6: cancel_bomb

def cancel_bomb(bot, trigger):
    """
    Lets a bomber disarm the bomb they set on the specified user. Does not reset the cooldown timer.
    (Bot admins can cancel bombs on any player in the channel.)
    """
    target = trigger.group(3) or None
    if not target:
        for bomb in BOMBS:
            if trigger.nick == BOMBS[bomb]['bomber']:
                target = BOMBS[bomb]['target']
                break
        if not target:
            return bot.reply(STRINGS['CANCEL_WHOM'])
    target = Identifier(target)  # issue #24
    with lock:
        if target.lower() not in BOMBS:
            bot.reply(STRINGS['CANCEL_NO_BOMB'] % target)
            return
        if trigger.nick != BOMBS[target.lower()]['bomber'] and not trigger.admin:
            bot.reply(STRINGS['CANCEL_NO_PERMISSION'] % target)
            return
        bomber = BOMBS[target.lower()]['bomber']
        bombs_planted = bot.db.get_nick_value(bomber, 'bombs_planted') or 0
        bot.db.set_nick_value(bomber, 'bombs_planted', bombs_planted - 1)
        BOMBS.pop(target.lower())['timer'].cancel()
        bot.say(STRINGS['CANCEL_DONE'] % target)
开发者ID:dgw,项目名称:sopel-BombBot,代码行数:26,代码来源:bombbot.py


示例7: track_nicks

def track_nicks(bot, trigger):
    """Track nickname changes and maintain our chanops list accordingly."""
    old = trigger.nick
    new = Identifier(trigger)

    # Give debug mssage, and PM the owner, if the bot's own nick changes.
    if old == bot.nick and new != bot.nick:
        privmsg = ("Hi, I'm your bot, %s."
                   "Something has made my nick change. "
                   "This can cause some problems for me, "
                   "and make me do weird things. "
                   "You'll probably want to restart me, "
                   "and figure out what made that happen "
                   "so you can stop it happening again. "
                   "(Usually, it means you tried to give me a nick "
                   "that's protected by NickServ.)") % bot.nick
        debug_msg = ("Nick changed by server. "
            "This can cause unexpected behavior. Please restart the bot.")
        LOGGER.critical(debug_msg)
        bot.msg(bot.config.core.owner, privmsg)
        return

    for channel in bot.privileges:
        channel = Identifier(channel)
        if old in bot.privileges[channel]:
            value = bot.privileges[channel].pop(old)
            bot.privileges[channel][new] = value

    for channel in bot.channels.values():
        channel.rename_user(old, new)
    if old in bot.users:
        bot.users[new] = bot.users.pop(old)
开发者ID:sopel-irc,项目名称:sopel,代码行数:32,代码来源:coretasks.py


示例8: track_modes

def track_modes(bot, trigger):
    """Track usermode changes and keep our lists of ops up to date."""
    # Mode message format: <channel> *( ( "-" / "+" ) *<modes> *<modeparams> )
    channel = Identifier(trigger.args[0])
    line = trigger.args[1:]

    # If the first character of where the mode is being set isn't a #
    # then it's a user mode, not a channel mode, so we'll ignore it.
    if channel.is_nick():
        return

    mapping = {'v': sopel.module.VOICE,
               'h': sopel.module.HALFOP,
               'o': sopel.module.OP,
               'a': sopel.module.ADMIN,
               'q': sopel.module.OWNER}

    modes = []
    for arg in line:
        if len(arg) == 0:
            continue
        if arg[0] in '+-':
            # There was a comment claiming IRC allows e.g. MODE +aB-c foo, but
            # I don't see it in any RFCs. Leaving in the extra parsing for now.
            sign = ''
            modes = []
            for char in arg:
                if char == '+' or char == '-':
                    sign = char
                else:
                    modes.append(sign + char)
        else:
            arg = Identifier(arg)
            for mode in modes:
                priv = bot.channels[channel].privileges.get(arg, 0)
                # Log a warning if the two privilege-tracking data structures
                # get out of sync. That should never happen.
                # This is a good place to verify that bot.channels is doing
                # what it's supposed to do before ultimately removing the old,
                # deprecated bot.privileges structure completely.
                ppriv = bot.privileges[channel].get(arg, 0)
                if priv != ppriv:
                    LOGGER.warning("Privilege data error! Please share Sopel's"
                                   "raw log with the developers, if enabled. "
                                   "(Expected {} == {} for {} in {}.)"
                                   .format(priv, ppriv, arg, channel))
                value = mapping.get(mode[1])
                if value is not None:
                    if mode[0] == '+':
                        priv = priv | value
                    else:
                        priv = priv & ~value
                    bot.privileges[channel][arg] = priv
                    bot.channels[channel].privileges[arg] = priv
开发者ID:neonobjclash,项目名称:sopel,代码行数:54,代码来源:coretasks.py


示例9: get_nick_value

 def get_nick_value(self, nick, key):
     """Retrieves the value for a given key associated with a nick."""
     nick = Identifier(nick)
     result = self.execute(
         'SELECT value FROM nicknames JOIN nick_values '
         'ON nicknames.nick_id = nick_values.nick_id '
         'WHERE slug = ? AND key = ?',
         [nick.lower(), key]
     ).fetchone()
     if result is not None:
         result = result[0]
     return _deserialize(result)
开发者ID:daniellawrence,项目名称:sopel,代码行数:12,代码来源:db.py


示例10: unalias_nick

    def unalias_nick(self, alias):
        """Removes an alias.

        Raises ValueError if there is not at least one other nick in the group.
        To delete an entire group, use `delete_group`.
        """
        alias = Identifier(alias)
        nick_id = self.get_nick_id(alias, False)
        count = self.execute('SELECT COUNT(*) FROM nicknames WHERE nick_id = ?',
                             [nick_id]).fetchone()[0]
        if count == 0:
            raise ValueError('Given alias is the only entry in its group.')
        self.execute('DELETE FROM nicknames WHERE slug = ?', [alias.lower()])
开发者ID:daniellawrence,项目名称:sopel,代码行数:13,代码来源:db.py


示例11: explode

def explode(bot, trigger):
    target = Identifier(trigger.group(3))
    orig_target = target
    with lock:
        if target.lower() not in BOMBS:  # nick change happened
            for nick in BOMBS.keys():
                if BOMBS[nick]['target'] == target:
                    target = Identifier(nick)
                    break
        bot.say(STRINGS['NEVER_TRIED'] % (target, BOMBS[target.lower()]['color']))
        kickboom(bot, trigger, target)
        BOMBS.pop(target.lower())
    timeouts = bot.db.get_nick_value(orig_target, 'bomb_timeouts') or 0
    bot.db.set_nick_value(orig_target, 'bomb_timeouts', timeouts + 1)
开发者ID:piagetbot,项目名称:sopel,代码行数:14,代码来源:bombbot.py


示例12: alias_nick

    def alias_nick(self, nick, alias):
        """Create an alias for a nick.

        Raises ValueError if the alias already exists. If nick does not already
        exist, it will be added along with the alias."""
        nick = Identifier(nick)
        alias = Identifier(alias)
        nick_id = self.get_nick_id(nick)
        sql = 'INSERT INTO nicknames (nick_id, slug, canonical) VALUES (?, ?, ?)'
        values = [nick_id, alias.lower(), alias]
        try:
            self.execute(sql, values)
        except sqlite3.IntegrityError as e:
            raise ValueError('Alias already exists. {0}'.format(e))
开发者ID:daniellawrence,项目名称:sopel,代码行数:14,代码来源:db.py


示例13: votemode

def votemode(bot, trigger, mode):
    make_user_active(bot, trigger)
    channel = trigger.sender
    account = trigger.account
    if account is None:
        bot.say("You must be authed to use this command")
        return
    if bot.privileges[trigger.sender][bot.nick] < OP:
        return bot.reply("I'm not a channel operator!")
    quota = calculate_quota(bot, trigger, bot.memory['mode_threshold'][mode])
    # This isn't per user but it's probably an OK heuristic
    if datetime.now() - bot.memory['last_vote'] > timedelta(minutes=5):
        clear_votes(bot)
    # Quota is 50% of active users plus one
    if trigger.group(2):
        target = Identifier(str(trigger.group(2)).split()[0].strip().lower())
        if not target.is_nick():
            return bot.reply("That is not a valid nick")
        if target not in bot.privileges[channel]:
            return bot.reply("I don't see %s." % target)
        target_privs = bot.privileges[channel][target]
        if target_privs > 0:
            return bot.reply("You cannot vote" + mode + " privileged users")

        if target in bot.memory['votes'][mode]:
            if str(account) not in bot.memory['votes'][mode][target]:
                bot.memory['votes'][mode][target].append(str(account))
        else:
            bot.memory['votes'][mode][target] = [str(account)]

        bot.reply("Vote recorded. (%s more votes for action)" % str(max(0, quota - len(bot.memory['votes'][mode][target])+1)))

        if len(bot.memory['votes'][mode][target]) > quota:
            bot.memory['vote_methods'][mode](bot, channel, target)
        bot.memory['last_vote'] = datetime.now()
    elif mode == "registered" or mode == "moderated":
        if str(account) not in bot.memory['votes'][mode]:
            bot.memory['votes'][mode].append(str(account))
        else:
            bot.memory['votes'][mode] = [str(account)]
        bot.reply("Vote recorded. (%s more votes for action)" % str(max(0, quota - len(bot.memory['votes'][mode])+1)))
        if len(bot.memory['votes'][mode]) > quota:
            bot.memory['vote_methods'][mode](bot, channel)
        bot.memory['last_vote'] = datetime.now()
    else:
        bot.say("Current active vote%s (%s needed to %s): " % (mode, str(quota + 1), mode))
        for ballot in bot.memory['votes'][mode]:
            bot.say("%s has %s %s votes." % (ballot, len(bot.memory['votes'][mode][ballot]), mode))
        return
开发者ID:aletheist,项目名称:willie-modules,代码行数:49,代码来源:votemode.py


示例14: write_log

def write_log(bot, event, channel):
    if bot.config.chanlogs2.allow_toggle:
        if not bot.db.get_channel_value(channel, 'logging'):
            return

    if not isinstance(channel, Identifier):
        channel = Identifier(channel)

    if channel.is_nick() and not bot.config.chanlogs2.privmsg:
        return  # Don't log if we are configured not to log PMs

    if bot.config.chanlogs2.backend == 'postgres':
        write_db_line(bot, event, channel)
    else:
        write_log_line(bot, event, channel)
开发者ID:maxpowa,项目名称:sopel-chanlogs2,代码行数:15,代码来源:chanlogs2.py


示例15: get_nick_value

 def get_nick_value(self, nick, key):
     """Retrieves the value for a given key associated with a nick."""
     nick = Identifier(nick)
     session = self.ssession()
     try:
         result = session.query(NickValues) \
             .filter(Nicknames.nick_id == NickValues.nick_id) \
             .filter(Nicknames.slug == nick.lower()) \
             .filter(NickValues.key == key) \
             .one_or_none()
         if result is not None:
             result = result.value
         return _deserialize(result)
     except SQLAlchemyError:
         session.rollback()
         raise
     finally:
         session.close()
开发者ID:sopel-irc,项目名称:sopel,代码行数:18,代码来源:db.py


示例16: track_modes

def track_modes(bot, trigger):
    """Track usermode changes and keep our lists of ops up to date."""
    # Mode message format: <channel> *( ( "-" / "+" ) *<modes> *<modeparams> )
    channel = Identifier(trigger.args[0])
    line = trigger.args[1:]

    # If the first character of where the mode is being set isn't a #
    # then it's a user mode, not a channel mode, so we'll ignore it.
    if channel.is_nick():
        return

    mapping = {
        "v": sopel.module.VOICE,
        "h": sopel.module.HALFOP,
        "o": sopel.module.OP,
        "a": sopel.module.ADMIN,
        "q": sopel.module.OWNER,
    }

    modes = []
    for arg in line:
        if len(arg) == 0:
            continue
        if arg[0] in "+-":
            # There was a comment claiming IRC allows e.g. MODE +aB-c foo, but
            # I don't see it in any RFCs. Leaving in the extra parsing for now.
            sign = ""
            modes = []
            for char in arg:
                if char == "+" or char == "-":
                    sign = char
                else:
                    modes.append(sign + char)
        else:
            arg = Identifier(arg)
            for mode in modes:
                priv = bot.privileges[channel].get(arg, 0)
                value = mapping.get(mode[1])
                if value is not None:
                    if mode[0] == "+":
                        priv = priv | value
                    else:
                        priv = priv & ~value
                    bot.privileges[channel][arg] = priv
开发者ID:duk3luk3,项目名称:sopel,代码行数:44,代码来源:coretasks.py


示例17: cancel_bomb

def cancel_bomb(bot, trigger):
    """
    Cancel the bomb placed on the specified player (can also be used by admins).
    """
    target = trigger.group(3) or None
    if not target:
        bot.reply(STRINGS['CANCEL_WHOM'])
        return
    target = Identifier(target)  # issue #24
    with lock:
        if target.lower() not in BOMBS:
            bot.reply(STRINGS['CANCEL_NO_BOMB'] % target)
            return
        if trigger.nick != BOMBS[target.lower()]['bomber'] and not trigger.admin:
            bot.reply(STRINGS['CANCEL_NO_PERMISSION'] % target)
            return
        bomber = BOMBS[target.lower()]['bomber']
        bombs_planted = bot.db.get_nick_value(bomber, 'bombs_planted') or 0
        bot.db.set_nick_value(bomber, 'bombs_planted', bombs_planted - 1)
        BOMBS.pop(target.lower())['timer'].cancel()
        bot.say(STRINGS['CANCEL_DONE'] % target)
开发者ID:piagetbot,项目名称:sopel,代码行数:21,代码来源:bombbot.py


示例18: cutwire

def cutwire(bot, trigger):
    """
    Tells sopel to cut a wire when you've been bombed.
    """
    global BOMBS
    target = Identifier(trigger.nick)
    if target == bot.nick:  # a parallel bot behind a bouncer (e.g. Bucket) can trigger this function (see #16)
        return
    with lock:
        if target.lower() != bot.nick.lower() and target.lower() not in BOMBS:
            bot.say(STRINGS['CUT_NO_BOMB'] % target)
            return
        if not trigger.group(3):
            bot.say(STRINGS['CUT_NO_WIRE'])
            return
        # Remove target from bomb list temporarily
        bomb = BOMBS.pop(target.lower())
        wirecut = trigger.group(3)
        if wirecut.lower() in ('all', 'all!'):
            bomb['timer'].cancel()  # defuse timer, execute premature detonation
            bot.say(STRINGS['CUT_ALL_WIRES'] % bomb['color'])
            kickboom(bot, trigger, target)
            alls = bot.db.get_nick_value(bomb['target'], 'bomb_alls') or 0
            bot.db.set_nick_value(bomb['target'], 'bomb_alls', alls + 1)
        elif wirecut.capitalize() not in bomb['wires']:
            bot.say(STRINGS['CUT_IMAGINARY'] % target)
            # Add the target back onto the bomb list
            BOMBS[target.lower()] = bomb
        elif wirecut.capitalize() == bomb['color']:
            bot.say(STRINGS['CUT_CORRECT'] % target)
            bomb['timer'].cancel()  # defuse bomb
            defuses = bot.db.get_nick_value(bomb['target'], 'bomb_defuses') or 0
            bot.db.set_nick_value(bomb['target'], 'bomb_defuses', defuses + 1)
        else:
            bomb['timer'].cancel()  # defuse timer, execute premature detonation
            bot.say(STRINGS['CUT_WRONG'] % bomb['color'])
            kickboom(bot, trigger, target)
            wrongs = bot.db.get_nick_value(bomb['target'], 'bomb_wrongs') or 0
            bot.db.set_nick_value(bomb['target'], 'bomb_wrongs', wrongs + 1)
开发者ID:piagetbot,项目名称:sopel,代码行数:39,代码来源:bombbot.py


示例19: unalias_nick

    def unalias_nick(self, alias):
        """Removes an alias.

        Raises ValueError if there is not at least one other nick in the group.
        To delete an entire group, use `delete_group`.
        """
        alias = Identifier(alias)
        nick_id = self.get_nick_id(alias, False)
        session = self.ssession()
        try:
            count = session.query(Nicknames) \
                .filter(Nicknames.nick_id == nick_id) \
                .count()
            if count <= 1:
                raise ValueError('Given alias is the only entry in its group.')
            session.query(Nicknames).filter(Nicknames.slug == alias.lower()).delete()
            session.commit()
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()
开发者ID:sopel-irc,项目名称:sopel,代码行数:22,代码来源:db.py


示例20: kick

def kick(bot, trigger):
    """
    Kick a user from the channel.
    """
    if bot.privileges[trigger.sender][bot.nick] < HALFOP:
        return bot.reply("I'm not a channel operator!")
    text = trigger.group().split()
    argc = len(text)
    if argc < 2:
        return
    opt = Identifier(text[1])
    nick = opt
    channel = trigger.sender
    reasonidx = 2
    if not opt.is_nick():
        if argc < 3:
            return
        nick = text[2]
        channel = opt
        reasonidx = 3
    reason = ' '.join(text[reasonidx:])
    if nick != bot.config.core.nick:
        bot.write(['KICK', channel, nick], reason)
开发者ID:Cnwauche,项目名称:sopel,代码行数:23,代码来源:adminchannel.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python time.format_time函数代码示例发布时间:2022-05-27
下一篇:
Python tools.stderr函数代码示例发布时间: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