本文整理汇总了Python中supybot.callbacks.tokenize函数的典型用法代码示例。如果您正苦于以下问题:Python tokenize函数的具体用法?Python tokenize怎么用?Python tokenize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了tokenize函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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:')
示例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)
示例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
示例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')
示例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:')
示例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)))
示例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)
示例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
示例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:')
示例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)
示例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)
示例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))
示例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:')
示例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)
示例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