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

Python callbacks.tokenize函数代码示例

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

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



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

示例1: _runCommandFunction

 def _runCommandFunction(self, irc, msg, command):
     """Run a command from message, as if command was sent over IRC."""
     tokens = callbacks.tokenize(command)        
     try:
         self.Proxy(irc.irc, msg, tokens)
     except Exception, e:
         log.exception('Uncaught exception in function called by MessageParser:')
开发者ID:mazaclub,项目名称:mazabot-core,代码行数:7,代码来源:plugin.py


示例2: doPrivmsg

 def doPrivmsg(self, irc, msg):
     if self.commandCalled:
         self.commandCalled = False
         return
     channel = msg.args[0]
     Owner = irc.getCallback('Owner')
     observers = self.registryValue('observers')
     active = self.registryValue('observers.active', channel)
     for name in active:
         if name not in observers:
             self.log.error('Active observers for %s include an '
                            'invalid observer: %s.', channel, name)
             continue
         observer = self.registryValue('observers.%s' % name, value=False)
         probability = observer.probability()
         if random.random() > probability:
             continue
         r = observer() # The regexp.
         m = r.search(msg.args[1])
         if m is not None:
             command = observer.command()
             groups = list(m.groups())
             groups.insert(0, m.group(0))
             for (i, group) in enumerate(groups):
                 command = command.replace('$%s' % i, group)
             tokens = callbacks.tokenize(command, channel=channel)
             Owner.processTokens(irc, msg, tokens)
开发者ID:Affix,项目名称:Fedbot,代码行数:27,代码来源:plugin.py


示例3: handle

    def handle(self):
        def hash_(data):
            return hashlib.sha1(str(time.time()) + data).hexdigest()
        self.request.settimeout(0.5)
        currentLine = ''
        prefix = 'a%s!%[email protected]%s.supybot-gui' % tuple([hash_(x)[0:6] for x in 'abc'])
        while self.server.enabled:
            if not '\n' in currentLine:
                try:
                    data = self.request.recv(4096)
                except socket.timeout:
                    time.sleep(0.1) # in case of odd problem
                    continue
            if not data: # Server closed connection
                return
            if '\n' in data:
                splitted = (currentLine + data).split('\n')
                currentLine = splitted[0]
                nextLines = '\n'.join(splitted[1:])
            else:
                continue
            splitted = currentLine.split(': ')
            hash_, command = splitted[0], ': '.join(splitted[1:])

            tokens = callbacks.tokenize(command)
            fakeIrc = FakeIrc(self.server._irc)
            msg = ircmsgs.privmsg(self.server._irc.nick, currentLine, prefix)
            self.server._plugin.Proxy(fakeIrc, msg, tokens)

            self.request.send('%s: %s\n' % (hash_, fakeIrc.message))
            currentLine = nextLines
开发者ID:AlanBell,项目名称:Supybot-plugins,代码行数:31,代码来源:plugin.py


示例4: cerror

    def cerror(self, irc, msg, args, testcommand):
        """<testcommand>

        Runs <testcommand> and returns true if it raises an error;
        false otherwise.
        """
        tokens = callbacks.tokenize(testcommand)
        InvalidCommand = collections.namedtuple('InvalidCommand',
                'command')
        replies = []
        errors = []
        class ErrorReportingProxy(self.Proxy):
            def reply(self2, s, *args, **kwargs):
                replies.append(s)
            def error(self2, s, Raise=False, *args, **kwargs):
                errors.append(s)
                if Raise:
                    raise ArgumentError
            def _callInvalidCommands(self2):
                errors.append(InvalidCommand(self2.args))
            def evalArgs(self2):
                # We don't want the replies in the nested command to
                # be stored here.
                super(ErrorReportingProxy, self2).evalArgs(withClass=self.Proxy)

        try:
            ErrorReportingProxy(irc.irc, msg, tokens)
        except callbacks.ArgumentError as e:
            pass
        # TODO: do something with the results
        if errors:
            irc.reply('true')
        else:
            irc.reply('false')
开发者ID:ElectroCode,项目名称:Limnoria,代码行数:34,代码来源:plugin.py


示例5: _runCommandFunction

 def _runCommandFunction(self, irc, msg, command):
     """Run a command from message, as if command was sent over IRC."""
     tokens = callbacks.tokenize(command)
     try:
         self.Proxy(irc.irc, msg, tokens)
     except Exception as e:
         self.log.exception('Uncaught exception in requested function:')
开发者ID:ElectroCode,项目名称:Limnoria,代码行数:7,代码来源:plugin.py


示例6: doPrivmsg

 def doPrivmsg(self, irc, msg):
     assert self is irc.callbacks[0], \
            'Owner isn\'t first callback: %r' % irc.callbacks
     if ircmsgs.isCtcp(msg):
         return
     s = callbacks.addressed(irc.nick, msg)
     if s:
         ignored = ircdb.checkIgnored(msg.prefix)
         if ignored:
             self.log.info('Ignoring command from %s.', msg.prefix)
             return
         maximum = conf.supybot.abuse.flood.command.maximum()
         self.commands.enqueue(msg)
         if conf.supybot.abuse.flood.command() \
            and self.commands.len(msg) > maximum \
            and not ircdb.checkCapability(msg.prefix, 'trusted'):
             punishment = conf.supybot.abuse.flood.command.punishment()
             banmask = ircutils.banmask(msg.prefix)
             self.log.info('Ignoring %s for %s seconds due to an apparent '
                           'command flood.', banmask, punishment)
             ircdb.ignores.add(banmask, time.time() + punishment)
             irc.reply('You\'ve given me %s commands within the last '
                       'minute; I\'m now ignoring you for %s.' %
                       (maximum,
                        utils.timeElapsed(punishment, seconds=False)))
             return
         try:
             tokens = callbacks.tokenize(s, channel=msg.args[0])
             self.Proxy(irc, msg, tokens)
         except SyntaxError, e:
             irc.queueMsg(callbacks.error(msg, str(e)))
开发者ID:boamaod,项目名称:Limnoria,代码行数:31,代码来源:plugin.py


示例7: _slot

    def _slot(self, lastItem):
        irc = lastItem.irc
        msg = lastItem.msg
        channel = lastItem.channel
        prefix = lastItem.prefix
        nick = prefix.split('!')[0]
        kind = lastItem.kind

        try:
            ircdb.users.getUser(msg.prefix) # May raise KeyError
            capability = self.registryValue('exempt')
            if capability:
                if ircdb.checkCapability(msg.prefix, capability):
                    return
        except KeyError:
            pass
        punishment = self.registryValue('%s.punishment' % kind, channel)
        reason = _('%s flood detected') % kind
        if punishment == 'kick':
            msg = ircmsgs.kick(channel, nick, reason)
            irc.queueMsg(msg)
        elif punishment == 'ban':
            msg = ircmsgs.ban(channel, prefix)
            irc.queueMsg(msg)
        elif punishment == 'kban':
            msg = ircmsgs.kick(channel, nick, reason)
            irc.queueMsg(msg)
            msg = ircmsgs.ban(channel, prefix)
            irc.queueMsg(msg)
        elif punishment.startswith('mode'):
            msg = ircmsgs.mode(channel, punishment[len('mode'):])
            irc.queueMsg(msg)
        elif punishment.startswith('command '):
            tokens = callbacks.tokenize(punishment[len('command '):])
            self.Proxy(irc, msg, tokens)
开发者ID:v2k,项目名称:Supybot-plugins,代码行数:35,代码来源:plugin.py


示例8: _makeCommandFunction

 def _makeCommandFunction(self, irc, msg, command, remove=True):
     """Makes a function suitable for scheduling from command."""
     tokens = callbacks.tokenize(command)
     def f():
         if remove:
             del self.events[str(f.eventId)]
         self.Proxy(irc.irc, msg, tokens)
     return f
开发者ID:AssetsIncorporated,项目名称:Limnoria,代码行数:8,代码来源:plugin.py


示例9: _run

 def _run(self, irc, msg, triggerName):
     command = self.registryValue('triggers.%s' % triggerName, msg.args[0])
     if command == '':
         return
     tokens = callbacks.tokenize(command)
     try:
         self.Proxy(irc.irc, msg, tokens)
     except Exception, e:
         log.exception('Error occured while running triggered command:')
开发者ID:Azelphur,项目名称:Supybot-plugins,代码行数:9,代码来源:plugin.py


示例10: fakehostmask

    def fakehostmask(self, irc, msg, args, hostmask, command):
        """<hostmask> <command>

        Runs <command> as if you were wearing the <hostmask>. Of course, usage
        of the command is restricted to the owner."""
        log.info('fakehostmask used to run "%s" as %s' % (command, hostmask))
        msg.prefix = hostmask
        tokens = callbacks.tokenize(command)
        self.Proxy(irc.irc, msg, tokens)
开发者ID:Albnetwork,项目名称:Supybot-plugins,代码行数:9,代码来源:plugin.py


示例11: act

	def act (self, irc, msg, channel, command, owner):
		tokens = callbacks.tokenize(command)
		#if ircdb.checkCapability(owner, 'owner') or ircdb.checkCapability(owner, '%s,op' % channel):
		#	owner = irc.prefix
		#elif ircdb.checkCapability(irc.prefix, 'owner') or ircdb.checkCapability(irc.prefix, '%s,op' % channel):
		#	owner = irc.prefix
		msg.command = 'PRIVMSG'
		(n,i,h) = ircutils.splitHostmask(owner)
		msg.prefix = ircutils.joinHostmask(irc.nick,i,h)
		self.Proxy(irc.irc, msg, tokens)
开发者ID:ncoevoet,项目名称:ChanReg,代码行数:10,代码来源:plugin.py


示例12: hadoken

    def hadoken(self, irc, msg, args):
        """takes no arguments

        Let everyone know that they should come get beat up by Guile."""
        users = {'Newfie':'@HWHQNewfie', 'C4':'@ceephour', 'that_guy':'@nliadm'}
        twitterstr = 'post HADOKEN! ' + " ".join(users.values())
        ircstring = 'MY FIGHT MONEY! ' + " ".join(users.keys())

        irc.reply(ircstring)
        self.Proxy(irc.irc, msg, callbacks.tokenize(twitterstr))
开发者ID:hdonnay,项目名称:supybot-lebowski,代码行数:10,代码来源:plugin.py


示例13: _createPrivmsg

        def _createPrivmsg(self, irc, channel, payload, event, hidden=None):
            bold = ircutils.bold

            format_ = self.plugin.registryValue('format.%s' % event, channel)
            if not format_.strip():
                return
            repl = flatten_subdicts(payload)
            for (key, value) in dict(repl).items():
                if isinstance(value, basestring) and \
                        value.startswith(('http://', 'https://')):
                    host = urlparse(value).netloc
                    # NOTE: Shortening api.github.com URLs causes too much
                    # overhead and it becomes really slow. At some point, we
                    # should probably check which keys are actually referenced
                    # in the format string and only shorten those.
                    #if host == 'github.com' or host.endswith('.github.com'):
                    if host == 'github.com':
                        url = self._shorten_url(value)
                        if url:
                            repl[key + '__tiny'] = url
                        else:
                            repl[key + '__tiny'] = value
                    else:
                        repl[key + '__tiny'] = value
                elif isinstance(value, basestring) and \
                        re.search(r'^[a-f0-9]{40}$', value):
                    # Check if it looks like a commit ID, because there are key
                    # names such as "before" and "after" containing commit IDs.
                    repl[key + '__short'] = value[0:7]
                elif key == 'commits':
                    repl['__num_commits'] = len(value)
                elif key.endswith('ref'):
                    try:
                        repl[key + '__branch'] = value.split('/', 2)[2] \
                                if value else None
                    except IndexError:
                        pass
                elif isinstance(value, str) or \
                        (sys.version_info[0] < 3 and isinstance(value, unicode)):
                    repl[key + '__firstline'] = value.split('\n', 1)[0]
            repl.update({'__hidden': hidden or 0})
            #if hidden is not None:
            #    s += _(' (+ %i hidden commits)') % hidden
            #if sys.version_info[0] < 3:
            #        s = s.encode('utf-8')
            tokens = callbacks.tokenize(format_)
            if not tokens:
                return
            fake_msg = ircmsgs.IrcMsg(command='PRIVMSG',
                    args=(channel, 'GITHUB'), prefix='[email protected]',
                    reply_env=repl)
            try:
                self.plugin.Proxy(irc, fake_msg, tokens)
            except Exception as  e:
                self.plugin.log.exception('Error occured while running triggered command:')
开发者ID:cripperz,项目名称:Supybot-plugins,代码行数:55,代码来源:plugin.py


示例14: _slot

    def _slot(self, lastItem):
        irc = lastItem.irc
        msg = lastItem.msg
        channel = lastItem.channel
        prefix = lastItem.prefix
        nick = prefix.split('!')[0]
        kind = lastItem.kind

        if not ircutils.isChannel(channel):
                return
        if not self.registryValue('enable', channel):
            return

        try:
            ircdb.users.getUser(msg.prefix) # May raise KeyError
            capability = self.registryValue('exempt')
            if capability:
                if ircdb.checkCapability(msg.prefix,
                        ','.join([channel, capability])):
                    self.log.info('Not punishing %s: they are immune.' %
                            prefix)
                    return
        except KeyError:
            pass
        punishment = self.registryValue('%s.punishment' % kind, channel)
        reason = _('%s flood detected') % kind

        if punishment == 'kick':
            self._eventCatcher(irc, msg, 'kicked', kicked_prefix=prefix)
        if kind == 'kicked':
            reason = _('You exceeded your kick quota.')

        banmaskstyle = conf.supybot.protocols.irc.banmask
        banmask = banmaskstyle.makeBanmask(prefix)
        if punishment == 'kick':
            msg = ircmsgs.kick(channel, nick, reason)
            irc.queueMsg(msg)
        elif punishment == 'ban':
            msg = ircmsgs.ban(channel, banmask)
            irc.queueMsg(msg)
        elif punishment == 'kban':
            msg = ircmsgs.ban(channel, banmask)
            irc.queueMsg(msg)
            msg = ircmsgs.kick(channel, nick, reason)
            irc.queueMsg(msg)
        elif punishment.startswith('mode'):
            msg = ircmsgs.mode(channel, punishment[len('mode'):])
            irc.queueMsg(msg)
        elif punishment.startswith('umode'):
            msg = ircmsgs.mode(channel, (punishment[len('umode'):], nick))
            irc.queueMsg(msg)
        elif punishment.startswith('command '):
            tokens = callbacks.tokenize(punishment[len('command '):])
            self.Proxy(irc, msg, tokens)
开发者ID:TameTimmah,项目名称:Supybot-plugins,代码行数:54,代码来源:plugin.py


示例15: __getitem__

 def __getitem__(self, k):
     try:
         return self.d[k]
     except KeyError:
         if self.cmd_exists(k):
             cmd = list(map(LispSymbol, callbacks.tokenize(k)))
             def wrapper(self, ctx, args):
                 return lisp_cmd(self, ctx, cmd + args)
             return LispBuiltin(wrapper, k)
         else:
             raise
开发者ID:benzrf,项目名称:Lispnoria,代码行数:11,代码来源:parthial_ext.py


示例16: _run

 def _run(self, irc, msg, triggerName, channel=None):
     if channel is None:
         channel = msg.args[0]
     command = self.registryValue('triggers.%s' % triggerName, channel)
     if command == '':
         return
     tokens = callbacks.tokenize(command)
     try:
         msg.args = (channel,) + msg.args[1:]
         self.Proxy(irc.irc, msg, tokens)
     except Exception, e:
         self.log.exception('Error occured while running triggered command:')
开发者ID:Erika-Mustermann,项目名称:Supybot-plugins,代码行数:12,代码来源:plugin.py


示例17: apply

    def apply(self, irc, msg, args, command, rest):
        """<command> <text>

        Tokenizes <text> and calls <command> with the resulting arguments.
        """
        args = [token and token or '""' for token in rest]
        text = ' '.join(args)
        commands = command.split()
        commands = map(callbacks.canonicalName, commands)
        tokens = callbacks.tokenize(text)
        allTokens = commands + tokens
        self.Proxy(irc, msg, allTokens)
开发者ID:GlitterCakes,项目名称:PoohBot,代码行数:12,代码来源:plugin.py


示例18: f

    def f(self, irc, msg, args):
        alias = original.replace("$nick", msg.nick)
        if "$channel" in original:
            channel = getChannel(msg, args)
            alias = alias.replace("$channel", channel)
        tokens = callbacks.tokenize(alias)
        if not wildcard and biggestDollar or biggestAt:
            args = getArgs(args, required=biggestDollar, optional=biggestAt)
            # Gotta have a mutable sequence (for replace).
            if biggestDollar + biggestAt == 1:  # We got a string, no tuple.
                args = [args]

        def regexpReplace(m):
            idx = int(m.group(1))
            return args[idx - 1]

        def replace(tokens, replacer):
            for (i, token) in enumerate(tokens):
                if isinstance(token, list):
                    replace(token, replacer)
                else:
                    tokens[i] = replacer(token)

        replace(tokens, lambda s: dollarRe.sub(regexpReplace, s))
        if biggestAt:
            assert not wildcard
            args = args[biggestDollar:]
            replace(tokens, lambda s: atRe.sub(regexpReplace, s))
        if wildcard:
            assert not biggestAt
            # Gotta remove the things that have already been subbed in.
            i = biggestDollar
            while i:
                args.pop(0)
                i -= 1

            def everythingReplace(tokens):
                for (i, token) in enumerate(tokens):
                    if isinstance(token, list):
                        if everythingReplace(token):
                            return
                    if token == "$*":
                        tokens[i : i + 1] = args
                        return True
                    elif "$*" in token:
                        tokens[i] = token.replace("$*", " ".join(args))
                        return True
                return False

            everythingReplace(tokens)
        self.Proxy(irc, msg, tokens)
开发者ID:ephemey,项目名称:ephesite,代码行数:51,代码来源:plugin.py


示例19: f

 def f(irc, msg, args):
     tokens = callbacks.tokenize(original)
     if biggestDollar or biggestAt:
         args = getArgs(args, required=biggestDollar, optional=biggestAt,
                         wildcard=wildcard)
     remaining_len = conf.supybot.reply.maximumLength()
     for (i, arg) in enumerate(args):
         if remaining_len < len(arg):
             arg = arg[0:remaining_len]
             args[i+1:] = []
             break
         remaining_len -= len(arg)
     def regexpReplace(m):
         idx = int(m.group(1))
         return args[idx-1]
     def replace(tokens, replacer):
         for (i, token) in enumerate(tokens):
             if isinstance(token, list):
                 replace(token, replacer)
             else:
                 tokens[i] = replacer(token)
     replace(tokens, lambda s: dollarRe.sub(regexpReplace, s))
     if biggestAt:
         assert not wildcard
         args = args[biggestDollar:]
         replace(tokens, lambda s: atRe.sub(regexpReplace, s))
     if wildcard:
         assert not biggestAt
         # Gotta remove the things that have already been subbed in.
         i = biggestDollar
         args[:] = args[i:]
         def everythingReplace(tokens):
             skip = 0
             for (i, token) in enumerate(tokens):
                 if skip:
                     skip -= 1
                     continue
                 if isinstance(token, list):
                     everythingReplace(token)
                 if token == '$*':
                     tokens[i:i+1] = args
                     skip = len(args)-1 # do not make replacements in
                                        # tokens we just added
                 elif '$*' in token:
                     tokens[i] = token.replace('$*', ' '.join(args))
         everythingReplace(tokens)
     maxNesting = conf.supybot.commands.nested.maximum()
     if maxNesting and irc.nested+1 > maxNesting:
         irc.error(_('You\'ve attempted more nesting than is '
               'currently allowed on this bot.'), Raise=True)
     self.Proxy(irc, msg, tokens, nested=irc.nested+1)
开发者ID:Hoaas,项目名称:Limnoria,代码行数:51,代码来源:plugin.py


示例20: f

 def f(self, irc, msg, args):
     alias = original.replace('$nick', msg.nick)
     if '$channel' in original:
         channel = getChannel(msg, args)
         alias = alias.replace('$channel', channel)
     tokens = callbacks.tokenize(alias)
     if biggestDollar or biggestAt:
         args = getArgs(args, required=biggestDollar, optional=biggestAt,
                         wildcard=wildcard)
     max_len = conf.supybot.reply.maximumLength()
     args = list([x[:max_len] for x in args])
     def regexpReplace(m):
         idx = int(m.group(1))
         return args[idx-1]
     def replace(tokens, replacer):
         for (i, token) in enumerate(tokens):
             if isinstance(token, list):
                 replace(token, replacer)
             else:
                 tokens[i] = replacer(token)
     replace(tokens, lambda s: dollarRe.sub(regexpReplace, s))
     if biggestAt:
         assert not wildcard
         args = args[biggestDollar:]
         replace(tokens, lambda s: atRe.sub(regexpReplace, s))
     if wildcard:
         assert not biggestAt
         # Gotta remove the things that have already been subbed in.
         i = biggestDollar
         while i:
             args.pop(0)
             i -= 1
         def everythingReplace(tokens):
             for (i, token) in enumerate(tokens):
                 if isinstance(token, list):
                     if everythingReplace(token):
                         return
                 if token == '$*':
                     tokens[i:i+1] = args
                     return True
                 elif '$*' in token:
                     tokens[i] = token.replace('$*', ' '.join(args))
                     return True
             return False
         everythingReplace(tokens)
     maxNesting = conf.supybot.commands.nested.maximum()
     if maxNesting and irc.nested+1 > maxNesting:
         irc.error(_('You\'ve attempted more nesting than is '
               'currently allowed on this bot.'), Raise=True)
     self.Proxy(irc, msg, tokens, nested=irc.nested+1)
开发者ID:limebot,项目名称:LimeBot,代码行数:50,代码来源:plugin.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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