First :D
This commit is contained in:
commit
37588421f3
|
@ -0,0 +1,22 @@
|
|||
/*
|
||||
* CloudBot 3.2DEV
|
||||
* www.dempltr.com
|
||||
*
|
||||
* Copyright Luke Rogers 2011
|
||||
|
||||
This file is part of CloudBot.
|
||||
|
||||
CloudBot is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
CloudBot is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with CloudBot. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
*/
|
|
@ -0,0 +1,17 @@
|
|||
= CloudBot - A fork of SkyBot =
|
||||
|
||||
==Goals==
|
||||
* simplicity
|
||||
** little boilerplate
|
||||
** minimal magic
|
||||
* power
|
||||
** multithreading
|
||||
** automatic reloading
|
||||
** extensibility
|
||||
|
||||
==Features==
|
||||
* Multithreaded dispatch and the ability to connect to multiple networks at a time.
|
||||
* Easy plugin development with automatic reloading and a simple hooking API.
|
||||
|
||||
==Requirements==
|
||||
Skybot runs on Python SOMESHIT. Many of the plugins require [[http://codespeak.net/lxml/|lxml]] and BeautifulSoup. It is developed on Ubuntu 11.10 with Python LOLWUT.
|
|
@ -0,0 +1,64 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
import os
|
||||
import Queue
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path += ['plugins'] # so 'import hook' works without duplication
|
||||
sys.path += ['lib']
|
||||
os.chdir(sys.path[0] or '.') # do stuff relative to the install directory
|
||||
|
||||
|
||||
class Bot(object):
|
||||
pass
|
||||
|
||||
|
||||
bot = Bot()
|
||||
|
||||
print 'Loading plugins'
|
||||
|
||||
# bootstrap the reloader
|
||||
eval(compile(open(os.path.join('core', 'reload.py'), 'U').read(),
|
||||
os.path.join('core', 'reload.py'), 'exec'))
|
||||
reload(init=True)
|
||||
|
||||
config()
|
||||
if not hasattr(bot, 'config'):
|
||||
exit()
|
||||
|
||||
print 'Connecting to IRC'
|
||||
|
||||
bot.conns = {}
|
||||
|
||||
try:
|
||||
for name, conf in bot.config['connections'].iteritems():
|
||||
if conf.get('ssl'):
|
||||
bot.conns[name] = SSLIRC(conf['server'], conf['nick'], conf=conf,
|
||||
port=conf.get('port', 6667), channels=conf['channels'],
|
||||
ignore_certificate_errors=conf.get('ignore_cert', True))
|
||||
else:
|
||||
bot.conns[name] = IRC(conf['server'], conf['nick'], conf=conf,
|
||||
port=conf.get('port', 6667), channels=conf['channels'])
|
||||
except Exception, e:
|
||||
print 'ERROR: malformed config file', e
|
||||
sys.exit()
|
||||
|
||||
bot.persist_dir = os.path.abspath('persist')
|
||||
if not os.path.exists(bot.persist_dir):
|
||||
os.mkdir(bot.persist_dir)
|
||||
|
||||
print 'Running main loop'
|
||||
|
||||
while True:
|
||||
reload() # these functions only do things
|
||||
config() # if changes have occured
|
||||
|
||||
for conn in bot.conns.itervalues():
|
||||
try:
|
||||
out = conn.out.get_nowait()
|
||||
main(conn, out)
|
||||
except Queue.Empty:
|
||||
pass
|
||||
while all(conn.out.empty() for conn in bot.conns.itervalues()):
|
||||
time.sleep(.1)
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"connections":
|
||||
{
|
||||
"CONNECTION_NAME":
|
||||
{
|
||||
"server": "",
|
||||
"nick": "",
|
||||
"user": "",
|
||||
"realname": "",
|
||||
"nickserv_password": "",
|
||||
"channels": ["#CHANNEL","#CHANNEL"]
|
||||
}
|
||||
},
|
||||
"disabled_plugins": [],
|
||||
"disabled_commands": [],
|
||||
"acls": {},
|
||||
"api_keys": {"geoip":"NULL","mc":["USER","PASS"]},
|
||||
"censored_strings":
|
||||
[
|
||||
"DCC SEND",
|
||||
"1nj3ct",
|
||||
"thewrestlinggame",
|
||||
"startkeylogger",
|
||||
"hybux",
|
||||
"\\0",
|
||||
"\\x01",
|
||||
"!coz",
|
||||
"!tell /x"
|
||||
],
|
||||
"admins": ["TheLuke","Luke"]
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
import inspect
|
||||
import json
|
||||
import os
|
||||
|
||||
|
||||
def save(conf):
|
||||
json.dump(conf, open('config', 'w'), sort_keys=True, indent=2)
|
||||
|
||||
if not os.path.exists('config'):
|
||||
open('config', 'w').write(inspect.cleandoc(
|
||||
r'''
|
||||
{
|
||||
"connections":
|
||||
{
|
||||
"local irc":
|
||||
{
|
||||
"server": "localhost",
|
||||
"nick": "skybot",
|
||||
"channels": ["#test"]
|
||||
}
|
||||
},
|
||||
"disabled_plugins": [],
|
||||
"disabled_commands": [],
|
||||
"acls": {},
|
||||
"api_keys": {},
|
||||
"censored_strings":
|
||||
[
|
||||
"DCC SEND",
|
||||
"1nj3ct",
|
||||
"thewrestlinggame",
|
||||
"startkeylogger",
|
||||
"hybux",
|
||||
"\\0",
|
||||
"\\x01",
|
||||
"!coz",
|
||||
"!tell /x"
|
||||
],
|
||||
"admins": []
|
||||
}''') + '\n')
|
||||
|
||||
|
||||
def config():
|
||||
# reload config from file if file has changed
|
||||
config_mtime = os.stat('config').st_mtime
|
||||
if bot._config_mtime != config_mtime:
|
||||
try:
|
||||
bot.config = json.load(open('config'))
|
||||
bot._config_mtime = config_mtime
|
||||
except ValueError, e:
|
||||
print 'ERROR: malformed config!', e
|
||||
|
||||
|
||||
bot._config_mtime = 0
|
|
@ -0,0 +1,25 @@
|
|||
import os
|
||||
import sqlite3
|
||||
import thread
|
||||
|
||||
threaddbs={}
|
||||
|
||||
def get_db_connection(conn, name=''):
|
||||
"returns an sqlite3 connection to a persistent database"
|
||||
|
||||
if not name:
|
||||
name = '%s.%s.db' % (conn.nick, conn.server)
|
||||
|
||||
threadid = thread.get_ident()
|
||||
if name in threaddbs and threadid in threaddbs[name]:
|
||||
return threaddbs[name][threadid]
|
||||
filename = os.path.join(bot.persist_dir, name)
|
||||
|
||||
db = sqlite3.connect(filename, timeout=10)
|
||||
if name in threaddbs:
|
||||
threaddbs[name][threadid] = db
|
||||
else:
|
||||
threaddbs[name] = {threadid: db}
|
||||
return db
|
||||
|
||||
bot.get_db_connection = get_db_connection
|
|
@ -0,0 +1,250 @@
|
|||
import re
|
||||
import socket
|
||||
import time
|
||||
import thread
|
||||
import Queue
|
||||
|
||||
from ssl import wrap_socket, CERT_NONE, CERT_REQUIRED, SSLError
|
||||
|
||||
|
||||
def decode(txt):
|
||||
for codec in ('utf-8', 'iso-8859-1', 'shift_jis', 'cp1252'):
|
||||
try:
|
||||
return txt.decode(codec)
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return txt.decode('utf-8', 'ignore')
|
||||
|
||||
|
||||
def censor(text):
|
||||
replacement = '[censored]'
|
||||
if 'censored_strings' in bot.config:
|
||||
words = map(re.escape, bot.config['censored_strings'])
|
||||
regex = re.compile('(%s)' % "|".join(words))
|
||||
text = regex.sub(replacement, text)
|
||||
return text
|
||||
|
||||
|
||||
class crlf_tcp(object):
|
||||
"Handles tcp connections that consist of utf-8 lines ending with crlf"
|
||||
|
||||
def __init__(self, host, port, timeout=300):
|
||||
self.ibuffer = ""
|
||||
self.obuffer = ""
|
||||
self.oqueue = Queue.Queue() # lines to be sent out
|
||||
self.iqueue = Queue.Queue() # lines that were received
|
||||
self.socket = self.create_socket()
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.timeout = timeout
|
||||
|
||||
def create_socket(self):
|
||||
return socket.socket(socket.AF_INET, socket.TCP_NODELAY)
|
||||
|
||||
def run(self):
|
||||
self.socket.connect((self.host, self.port))
|
||||
thread.start_new_thread(self.recv_loop, ())
|
||||
thread.start_new_thread(self.send_loop, ())
|
||||
|
||||
def recv_from_socket(self, nbytes):
|
||||
return self.socket.recv(nbytes)
|
||||
|
||||
def get_timeout_exception_type(self):
|
||||
return socket.timeout
|
||||
|
||||
def handle_receive_exception(self, error, last_timestamp):
|
||||
if time.time() - last_timestamp > self.timeout:
|
||||
self.iqueue.put(StopIteration)
|
||||
self.socket.close()
|
||||
return True
|
||||
return False
|
||||
|
||||
def recv_loop(self):
|
||||
last_timestamp = time.time()
|
||||
while True:
|
||||
try:
|
||||
data = self.recv_from_socket(4096)
|
||||
self.ibuffer += data
|
||||
if data:
|
||||
last_timestamp = time.time()
|
||||
else:
|
||||
if time.time() - last_timestamp > self.timeout:
|
||||
self.iqueue.put(StopIteration)
|
||||
self.socket.close()
|
||||
return
|
||||
time.sleep(1)
|
||||
except (self.get_timeout_exception_type(), socket.error) as e:
|
||||
if self.handle_receive_exception(e, last_timestamp):
|
||||
return
|
||||
continue
|
||||
|
||||
while '\r\n' in self.ibuffer:
|
||||
line, self.ibuffer = self.ibuffer.split('\r\n', 1)
|
||||
self.iqueue.put(decode(line))
|
||||
|
||||
def send_loop(self):
|
||||
while True:
|
||||
line = self.oqueue.get().splitlines()[0][:500]
|
||||
print ">>> %r" % line
|
||||
self.obuffer += line.encode('utf-8', 'replace') + '\r\n'
|
||||
while self.obuffer:
|
||||
sent = self.socket.send(self.obuffer)
|
||||
self.obuffer = self.obuffer[sent:]
|
||||
|
||||
|
||||
class crlf_ssl_tcp(crlf_tcp):
|
||||
"Handles ssl tcp connetions that consist of utf-8 lines ending with crlf"
|
||||
def __init__(self, host, port, ignore_cert_errors, timeout=300):
|
||||
self.ignore_cert_errors = ignore_cert_errors
|
||||
crlf_tcp.__init__(self, host, port, timeout)
|
||||
|
||||
def create_socket(self):
|
||||
return wrap_socket(crlf_tcp.create_socket(self), server_side=False,
|
||||
cert_reqs=CERT_NONE if self.ignore_cert_errors else
|
||||
CERT_REQUIRED)
|
||||
|
||||
def recv_from_socket(self, nbytes):
|
||||
return self.socket.read(nbytes)
|
||||
|
||||
def get_timeout_exception_type(self):
|
||||
return SSLError
|
||||
|
||||
def handle_receive_exception(self, error, last_timestamp):
|
||||
# this is terrible
|
||||
if not "timed out" in error.args[0]:
|
||||
raise
|
||||
return crlf_tcp.handle_receive_exception(self, error, last_timestamp)
|
||||
|
||||
irc_prefix_rem = re.compile(r'(.*?) (.*?) (.*)').match
|
||||
irc_noprefix_rem = re.compile(r'()(.*?) (.*)').match
|
||||
irc_netmask_rem = re.compile(r':?([^!@]*)!?([^@]*)@?(.*)').match
|
||||
irc_param_ref = re.compile(r'(?:^|(?<= ))(:.*|[^ ]+)').findall
|
||||
|
||||
|
||||
class IRC(object):
|
||||
"handles the IRC protocol"
|
||||
#see the docs/ folder for more information on the protocol
|
||||
def __init__(self, server, nick, port=6667, channels=[], conf={}):
|
||||
self.channels = channels
|
||||
self.conf = conf
|
||||
self.server = server
|
||||
self.port = port
|
||||
self.nick = nick
|
||||
|
||||
self.out = Queue.Queue() # responses from the server are placed here
|
||||
# format: [rawline, prefix, command, params,
|
||||
# nick, user, host, paramlist, msg]
|
||||
self.connect()
|
||||
|
||||
thread.start_new_thread(self.parse_loop, ())
|
||||
|
||||
def create_connection(self):
|
||||
return crlf_tcp(self.server, self.port)
|
||||
|
||||
def connect(self):
|
||||
self.conn = self.create_connection()
|
||||
thread.start_new_thread(self.conn.run, ())
|
||||
self.set_pass(self.conf.get('server_password'))
|
||||
self.set_nick(self.nick)
|
||||
self.cmd("USER",
|
||||
[conf.get('user', 'skybot'), "3", "*", conf.get('realname',
|
||||
'Python bot - http://github.com/rmmh/skybot')])
|
||||
|
||||
def parse_loop(self):
|
||||
while True:
|
||||
msg = self.conn.iqueue.get()
|
||||
|
||||
if msg == StopIteration:
|
||||
self.connect()
|
||||
continue
|
||||
|
||||
if msg.startswith(":"): # has a prefix
|
||||
prefix, command, params = irc_prefix_rem(msg).groups()
|
||||
else:
|
||||
prefix, command, params = irc_noprefix_rem(msg).groups()
|
||||
nick, user, host = irc_netmask_rem(prefix).groups()
|
||||
paramlist = irc_param_ref(params)
|
||||
lastparam = ""
|
||||
if paramlist:
|
||||
if paramlist[-1].startswith(':'):
|
||||
paramlist[-1] = paramlist[-1][1:]
|
||||
lastparam = paramlist[-1]
|
||||
self.out.put([msg, prefix, command, params, nick, user, host,
|
||||
paramlist, lastparam])
|
||||
if command == "PING":
|
||||
self.cmd("PONG", paramlist)
|
||||
|
||||
def set_pass(self, password):
|
||||
if password:
|
||||
self.cmd("PASS", [password])
|
||||
|
||||
def set_nick(self, nick):
|
||||
self.cmd("NICK", [nick])
|
||||
|
||||
def join(self, channel):
|
||||
self.cmd("JOIN", [channel])
|
||||
|
||||
def msg(self, target, text):
|
||||
self.cmd("PRIVMSG", [target, text])
|
||||
|
||||
def cmd(self, command, params=None):
|
||||
if params:
|
||||
params[-1] = ':' + params[-1]
|
||||
self.send(command + ' ' + ' '.join(map(censor, params)))
|
||||
else:
|
||||
self.send(command)
|
||||
|
||||
def send(self, str):
|
||||
self.conn.oqueue.put(str)
|
||||
|
||||
|
||||
class FakeIRC(IRC):
|
||||
def __init__(self, server, nick, port=6667, channels=[], conf={}, fn=""):
|
||||
self.channels = channels
|
||||
self.conf = conf
|
||||
self.server = server
|
||||
self.port = port
|
||||
self.nick = nick
|
||||
|
||||
self.out = Queue.Queue() # responses from the server are placed here
|
||||
|
||||
self.f = open(fn, 'rb')
|
||||
|
||||
thread.start_new_thread(self.parse_loop, ())
|
||||
|
||||
def parse_loop(self):
|
||||
while True:
|
||||
msg = decode(self.f.readline()[9:])
|
||||
|
||||
if msg == '':
|
||||
print "!!!!DONE READING FILE!!!!"
|
||||
return
|
||||
|
||||
if msg.startswith(":"): # has a prefix
|
||||
prefix, command, params = irc_prefix_rem(msg).groups()
|
||||
else:
|
||||
prefix, command, params = irc_noprefix_rem(msg).groups()
|
||||
nick, user, host = irc_netmask_rem(prefix).groups()
|
||||
paramlist = irc_param_ref(params)
|
||||
lastparam = ""
|
||||
if paramlist:
|
||||
if paramlist[-1].startswith(':'):
|
||||
paramlist[-1] = paramlist[-1][1:]
|
||||
lastparam = paramlist[-1]
|
||||
self.out.put([msg, prefix, command, params, nick, user, host,
|
||||
paramlist, lastparam])
|
||||
if command == "PING":
|
||||
self.cmd("PONG", [params])
|
||||
|
||||
def cmd(self, command, params=None):
|
||||
pass
|
||||
|
||||
|
||||
class SSLIRC(IRC):
|
||||
def __init__(self, server, nick, port=6667, channels=[], conf={},
|
||||
ignore_certificate_errors=True):
|
||||
self.ignore_cert_errors = ignore_certificate_errors
|
||||
IRC.__init__(self, server, nick, port, channels, conf)
|
||||
|
||||
def create_connection(self):
|
||||
return crlf_ssl_tcp(self.server, self.port, self.ignore_cert_errors)
|
|
@ -0,0 +1,187 @@
|
|||
import thread
|
||||
import traceback
|
||||
|
||||
|
||||
thread.stack_size(1024 * 512) # reduce vm size
|
||||
|
||||
|
||||
class Input(dict):
|
||||
def __init__(self, conn, raw, prefix, command, params,
|
||||
nick, user, host, paraml, msg):
|
||||
|
||||
chan = paraml[0].lower()
|
||||
if chan == conn.nick.lower(): # is a PM
|
||||
chan = nick
|
||||
|
||||
def say(msg):
|
||||
conn.msg(chan, msg)
|
||||
|
||||
def reply(msg):
|
||||
if chan == nick: # PMs don't need prefixes
|
||||
conn.msg(chan, msg)
|
||||
else:
|
||||
conn.msg(chan, '(' + nick + ') ' + msg)
|
||||
|
||||
def pm(msg):
|
||||
conn.msg(nick, msg)
|
||||
|
||||
def set_nick(nick):
|
||||
conn.set_nick(nick)
|
||||
|
||||
def me(msg):
|
||||
conn.msg(chan, "\x01%s %s\x01" % ("ACTION", msg))
|
||||
|
||||
def notice(msg):
|
||||
conn.cmd('NOTICE', [nick, msg])
|
||||
|
||||
dict.__init__(self, conn=conn, raw=raw, prefix=prefix, command=command,
|
||||
params=params, nick=nick, user=user, host=host,
|
||||
paraml=paraml, msg=msg, server=conn.server, chan=chan,
|
||||
notice=notice, say=say, reply=reply, pm=pm, bot=bot,
|
||||
me=me, set_nick=set_nick, lastparam=paraml[-1])
|
||||
|
||||
# make dict keys accessible as attributes
|
||||
def __getattr__(self, key):
|
||||
return self[key]
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
self[key] = value
|
||||
|
||||
|
||||
def run(func, input):
|
||||
args = func._args
|
||||
|
||||
if 'inp' not in input:
|
||||
input.inp = input.paraml
|
||||
|
||||
if args:
|
||||
if 'db' in args and 'db' not in input:
|
||||
input.db = get_db_connection(input.conn)
|
||||
if 'input' in args:
|
||||
input.input = input
|
||||
if 0 in args:
|
||||
out = func(input.inp, **input)
|
||||
else:
|
||||
kw = dict((key, input[key]) for key in args if key in input)
|
||||
out = func(input.inp, **kw)
|
||||
else:
|
||||
out = func(input.inp)
|
||||
if out is not None:
|
||||
input.reply(unicode(out))
|
||||
|
||||
|
||||
def do_sieve(sieve, bot, input, func, type, args):
|
||||
try:
|
||||
return sieve(bot, input, func, type, args)
|
||||
except Exception:
|
||||
print 'sieve error',
|
||||
traceback.print_exc()
|
||||
return None
|
||||
|
||||
|
||||
class Handler(object):
|
||||
'''Runs plugins in their own threads (ensures order)'''
|
||||
def __init__(self, func):
|
||||
self.func = func
|
||||
self.input_queue = Queue.Queue()
|
||||
thread.start_new_thread(self.start, ())
|
||||
|
||||
def start(self):
|
||||
uses_db = 'db' in self.func._args
|
||||
db_conns = {}
|
||||
while True:
|
||||
input = self.input_queue.get()
|
||||
|
||||
if input == StopIteration:
|
||||
break
|
||||
|
||||
if uses_db:
|
||||
db = db_conns.get(input.conn)
|
||||
if db is None:
|
||||
db = bot.get_db_connection(input.conn)
|
||||
db_conns[input.conn] = db
|
||||
input.db = db
|
||||
|
||||
run(self.func, input)
|
||||
|
||||
def stop(self):
|
||||
self.input_queue.put(StopIteration)
|
||||
|
||||
def put(self, value):
|
||||
self.input_queue.put(value)
|
||||
|
||||
|
||||
def dispatch(input, kind, func, args, autohelp=False):
|
||||
for sieve, in bot.plugs['sieve']:
|
||||
input = do_sieve(sieve, bot, input, func, kind, args)
|
||||
if input == None:
|
||||
return
|
||||
|
||||
if autohelp and args.get('autohelp', True) and not input.inp \
|
||||
and func.__doc__ is not None:
|
||||
input.notice(func.__doc__)
|
||||
return
|
||||
|
||||
if func._thread:
|
||||
bot.threads[func].put(input)
|
||||
else:
|
||||
thread.start_new_thread(run, (func, input))
|
||||
|
||||
|
||||
def match_command(command):
|
||||
commands = list(bot.commands)
|
||||
|
||||
# do some fuzzy matching
|
||||
prefix = filter(lambda x: x.startswith(command), commands)
|
||||
if len(prefix) == 1:
|
||||
return prefix[0]
|
||||
elif prefix and command not in prefix:
|
||||
return prefix
|
||||
|
||||
return command
|
||||
|
||||
|
||||
def main(conn, out):
|
||||
inp = Input(conn, *out)
|
||||
|
||||
# EVENTS
|
||||
for func, args in bot.events[inp.command] + bot.events['*']:
|
||||
dispatch(Input(conn, *out), "event", func, args)
|
||||
|
||||
if inp.command == 'PRIVMSG':
|
||||
# COMMANDS
|
||||
if inp.chan == inp.nick: # private message, no command prefix
|
||||
prefix = r'^(?:[.]?|'
|
||||
else:
|
||||
prefix = r'^(?:[.]|'
|
||||
|
||||
command_re = prefix + inp.conn.nick
|
||||
command_re += r'[:]+\s+)(\w+)(?:$|\s+)(.*)'
|
||||
|
||||
m = re.match(command_re, inp.lastparam)
|
||||
|
||||
if m:
|
||||
trigger = m.group(1).lower()
|
||||
command = match_command(trigger)
|
||||
|
||||
if isinstance(command, list): # multiple potential matches
|
||||
input = Input(conn, *out)
|
||||
input.notice("Did you mean %s or %s?" %
|
||||
(', '.join(command[:-1]), command[-1]))
|
||||
elif command in bot.commands:
|
||||
input = Input(conn, *out)
|
||||
input.trigger = trigger
|
||||
input.inp_unstripped = m.group(2)
|
||||
input.inp = input.inp_unstripped.strip()
|
||||
|
||||
func, args = bot.commands[command]
|
||||
dispatch(input, "command", func, args, autohelp=True)
|
||||
|
||||
# REGEXES
|
||||
for func, args in bot.plugs['regex']:
|
||||
m = args['re'].search(inp.lastparam)
|
||||
if m:
|
||||
input = Input(conn, *out)
|
||||
input.inp = m
|
||||
|
||||
dispatch(input, "regex", func, args)
|
|
@ -0,0 +1,161 @@
|
|||
import collections
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
|
||||
if 'mtimes' not in globals():
|
||||
mtimes = {}
|
||||
|
||||
if 'lastfiles' not in globals():
|
||||
lastfiles = set()
|
||||
|
||||
|
||||
def make_signature(f):
|
||||
return f.func_code.co_filename, f.func_name, f.func_code.co_firstlineno
|
||||
|
||||
|
||||
def format_plug(plug, kind='', lpad=0, width=40):
|
||||
out = ' ' * lpad + '%s:%s:%s' % make_signature(plug[0])
|
||||
if kind == 'command':
|
||||
out += ' ' * (50 - len(out)) + plug[1]['name']
|
||||
|
||||
if kind == 'event':
|
||||
out += ' ' * (50 - len(out)) + ', '.join(plug[1]['events'])
|
||||
|
||||
if kind == 'regex':
|
||||
out += ' ' * (50 - len(out)) + plug[1]['regex']
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def reload(init=False):
|
||||
changed = False
|
||||
|
||||
if init:
|
||||
bot.plugs = collections.defaultdict(list)
|
||||
bot.threads = {}
|
||||
|
||||
core_fileset = set(glob.glob(os.path.join("core", "*.py")))
|
||||
|
||||
for filename in core_fileset:
|
||||
mtime = os.stat(filename).st_mtime
|
||||
if mtime != mtimes.get(filename):
|
||||
mtimes[filename] = mtime
|
||||
|
||||
changed = True
|
||||
|
||||
try:
|
||||
eval(compile(open(filename, 'U').read(), filename, 'exec'),
|
||||
globals())
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
if init: # stop if there's an error (syntax?) in a core
|
||||
sys.exit() # script on startup
|
||||
continue
|
||||
|
||||
if filename == os.path.join('core', 'reload.py'):
|
||||
reload(init=init)
|
||||
return
|
||||
|
||||
fileset = set(glob.glob(os.path.join('plugins', '*.py')))
|
||||
|
||||
# remove deleted/moved plugins
|
||||
for name, data in bot.plugs.iteritems():
|
||||
bot.plugs[name] = [x for x in data if x[0]._filename in fileset]
|
||||
|
||||
for filename in list(mtimes):
|
||||
if filename not in fileset and filename not in core_fileset:
|
||||
mtimes.pop(filename)
|
||||
|
||||
for func, handler in list(bot.threads.iteritems()):
|
||||
if func._filename not in fileset:
|
||||
handler.stop()
|
||||
del bot.threads[func]
|
||||
|
||||
# compile new plugins
|
||||
for filename in fileset:
|
||||
mtime = os.stat(filename).st_mtime
|
||||
if mtime != mtimes.get(filename):
|
||||
mtimes[filename] = mtime
|
||||
|
||||
changed = True
|
||||
|
||||
try:
|
||||
code = compile(open(filename, 'U').read(), filename, 'exec')
|
||||
namespace = {}
|
||||
eval(code, namespace)
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
continue
|
||||
|
||||
# remove plugins already loaded from this filename
|
||||
for name, data in bot.plugs.iteritems():
|
||||
bot.plugs[name] = [x for x in data
|
||||
if x[0]._filename != filename]
|
||||
|
||||
for func, handler in list(bot.threads.iteritems()):
|
||||
if func._filename == filename:
|
||||
handler.stop()
|
||||
del bot.threads[func]
|
||||
|
||||
for obj in namespace.itervalues():
|
||||
if hasattr(obj, '_hook'): # check for magic
|
||||
if obj._thread:
|
||||
bot.threads[obj] = Handler(obj)
|
||||
|
||||
for type, data in obj._hook:
|
||||
bot.plugs[type] += [data]
|
||||
|
||||
if not init:
|
||||
print '### new plugin (type: %s) loaded:' % \
|
||||
type, format_plug(data)
|
||||
|
||||
if changed:
|
||||
bot.commands = {}
|
||||
for plug in bot.plugs['command']:
|
||||
name = plug[1]['name'].lower()
|
||||
if not re.match(r'^\w+$', name):
|
||||
print '### ERROR: invalid command name "%s" (%s)' % (name,
|
||||
format_plug(plug))
|
||||
continue
|
||||
if name in bot.commands:
|
||||
print "### ERROR: command '%s' already registered (%s, %s)" % \
|
||||
(name, format_plug(bot.commands[name]),
|
||||
format_plug(plug))
|
||||
continue
|
||||
bot.commands[name] = plug
|
||||
|
||||
bot.events = collections.defaultdict(list)
|
||||
for func, args in bot.plugs['event']:
|
||||
for event in args['events']:
|
||||
bot.events[event].append((func, args))
|
||||
|
||||
if init:
|
||||
print ' plugin listing:'
|
||||
|
||||
if bot.commands:
|
||||
# hack to make commands with multiple aliases
|
||||
# print nicely
|
||||
|
||||
print ' command:'
|
||||
commands = collections.defaultdict(list)
|
||||
|
||||
for name, (func, args) in bot.commands.iteritems():
|
||||
commands[make_signature(func)].append(name)
|
||||
|
||||
for sig, names in sorted(commands.iteritems()):
|
||||
names.sort(key=lambda x: (-len(x), x)) # long names first
|
||||
out = ' ' * 6 + '%s:%s:%s' % sig
|
||||
out += ' ' * (50 - len(out)) + ', '.join(names)
|
||||
print out
|
||||
|
||||
for kind, plugs in sorted(bot.plugs.iteritems()):
|
||||
if kind == 'command':
|
||||
continue
|
||||
print ' %s:' % kind
|
||||
for plug in plugs:
|
||||
print format_plug(plug, kind=kind, lpad=6)
|
||||
print
|
|
@ -0,0 +1,26 @@
|
|||
Other bots we should "borrow" ideas from:
|
||||
|
||||
supybot http://supybot.com/
|
||||
- horribly bloated plugin structure, each plugin has its own directory and 4 files (unit testing for plugins what)
|
||||
|
||||
phenny http://inamidst.com/phenny/
|
||||
- inspiration for skybot, too much magic and not easy enough to change
|
||||
|
||||
pyfibot http://code.google.com/p/pyfibot/
|
||||
- interesting, but lots of magic
|
||||
|
||||
rbot http://linuxbrit.co.uk/rbot/
|
||||
- Ruby
|
||||
- lots of plugins
|
||||
|
||||
pyirc http://www.k-pdt.net/pyirc/
|
||||
- very simple, not multithreaded
|
||||
- poor use of regexes, skybot has much better parsing, but it implements many more irc control codes
|
||||
- can convert irc colors to vt100 escape codes -- should implement this
|
||||
- autoreconnect
|
||||
|
||||
pybot
|
||||
- can handle multiple servers, but not multithreaded
|
||||
- ugly modules
|
||||
- too many external dependencies
|
||||
- attempt at NLP
|
|
@ -0,0 +1,19 @@
|
|||
GOALS:
|
||||
simplicity
|
||||
as little boilerplate and magic as possible
|
||||
multithreaded dispatch
|
||||
|
||||
plugins are located in plugins/
|
||||
|
||||
input:
|
||||
nick -- string, the nickname of whoever sent the message
|
||||
channel -- string, the channel the message was sent on. Equal to nick if it's a private message.
|
||||
msg -- string, the line that was sent
|
||||
raw -- string, the raw full line that was sent
|
||||
re -- the result of doing re.match(hook, msg)
|
||||
|
||||
attributes and methods of bot:
|
||||
say(msg): obvious
|
||||
reply(msg): say(input.nick + ": " + msg)
|
||||
msg(target, msg): sends msg to target
|
||||
(other irc commands, like mode, topic, etc)
|
|
@ -0,0 +1,27 @@
|
|||
All plugins need to 'from util import hook' if they want to be callable.
|
||||
|
||||
There are three ways to set when a plugin is called using
|
||||
decorators. @hook.command causes it to be callable using normal command
|
||||
syntax; an argument will register it under that name (so if my function is
|
||||
called foo and I use @hook.command, .foo will work; if I use
|
||||
@hook.command("bar"), .bar will work but not .foo). The first argument, inp,
|
||||
will be the text that occurs after the command. (e.g., "bar" in ".foo bar").
|
||||
|
||||
@hook.regex takes an argument corresponding to the regex string (not the
|
||||
compiled regex), followed by optional flags. It will attempt to match the regex
|
||||
on all inputs; if so, the hooked function will be called with the match object.
|
||||
|
||||
@hook.event requires a parameter; if it's '*", it will trigger on every line. If
|
||||
it's 'PRIVMSG', it'll trigger on only actual lines of chat (not
|
||||
nick-changes). The first argument in these cases will be a two-element list of
|
||||
the form ["#channel", "text"]; I don't know what it's like for NICK or other
|
||||
'commands'.
|
||||
|
||||
@hook.singlethread indicates that the command should run in its own thread; this
|
||||
means that you can't use the existing database connection object!
|
||||
|
||||
In addition to the standard argument, plugins can take other arguments; db is
|
||||
the database object; input corresponds to the triggering line of text, and bot
|
||||
is the bot itself.
|
||||
|
||||
TODO: describe what can be done with db, input, and bot.
|
|
@ -0,0 +1,914 @@
|
|||
Ed. Note: The following note is from the author's original email
|
||||
announcing this CTCP specification file. All of this came after the
|
||||
original RFC 1459 for the IRC protocol. -Jolo
|
||||
|
||||
From: ben@gnu.ai.mit.edu
|
||||
Subject: REVISED AND UPDATED CTCP SPECIFICATION
|
||||
Date: Fri, 12 Aug 94 00:21:54 edt
|
||||
|
||||
As part of documenting the ZenIRC client, I expanded, revised, and
|
||||
merged two text files that have been around on IRC archive sites for
|
||||
some time: ctcp.doc, and dcc.protocol. The file "ctcp.doc" by Klaus
|
||||
Zeuge described the basic CTCP protocol, and most of the CTCP commands
|
||||
other than DCC. The file Troy Rollo wrote, "dcc.protocol", contained
|
||||
a description of the CTCP DCC messages as well as the protocols used
|
||||
by DCC CHAT and DCC file transfers. I have merged the two documents to
|
||||
produce this one, edited them for clarity, and expanded on them where I
|
||||
found them unclear while implementing CTCP in the ZenIRC client.
|
||||
|
||||
--Ben
|
||||
|
||||
----------------------------------------------------------------------
|
||||
|
||||
The Client-To-Client Protocol (CTCP)
|
||||
|
||||
Klaus Zeuge <sojge@Minsk.DoCS.UU.SE>
|
||||
Troy Rollo <troy@plod.cbme.unsw.oz.au>
|
||||
Ben Mesander <ben@gnu.ai.mit.edu>
|
||||
|
||||
|
||||
The Client-To-Client Protocol is meant to be used as a way to
|
||||
1/ in general send structured data (such as graphics,
|
||||
voice and different font information) between users
|
||||
clients, and in a more specific case:
|
||||
2/ place a query to a users client and getting an answer.
|
||||
|
||||
*****************************************
|
||||
BASIC PROTOCOL BETWEEN CLIENTS AND SERVER
|
||||
*****************************************
|
||||
|
||||
Characters between an Internet Relay Chat (IRC) client and server are
|
||||
8 bit bytes (also known as octets) and can have numeric values from
|
||||
octal \000 to \377 inclusive (0 to 255 decimal). Some characters are
|
||||
special:
|
||||
|
||||
CHARS ::= '\000' .. '\377'
|
||||
NUL ::= '\000'
|
||||
NL ::= '\n'
|
||||
CR ::= '\r'
|
||||
|
||||
Note: `\' followed by three digits is used to denote an octal value in this
|
||||
paper. `\' followed by an alphabetic character is used to denote a C
|
||||
language style special character, and `..' denotes a range of characters.
|
||||
|
||||
A line sent to a server, or received from a server (here called "low
|
||||
level messages") consist or zero or more octets (expcept NUL, NL or
|
||||
CR) with either a NL or CR appended.
|
||||
|
||||
L-CHARS ::= '\001' .. '\011' | '\013' | '\014' |
|
||||
'\016' .. '\377'
|
||||
L-LINE ::= L-CHARS* CR LF
|
||||
|
||||
Note: The `*' is used here to denote "zero or more of the preceding class of
|
||||
characters", and the `|' is used to denote alternation.
|
||||
|
||||
A NUL is never sent to the server.
|
||||
|
||||
*****************
|
||||
LOW LEVEL QUOTING
|
||||
*****************
|
||||
|
||||
Even though messages to and from IRC servers cannot contain NUL, NL,
|
||||
or CR, it still might be desirable to send ANY character (in so called
|
||||
"middle level messages") between clients. In order for this to be
|
||||
possible, those three characters have to be quoted. Therefore a quote
|
||||
character is needed. Of course, the quote character itself has to be
|
||||
quoted too, since it is in-band.
|
||||
|
||||
M-QUOTE ::= '\020'
|
||||
|
||||
(Ie a CNTRL/P).
|
||||
|
||||
When sending a middle level message, if there is a character in the
|
||||
set { NUL, NL, CR, M-QUOTE } present in the message, that character is
|
||||
replaced by a two character sequence according to the following table:
|
||||
|
||||
NUL --> M-QUOTE '0'
|
||||
NL --> M-QUOTE 'n'
|
||||
CR --> M-QUOTE 'r'
|
||||
M-QUOTE --> M-QUOTE M-QUOTE
|
||||
|
||||
When receiving a low level message, if there is a M-QUOTE, look at the
|
||||
next character, and replace those two according to the following table
|
||||
to get the corresponding middle level message:
|
||||
|
||||
M-QUOTE '0' --> NUL
|
||||
M-QUOTE 'n' --> NL
|
||||
M-QUOTE 'r' --> CR
|
||||
M-QUOTE M-QUOTE --> M-QUOTE
|
||||
|
||||
If the character following M-QUOTE is not any of the listed
|
||||
characters, that is an error, so drop the M-QUOTE character from the
|
||||
message, optionally warning the user about it. For example, a string
|
||||
'x' M-QUOTE 'y' 'z' from a server dequotes into 'x 'y' 'z'.
|
||||
|
||||
Before low level quoting, a message to the server (and in the opposite
|
||||
direction: after low level dequoting, a message from the server) looks
|
||||
like:
|
||||
|
||||
M-LINE ::= CHARS*
|
||||
|
||||
***********
|
||||
TAGGED DATA
|
||||
***********
|
||||
|
||||
To send both extended data and query/reply pairs between clients, an
|
||||
extended data format is needed. The extended data are sent in the text
|
||||
part of a middle level message (and after low level quoting, in the
|
||||
text part of the low level message).
|
||||
|
||||
To send extended data inside the middle level message, we need some
|
||||
way to delimit it. This is done by starting and ending extended data
|
||||
with a delimiter character, defined as:
|
||||
|
||||
X-DELIM ::= '\001'
|
||||
|
||||
As both the starting and ending delimiter looks the same, the first
|
||||
X-DELIM is called the odd delimiter, and the one that follows, the
|
||||
even delimiter. The next one after that, an odd delimiter, then and
|
||||
even, and so on.
|
||||
|
||||
When data are quoted (and conversely, before being dequoted) any number
|
||||
of characters of any kind except X-DELIM can be used in the extended
|
||||
data inside the X-DELIM pair.
|
||||
|
||||
X-CHR ::= '\000' | '\002' .. '\377'
|
||||
|
||||
An extended message is either empty (nothing between the odd and even
|
||||
delimiter), has one or more non-space characters (any character but
|
||||
'\040') or has one or more non-space characters followed by a space
|
||||
followed by zero or more characters.
|
||||
|
||||
X-N-AS ::= '\000' | '\002' .. '\037' | '\041' .. '\377'
|
||||
SPC ::= '\040'
|
||||
X-MSG ::= | X-N-AS+ | X-N-AS+ SPC X-CHR*
|
||||
|
||||
Note: Here `+' is used to denote "one or more of the previous class of
|
||||
characters", and `*' is used to denote "zero or more of the previous
|
||||
class of characters".
|
||||
|
||||
The characters up until the first SPC (or if no SPC, all of the X-MSG)
|
||||
is called the tag of the extended message. The tag is used to denote
|
||||
what kind of extended data is used.
|
||||
|
||||
The tag can be *any* string of characters, and if it contains
|
||||
alphabetics, it is case sensitive, so upper and lower case matters.
|
||||
|
||||
Extended data is only valid in PRIVMSG and NOTICE commands. If the
|
||||
extended data is a reply to a query, it is sent in a NOTICE, otherwise
|
||||
it is sent in a PRIVMSG. Both PRIVMSG and NOTICE to a user and to a
|
||||
channel may contain extended data.
|
||||
|
||||
The text part of a PRIVMSG or NOTICE might contain zero or more
|
||||
extended messages, intermixed with zero or more chunks of non-extended
|
||||
data.
|
||||
|
||||
******************
|
||||
CTCP LEVEL QUOTING
|
||||
******************
|
||||
|
||||
In order to be able to send the delimiter X-DELIM inside an extended
|
||||
data message, it has to be quoted. This introduces another quote
|
||||
character (which differs from the low level quote character so it
|
||||
won't have to be quoted yet again).
|
||||
|
||||
X-QUOTE ::= '\134'
|
||||
|
||||
(a back slash - `\').
|
||||
|
||||
When quoting on the CTCP level, only the actual CTCP message (extended
|
||||
data, queries, replies) are quoted. This enables users to actually
|
||||
send X-QUOTE characters at will. The following translations should be
|
||||
used:
|
||||
|
||||
X-DELIM --> X-QUOTE 'a'
|
||||
X-QUOTE --> X-QUOTE X-QUOTE
|
||||
|
||||
and when dequoting on the CTCP level, only CTCP messages are dequoted
|
||||
whereby the following table is used.
|
||||
|
||||
X-QUOTE 'a' --> X-DELIM
|
||||
X-QUOTE X-QUOTE --> X-QUOTE
|
||||
|
||||
If an X-QUOTE is seen with a character following it other than the
|
||||
ones above, that is an error and the X-QUOTE character should be
|
||||
dropped. For example the CTCP-quoted string 'x' X-QUOTE 'y' 'z'
|
||||
becomes after dequoting, the three character string 'x' 'y' 'z'.
|
||||
|
||||
If a X-DELIM is found outside a CTCP message, the message will contain
|
||||
the X-DELIM. (This should only happen with the last X-DELIM when there
|
||||
are an odd number of X-DELIM's in a middle level message.)
|
||||
|
||||
****************
|
||||
QUOTING EXAMPLES
|
||||
****************
|
||||
|
||||
There are three levels of messages. The highest level (H) is the text
|
||||
on the user-to-client level. The middle layer (M) is on the level
|
||||
where CTCP quoting has been applied to the H-level message. The lowest
|
||||
level (L) is on the client-to-server level, where low level quoting
|
||||
has been applied to the M-level message.
|
||||
|
||||
The following relations are true, with lowQuote(message) being a
|
||||
function doing the low level quoting, lowDequote(message) the low
|
||||
level dequoting function, ctcpQuote(message) the CTCP level quoting
|
||||
function, ctcpDequote(message) the CTCP level dequoting function, and
|
||||
ctcpExtract(message) the function which removes all CTCP messages from
|
||||
a message:
|
||||
|
||||
L = lowQuote(M)
|
||||
M = ctcpDequote(L)
|
||||
|
||||
M = ctcpQuote(H)
|
||||
H = ctcpDequote(ctcpExtract(M))
|
||||
|
||||
When sending a CTCP message embedded in normal text:
|
||||
|
||||
M = ctcpQuote(H1) || '\001' || ctcpQuote(X) || '\001' || ctcpQuote(H2)
|
||||
|
||||
Note: The operator || denotes string concatenation.
|
||||
|
||||
Of course, there might be zero or more normal text messages and zero
|
||||
or more CTCP messages mixed.
|
||||
|
||||
- --- Example 1 -----------------------------------------------------------------
|
||||
|
||||
A user (called actor) wanting to send the string:
|
||||
|
||||
Hi there!\nHow are you?
|
||||
|
||||
to user victim, i.e. a message where the user has entered an inline
|
||||
newline (how this is done, if at all, differs from client to client),
|
||||
will result internaly in the client in the command:
|
||||
|
||||
PRIVMSG victim :Hi there!\nHow are you? \K?
|
||||
|
||||
which will be CTCP quoted into:
|
||||
|
||||
PRIVMSG victim :Hi there!\nHow are you? \\K?
|
||||
|
||||
which in turn will be low level quoted into:
|
||||
|
||||
PRIVMSG victim :Hi there!\020nHow are you? \\K?
|
||||
|
||||
and sent to the server after appending a newline at the end.
|
||||
|
||||
This will arrive on victim's side as:
|
||||
|
||||
:actor PRIVMSG victim :Hi there!\020nHow are you? \\K?
|
||||
|
||||
(where the \\K would look similar to OK in SIS D47 et. al.) which after
|
||||
low level dequoting becomes:
|
||||
|
||||
:actor PRIVMSG victim :Hi there!\nHow are you? \\K?
|
||||
|
||||
and after CTCP dequoting:
|
||||
|
||||
:actom PRIVMSG victim :Hi there!\nHow are you? \K?
|
||||
|
||||
How this is displayed differs from client to client, but it suggested
|
||||
that a line break should occour between the words "there" and "How".
|
||||
|
||||
- --- Example 2 -----------------------------------------------------------------
|
||||
|
||||
If actor's client wants to send the string "Emacs wins" this might
|
||||
become the string "\n\t\big\020\001\000\\:" when being SED-encrypted
|
||||
[SED is a simple encryption protocol between IRC clients implemented
|
||||
with CTCP. I don't have any reference for it -- Ben] using some key,
|
||||
so the client starts by CTCP-quoting this string into the string
|
||||
"\n\t\big\020\\a\000\\\\:" and builds the M-level message:
|
||||
|
||||
PRIVMSG victim :\001SED \n\t\big\020\\a\000\\\\:\001
|
||||
|
||||
which after low level quoting becomes:
|
||||
|
||||
PRIVMSG victim :\001SED \020n\t\big\020\020\\a\0200\\\\:\001
|
||||
|
||||
which will be sent to the server, with a newline tacked on.
|
||||
|
||||
On victim's side, the string:
|
||||
|
||||
:actor PRIVMSG victim :\001SED \020n\t\big\020\020\\a\0200\\\\:\001
|
||||
|
||||
will be received from the server and low level dequoted into:
|
||||
|
||||
:actor PRIVMSG victim :\001SED \n\t\big\020\\a\000\\\\:\001
|
||||
|
||||
whereafter the string "\n\t\big\020\\a\000\\\\:" will be extracted
|
||||
and first CTCP dequoted into "\n\t\big\020\001\000\\:" and then
|
||||
SED decoded getting back "Emacs wins" when using the same key.
|
||||
|
||||
- --- Example 3 -----------------------------------------------------------------
|
||||
|
||||
If the user actor wants to query the USERINFO of user victim, and is
|
||||
in the middle of a conversation, the client may decide to tack on
|
||||
USERINFO request on the end of a normal text message. Let's say actor
|
||||
wants to send the textmessage "Say hi to Ron\n\t/actor" and the CTCP
|
||||
request "USERINFO" to victim:
|
||||
|
||||
PRIVMSG victim :Say hi to Ron\n\t/actor
|
||||
|
||||
plus:
|
||||
|
||||
USERINFO
|
||||
|
||||
which after CTCP quoting become:
|
||||
|
||||
PRIVMSG victim :Say hi to Ron\n\t/actor
|
||||
|
||||
plus:
|
||||
|
||||
USERINFO
|
||||
|
||||
which gets merged into:
|
||||
|
||||
PRIVMSG victim :Say hi to Ron\n\t/actor\001USERINFO\001
|
||||
|
||||
and after low level quoting:
|
||||
|
||||
PRIVMSG victim :Say hi to Ron\020n\t/actor\001USERINFO\001
|
||||
|
||||
and sent off to the server.
|
||||
|
||||
On victim's side, the message:
|
||||
|
||||
:actor PRIVMSG victim :Say hi to Ron\020n\t/actor\001USERINFO\001
|
||||
|
||||
arrives. This gets low level dequoted into:
|
||||
|
||||
:actor PRIVMSG victim :Say hi to Ron\n\t/actor\001USERINFO\001
|
||||
|
||||
and thereafter split up into:
|
||||
|
||||
:actor PRIVMSG victim :Say hi to Ron\n\t/actor
|
||||
|
||||
plus:
|
||||
|
||||
USERINFO
|
||||
|
||||
After CTCP dequoting both, the message:
|
||||
|
||||
:actor PRIVMSG victim :Say hi to Ron\n\t/actor
|
||||
|
||||
gets displayed, while the CTCP command:
|
||||
|
||||
USERINFO
|
||||
|
||||
gets replied to. The reply might be:
|
||||
|
||||
USERINFO :CS student\n\001test\001
|
||||
|
||||
which gets CTCP quoted into:
|
||||
|
||||
USERINFO :CS student\n\\atest\\a
|
||||
|
||||
and sent in a NOTICE as it is a reply:
|
||||
|
||||
NOTICE actor :\001USERINFO :CS student\n\\atest\\a\001
|
||||
|
||||
and low level quoted into:
|
||||
|
||||
NOTICE actor :\001USERINFO :CS student\020n\\atest\\a\001
|
||||
|
||||
after which is it sent to victim's server.
|
||||
|
||||
When arriving on actor's side, the message:
|
||||
|
||||
:victim NOTICE actor :\001USERINFO :CS student\020n\\atest\\a\001
|
||||
|
||||
gets low level dequoted into:
|
||||
|
||||
:victim NOTICE actor :\001USERINFO :CS student\n\\atest\\a\001
|
||||
|
||||
At this point, all CTCP replies get extracted, giving 1 CTCP reply and
|
||||
no normal NOTICE:
|
||||
|
||||
USERINFO :CS student\n\\atest\\a
|
||||
|
||||
The remaining reply gets CTCP dequoted into:
|
||||
|
||||
USERINFO :CS student\n\001test\001
|
||||
|
||||
and presumly displayed to user actor.
|
||||
|
||||
*******************
|
||||
KNOWN EXTENDED DATA
|
||||
*******************
|
||||
|
||||
Extended data passed between clients can be used to pass structured
|
||||
information between them. Currently known extended data types are:
|
||||
|
||||
ACTION - Used to simulate "role playing" on IRC.
|
||||
DCC - Negotiates file transfers and direct tcp chat
|
||||
connections between clients.
|
||||
SED - Used to send encrypted messages between clients.
|
||||
|
||||
ACTION
|
||||
======
|
||||
This is used by losers on IRC to simulate "role playing" games. An
|
||||
action message looks like the following:
|
||||
|
||||
\001ACTION barfs on the floor.\001
|
||||
|
||||
Clients that recieve such a message should format them to indicate the
|
||||
user who did this is performing an "action". For example, if the user
|
||||
"actor" sent the above message to the channel "#twilight_zone", other
|
||||
users clients might display the message as:
|
||||
|
||||
[ACTION] actor->#twilight_zone: barfs on the floor.
|
||||
|
||||
Presumably other users on the channel are suitably impressed.
|
||||
|
||||
DCC
|
||||
===
|
||||
DCC stands for something like "Direct Client Connection". CTCP DCC
|
||||
extended data messages are used to negotiate file transfers between
|
||||
clients and to negotiate chat connections over tcp connections between
|
||||
two clients, with no IRC server involved. Connections between clients
|
||||
involve protocols other than the usual IRC protocol. Due to this
|
||||
complexity, a full description of the DCC protocol is included
|
||||
separately at the end of this document in Appendix A.
|
||||
|
||||
SED
|
||||
===
|
||||
SED probably stands for something like "Simple Encryption D???". It is
|
||||
used by clients to exchange encrypted messages between clients. A
|
||||
message encoded by SED probably looks something like:
|
||||
|
||||
\001SED encrypted-text-goes-here\001
|
||||
|
||||
Clients which accept such messages should display them in decrypted
|
||||
form. It would be nice if someone documented this, and included the
|
||||
encryption scheme in an Appendix B.
|
||||
|
||||
*************************
|
||||
KNOWN REQUEST/REPLY PAIRS
|
||||
*************************
|
||||
|
||||
A request/reply pair is sent between the two clients in two phases.
|
||||
The first phase is to send the request. This is done with a "privmsg"
|
||||
command (either to a nick or to a channel -- it doesn't matter).
|
||||
|
||||
The second phase is to send a reply. This is done with a "notice"
|
||||
command.
|
||||
|
||||
The known request/reply pairs are for the following commands.
|
||||
|
||||
FINGER - Returns the user's full name, and idle time.
|
||||
VERSION - The version and type of the client.
|
||||
SOURCE - Where to obtain a copy of a client.
|
||||
USERINFO - A string set by the user (never the client coder)
|
||||
CLIENTINFO - Dynamic master index of what a client knows.
|
||||
ERRMSG - Used when an error needs to be replied with.
|
||||
PING - Used to measure the delay of the IRC network
|
||||
between clients.
|
||||
TIME - Gets the local date and time from other clients.
|
||||
|
||||
FINGER
|
||||
======
|
||||
This is used to get a user's real name, and perhaps also the idle time
|
||||
of the user (this usage has been obsoleted by enhancements to the IRC
|
||||
protocol. The request is in a "privmsg" and looks like
|
||||
|
||||
\001FINGER\001
|
||||
|
||||
while the reply is in a "notice" and looks like
|
||||
|
||||
\001FINGER :#\001
|
||||
|
||||
where the # denotes contains information about the users real name,
|
||||
login name at clientmachine and idle time and is of type X-N-AS.
|
||||
|
||||
VERSION
|
||||
=======
|
||||
This is used to get information about the name of the other client and
|
||||
the version of it. The request in a "privmsg" is simply
|
||||
|
||||
\001VERSION\001
|
||||
|
||||
and the reply
|
||||
|
||||
\001VERSION #:#:#\001
|
||||
|
||||
where the first # denotes the name of the client, the second # denotes
|
||||
the version of the client, the third # the enviroment the client is
|
||||
running in.
|
||||
|
||||
Using
|
||||
|
||||
X-N-CLN ::= '\000' .. '\071' | '\073' .. '\377'
|
||||
|
||||
the client name is a string of type X-N-CLN saying things like "Kiwi"
|
||||
or "ircII", the version saying things like "5.2" or "2.1.5c", the
|
||||
enviroment saying things like "GNU Emacs 18.57.19 under SunOS 4.1.1 on
|
||||
Sun SLC" or "Compiled with gcc -ansi under Ultrix 4.0 on VAX-11/730".
|
||||
|
||||
|
||||
SOURCE
|
||||
|
||||
This is used to get information about where to get a copy of the
|
||||
client. The request in a "privmsg" is simply
|
||||
|
||||
\001SOURCE\001
|
||||
|
||||
and the reply is zero or more CTCP replies of the form
|
||||
|
||||
\001SOURCE #:#:#\001
|
||||
|
||||
followed by an end marker
|
||||
|
||||
\001SOURCE\001
|
||||
|
||||
where the first # is the name of an Internet host where the client can
|
||||
be gotten from with anonymous FTP the second # a directory names, and
|
||||
the third # a space separated list of files to be gotten from that
|
||||
directory.
|
||||
|
||||
Using
|
||||
|
||||
X-N-SPC ::= '\000' .. '\037' | '\041' .. '\377'
|
||||
|
||||
the name of the FTP site is to be given by name like "cs.bu.edu" or
|
||||
"funic.funet.fi".
|
||||
|
||||
The file name field is a directory specification optionally followed
|
||||
by one or more file names, delimited by spaces. If only a directory
|
||||
name is given, all files in that directory should be copied when
|
||||
retrieving the clients source. If some files are given, only those
|
||||
files in that directpry should be copied. Note that the spcification
|
||||
allows for all characters but space in the names, this includes
|
||||
allowing :. Examples are "pub/emacs/irc/" to get all files in
|
||||
directory pub/emacs/irc/, the client should be able to first login as
|
||||
user "ftp" and the give the command "CD pub/emacs/irc/", followed by
|
||||
the command "mget *". (It of course has to take care of binary and
|
||||
prompt mode too). Another example is "/pub/irc Kiwi.5.2.el.Z" in which
|
||||
case a "CD /pub/irc" and "get Kiwi.5.2.el.Z" is what should be done.
|
||||
|
||||
|
||||
USERINFO
|
||||
========
|
||||
This is used to transmit a string which is settable by the user (and
|
||||
never should be set by the client). The query is simply
|
||||
|
||||
\001USERINFO\001
|
||||
|
||||
with the reply
|
||||
|
||||
\001USERINFO :#\001
|
||||
|
||||
where the # is the value of the string the client's user has set.
|
||||
|
||||
CLIENTINFO
|
||||
==========
|
||||
This is for client developers use to make it easier to show other
|
||||
client hackers what a certain client knows when it comes to CTCP. The
|
||||
replies should be fairly verbose explaining what CTCP commands are
|
||||
understood, what arguments are expected of what type, and what replies
|
||||
might be expected from the client.
|
||||
|
||||
The query is the word CLIENTINFO in a "privmsg" optionally followed by
|
||||
a colon and one or more specifying words delimited by spaces, where
|
||||
the word CLIENTINFO by itself,
|
||||
|
||||
\001CLIENTINFO\001
|
||||
|
||||
should be replied to by giving a list of known tags (see above in
|
||||
section TAGGED DATA). This is only intended to be read by humans.
|
||||
|
||||
With one argument, the reply should be a description of how to use
|
||||
that tag. With two arguments, a description of how to use that
|
||||
tag's subcommand. And so on.
|
||||
|
||||
ERRMSG
|
||||
======
|
||||
This is used as a reply whenever an unknown query is seen. Also, when
|
||||
used as a query, the reply should echo back the text in the query,
|
||||
together with an indication that no error has happened. Should the
|
||||
query form be used, it is
|
||||
|
||||
\001ERRMSG #\001
|
||||
|
||||
where # is a string containing any character, with the reply
|
||||
|
||||
\001ERRMSG # :#\001
|
||||
|
||||
where the first # is the same string as in the query and the second #
|
||||
a short text notifying the user that no error has occurred.
|
||||
|
||||
A normal ERRMSG reply which is sent when a corrupted query or some
|
||||
corrupted extended data is received, looks like
|
||||
|
||||
\001ERRMSG # :#\001
|
||||
|
||||
where the first # is the the failed query or corrupted extended data
|
||||
and the second # a text explaining what the problem is, like "unknown
|
||||
query" or "failed decrypting text".
|
||||
|
||||
PING
|
||||
====
|
||||
Ping is used to measure the time delay between clients on the IRC
|
||||
network. A ping query is encoded in a privmsg, and has the form:
|
||||
|
||||
\001PING timestamp\001
|
||||
|
||||
where `timestamp' is the current time encoded in any form the querying
|
||||
client finds convienent. The replying client sends back an identical
|
||||
message inside a notice:
|
||||
|
||||
\001PING timestamp\001
|
||||
|
||||
The querying client can then subtract the recieved timestamp from the
|
||||
current time to obtain the delay between clients over the IRC network.
|
||||
|
||||
TIME
|
||||
====
|
||||
Time queries are used to determine what time it is where another
|
||||
user's client is running. This can be useful to determine if someone
|
||||
is probably awake or not, or what timezone they are in. A time query
|
||||
has the form:
|
||||
|
||||
\001TIME\001
|
||||
|
||||
On reciept of such a query in a privmsg, clients should reply with a
|
||||
notice of the form:
|
||||
|
||||
\001TIME :human-readable-time-string\001
|
||||
|
||||
For example:
|
||||
|
||||
\001TIME :Thu Aug 11 22:52:51 1994 CST\001
|
||||
|
||||
********
|
||||
EXAMPLES
|
||||
********
|
||||
|
||||
|
||||
Sending
|
||||
|
||||
PRIVMSG victim :\001FINGER\001
|
||||
|
||||
might return
|
||||
|
||||
:victim NOTICE actor :\001FINGER :Please check my USERINFO
|
||||
instead :Klaus Zeuge (sojge@mizar) 1 second has passed since
|
||||
victim gave a command last.\001
|
||||
|
||||
(this is only one line) or why not
|
||||
|
||||
:victim NOTICE actor :\001FINGER :Please check my USERINFO
|
||||
instead :Klaus Zeuge (sojge@mizar) 427 seconds (7 minutes and
|
||||
7 seconds) have passed since victim gave a command last.\001
|
||||
|
||||
if Klaus Zeuge happens to be lazy? :-)
|
||||
|
||||
Sending
|
||||
|
||||
PRIVMSG victim :\001CLIENTINFO\001
|
||||
|
||||
might return
|
||||
|
||||
:victim NOTICE actor :\001CLIENTINFO :You can request help of the
|
||||
commands CLIENTINFO ERRMSG FINGER USERINFO VERSION by giving
|
||||
an argument to CLIENTINFO.\001
|
||||
|
||||
Sending
|
||||
|
||||
PRIVMSG victim :\001CLIENTINFO CLIENTINFO\001
|
||||
|
||||
might return
|
||||
|
||||
:victim NOTICE actor :\001CLIENTINFO :CLIENTINFO with 0
|
||||
arguments gives a list of known client query keywords. With 1
|
||||
argument, a description of the client query keyword is
|
||||
returned.\001
|
||||
|
||||
while sending
|
||||
|
||||
PRIVMSG victim :\001clientinfo clientinfo\001
|
||||
|
||||
probably will return something like
|
||||
|
||||
:victim NOTICE actor :\001ERRMSG clientinfo clientinfo :Query is
|
||||
unknown\001
|
||||
|
||||
as tag "clientinfo" isn't known.
|
||||
|
||||
Sending
|
||||
|
||||
PRIVMSG victim :\001CLIENTINFO ERRMSG\001
|
||||
|
||||
might return
|
||||
|
||||
:victim NOTICE actor :\001CLIENTINFO :ERRMSG is the given answer
|
||||
on seeing an unknown keyword. When seeing the keyword ERRMSG,
|
||||
it works like an echo.\001
|
||||
|
||||
Sending
|
||||
|
||||
PRIVMSG victim :\001USERINFO\001
|
||||
|
||||
might return the somewhat pathetically long
|
||||
|
||||
:victim NOTICE actor :\001USERINFO :I'm studying computer
|
||||
science in Uppsala, I'm male (somehow, that seems to be an
|
||||
important matter on IRC:-) and I speak fluent swedish, decent
|
||||
german, and some english.\001
|
||||
|
||||
Sending
|
||||
|
||||
PRIVMSG victim :\001VERSION\001
|
||||
|
||||
might return:
|
||||
|
||||
:victim NOTICE actor :\001VERSION Kiwi:5.2:GNU Emacs
|
||||
18.57.19 under SunOS 4.1.1 on Sun
|
||||
SLC:FTP.Lysator.LiU.SE:/pub/emacs Kiwi-5.2.el.Z
|
||||
Kiwi.README\001
|
||||
|
||||
if the client is named Kiwi of version 5.2 and is used under GNU Emacs
|
||||
18.57.19 running on a Sun SLCwith SunOS 4.1.1. The client claims a
|
||||
copy of it can be found with anonymous FTP on FTP.Lysator.LiU.SE after
|
||||
giving the FTP command "cd /pub/emacs/". There, one should get files
|
||||
Kiwi-5.2.el.Z and Kiwi.README; presumably one of the files tells how to
|
||||
proceed with building the client after having gotten the files.
|
||||
|
||||
|
||||
----------------------------------------------------------------------
|
||||
|
||||
|
||||
**********************************************************************
|
||||
Appendix A -- A description of the DCC protocol
|
||||
**********************************************************************
|
||||
|
||||
By Troy Rollo (troy@plod.cbme.unsw.oz.au)
|
||||
Revised by Ben Mesander (ben@gnu.ai.mit.edu)
|
||||
|
||||
Troy Rollo, the original implementor of the DCC protocol, said
|
||||
that the DCC protocol was never designed to be portable to clients
|
||||
other than IRCII. However, time has shown that DCC is useable in
|
||||
environments other than IRCII. IRC clients in diverse languages, such
|
||||
as ksh, elisp, C, and perl have all had DCC implementations.
|
||||
|
||||
Why DCC?
|
||||
========
|
||||
|
||||
DCC allows the user to overcome some limitations of the IRC
|
||||
server network and to have a somewhat more secure chat connection
|
||||
while still in an IRC-oriented protocol.
|
||||
|
||||
DCC uses direct TCP connections between the clients taking
|
||||
part to carry data. There is no flood control, so packets can be sent
|
||||
at full speed, and there is no dependance on server links (or load
|
||||
imposed on them). In addition, since only the initial handshake for
|
||||
DCC conections is passed through the IRC network, it makes it harder
|
||||
for operators with cracked servers to spy on personal messages.
|
||||
|
||||
How?
|
||||
====
|
||||
|
||||
The initial socket for a DCC connection is created
|
||||
by the side that initiates (Offers) the connection. This socket
|
||||
should be a TCP socket bound to INADDR_ANY, listening for
|
||||
connections.
|
||||
|
||||
The Initiating client, on creating the socket, should
|
||||
send its details to the target client using the CTCP command
|
||||
DCC. This command takes the form:
|
||||
|
||||
DCC type argument address port [size]
|
||||
|
||||
type - The connection type.
|
||||
argument - The connectin type dependant argument.
|
||||
address - The host address of the initiator as an integer.
|
||||
port - The port or the socket on which the initiator expects
|
||||
to receive the connection.
|
||||
size - If the connection type is "SEND" (see below), then size
|
||||
will indicate the size of the file being offered. Obsolete
|
||||
IRCII clients do not send this, so be prepared if this is
|
||||
not present.
|
||||
|
||||
The address, port, and size should be sent as ASCII representations of
|
||||
the decimal integer formed by converting the values to host byte order
|
||||
and treating them as an unsigned long, unsigned short, and unsigned
|
||||
long respectively.
|
||||
|
||||
Implementations of the DCC protocol should be prepared to
|
||||
accept further arguments in a CTCP DCC message. There has been some
|
||||
discussion of adding another argument that would specify the type of
|
||||
file being transferred - text, binary, and perhaps others if DCC is
|
||||
implemented on operating systems other than UNIX. If additional
|
||||
arguments are added to the protocol, they should have semantics such
|
||||
that clients which ignore them will interoperate with clients that
|
||||
don't in a sensible way.
|
||||
|
||||
The following DCC connection types are defined:
|
||||
|
||||
Type Purpose Argument
|
||||
CHAT To carry on a semi-secure conversation the string "chat"
|
||||
SEND To send a file to the recipient the file name
|
||||
|
||||
Although the following subcommand is included in the IRCII DCC command,
|
||||
it does _not_ transmit a DCC request via IRC, and thus is not
|
||||
discussed in this document:
|
||||
|
||||
TALK Establishes a TALK connection
|
||||
|
||||
|
||||
Implementation
|
||||
==============
|
||||
|
||||
The CHAT and SEND connection types should not be
|
||||
accepted automatically as this would create the potential for
|
||||
terrorism. Instead, they should notify the user that an
|
||||
offer has been made, and allow the user to accept it.
|
||||
|
||||
The recipient should have the opportunity to rename a file
|
||||
offered with the DCC SEND command prior to retrieving it. It is also
|
||||
desirable to ensure that the offered file will not overwrite an
|
||||
existing file.
|
||||
|
||||
Older IRCII clients send the entire pathname of the file being
|
||||
transmitted. This is annoying, and newer clients should simply send
|
||||
the filename portion of the file being transmitted.
|
||||
|
||||
The port number should be scrutinized - if the port number is
|
||||
in the UNIX reserved port range, the connection should only be
|
||||
accepted with caution.
|
||||
|
||||
If it is not possible in the client implementation language to
|
||||
handle a 32-bit integer (for instance emacs 18 elisp and ksh 88), then
|
||||
it is often possible to use the hostname in the originating PRIVMSG.
|
||||
|
||||
The following are the steps which should occur in the clients
|
||||
(this description assumes use of the BSD socket interface on a UNIX
|
||||
system).
|
||||
|
||||
Initiator:
|
||||
DCC command issued.
|
||||
Create a socket, bind it to INADDR_ANY, port 0, and
|
||||
make it passive (a listening socket).
|
||||
Send the recipient a DCC request via CTCP supplying
|
||||
the address and port of the socket. (This
|
||||
is ideally taken from the address of the local
|
||||
side of the socket which is connected to a
|
||||
server. This is presumably the interface on
|
||||
the host which is closest to the rest of
|
||||
the net, and results in one less routing hop
|
||||
in the case of gateway nodes).
|
||||
Continue normally until a connection is received.
|
||||
|
||||
On a connection:
|
||||
Accept the connection.
|
||||
Close the original passive socket.
|
||||
Conduct transaction on the new socket.
|
||||
|
||||
Acceptor:
|
||||
CTCP DCC request received.
|
||||
Record information on the DCC request and notify the user.
|
||||
|
||||
At this point, the USER should be able to abort (close) the
|
||||
request, or accept it. The request should be accepted with
|
||||
a command specifying the sender, type, and argument, or
|
||||
a subset of these where no ambiguity exists.
|
||||
|
||||
If accepted, create a TCP socket.
|
||||
Connect the new socket to the address and port supplied.
|
||||
Conduct the transaction over the socket.
|
||||
|
||||
|
||||
Type specific details.
|
||||
======================
|
||||
|
||||
CHAT Data sent across a CHAT connection should be sent line-by-line
|
||||
without any prefixes or commands. A CHAT connection ends when
|
||||
one party issues the DCC CLOSE command to their clients, which
|
||||
causes the socket to be closed and the information on the connection
|
||||
to be discarded. The terminating character of each line is a
|
||||
newline character, '\n'.
|
||||
|
||||
FILE Data is sent in packets, rather than dumped in a stream manner.
|
||||
This allows the DCC SEND connection to survive where an FTP
|
||||
connection might fail. The size of the packets is up to the
|
||||
client, and may be set by the user. Smaller packets result
|
||||
in a higher probability of survival over bad links.
|
||||
The recipient should acknowledge each packet by transmitting
|
||||
the total number of bytes received as an unsigned, 4 byte
|
||||
integer in network byte order. The sender should not continue
|
||||
to transmit until the recipient has acknowledged all data
|
||||
already transmitted. Additionally, the sender should not
|
||||
close the connection until the last byte has been
|
||||
acknowledged by the recipient.
|
||||
|
||||
Older IRCII clients do not send the file size of the file
|
||||
being transmitted via DCC. For those clients, note that it is
|
||||
not possible for the recipient to tell if the entire file has
|
||||
been received - only the sender has that information, although
|
||||
IRCII does not report it. Users generally verify the transfer
|
||||
by checking file sizes. Authors of clients are urged to use
|
||||
the size feature.
|
||||
|
||||
Note also that no provision is made for text translation.
|
||||
|
||||
The original block size used by IRCII was 1024. Other clients
|
||||
have adopted this. Note, however, that an implementation should accept
|
||||
any blocksize. IRCII currently allows a user-settable blocksize.
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,455 @@
|
|||
RFC 2810 (RFC2810)
|
||||
|
||||
Internet RFC/STD/FYI/BCP Archives
|
||||
|
||||
[ RFC Index | RFC Search | Usenet FAQs | Web FAQs | Documents | Cities ]
|
||||
|
||||
Alternate Formats: rfc2810.txt | rfc2810.txt.pdf
|
||||
|
||||
RFC 2810 - Internet Relay Chat: Architecture
|
||||
|
||||
----------------------------------------------------------------------
|
||||
|
||||
|
||||
Network Working Group C. Kalt
|
||||
Request for Comments: 2810 April 2000
|
||||
Updates: 1459
|
||||
Category: Informational
|
||||
|
||||
Internet Relay Chat: Architecture
|
||||
|
||||
Status of this Memo
|
||||
|
||||
This memo provides information for the Internet community. It does
|
||||
not specify an Internet standard of any kind. Distribution of this
|
||||
memo is unlimited.
|
||||
|
||||
Copyright Notice
|
||||
|
||||
Copyright (C) The Internet Society (2000). All Rights Reserved.
|
||||
|
||||
Abstract
|
||||
|
||||
The IRC (Internet Relay Chat) protocol is for use with text based
|
||||
conferencing. It has been developed since 1989 when it was originally
|
||||
implemented as a mean for users on a BBS to chat amongst themselves.
|
||||
|
||||
First formally documented in May 1993 by RFC 1459 [IRC], the protocol
|
||||
has kept evolving. This document is an update describing the
|
||||
architecture of the current IRC protocol and the role of its
|
||||
different components. Other documents describe in detail the
|
||||
protocol used between the various components defined here.
|
||||
|
||||
Table of Contents
|
||||
|
||||
1. Introduction ............................................... 2
|
||||
2. Components ................................................. 2
|
||||
2.1 Servers ................................................ 2
|
||||
2.2 Clients ................................................ 3
|
||||
2.2.1 User Clients ...................................... 3
|
||||
2.2.2 Service Clients ................................... 3
|
||||
3. Architecture ............................................... 3
|
||||
4. IRC Protocol Services ...................................... 4
|
||||
4.1 Client Locator ......................................... 4
|
||||
4.2 Message Relaying ....................................... 4
|
||||
4.3 Channel Hosting And Management ......................... 4
|
||||
5. IRC Concepts ............................................... 4
|
||||
5.1 One-To-One Communication ............................... 5
|
||||
5.2 One-To-Many ............................................ 5
|
||||
5.2.1 To A Channel ...................................... 5
|
||||
5.2.2 To A Host/Server Mask ............................. 6
|
||||
|
||||
5.2.3 To A List ......................................... 6
|
||||
5.3 One-To-All ............................................. 6
|
||||
5.3.1 Client-to-Client .................................. 6
|
||||
5.3.2 Client-to-Server .................................. 7
|
||||
5.3.3 Server-to-Server .................................. 7
|
||||
6. Current Problems ........................................... 7
|
||||
6.1 Scalability ............................................ 7
|
||||
6.2 Reliability ............................................ 7
|
||||
6.3 Network Congestion ..................................... 7
|
||||
6.4 Privacy ................................................ 8
|
||||
7. Security Considerations .................................... 8
|
||||
8. Current Support And Availability ........................... 8
|
||||
9. Acknowledgements ........................................... 8
|
||||
10. References ................................................ 8
|
||||
11. Author's Address .......................................... 9
|
||||
12. Full Copyright Statement .................................. 10
|
||||
|
||||
1. Introduction
|
||||
|
||||
The IRC (Internet Relay Chat) protocol has been designed over a
|
||||
number of years for use with text based conferencing. This document
|
||||
describes its current architecture.
|
||||
|
||||
The IRC Protocol is based on the client-server model, and is well
|
||||
suited to running on many machines in a distributed fashion. A
|
||||
typical setup involves a single process (the server) forming a
|
||||
central point for clients (or other servers) to connect to,
|
||||
performing the required message delivery/multiplexing and other
|
||||
functions.
|
||||
|
||||
This distributed model, which requires each server to have a copy
|
||||
of the global state information, is still the most flagrant problem
|
||||
of the protocol as it is a serious handicap, which limits the maximum
|
||||
size a network can reach. If the existing networks have been able to
|
||||
keep growing at an incredible pace, we must thank hardware
|
||||
manufacturers for giving us ever more powerful systems.
|
||||
|
||||
2. Components
|
||||
|
||||
The following paragraphs define the basic components of the IRC
|
||||
protocol.
|
||||
|
||||
2.1 Servers
|
||||
|
||||
The server forms the backbone of IRC as it is the only component
|
||||
of the protocol which is able to link all the other components
|
||||
together: it provides a point to which clients may connect to talk to
|
||||
|
||||
each other [IRC-CLIENT], and a point for other servers to connect to
|
||||
[IRC-SERVER]. The server is also responsible for providing the basic
|
||||
services defined by the IRC protocol.
|
||||
|
||||
2.2 Clients
|
||||
|
||||
A client is anything connecting to a server that is not another
|
||||
server. There are two types of clients which both serve a different
|
||||
purpose.
|
||||
|
||||
2.2.1 User Clients
|
||||
|
||||
User clients are generally programs providing a text based
|
||||
interface that is used to communicate interactively via IRC. This
|
||||
particular type of clients is often referred as "users".
|
||||
|
||||
2.2.2 Service Clients
|
||||
|
||||
Unlike users, service clients are not intended to be used manually
|
||||
nor for talking. They have a more limited access to the chat
|
||||
functions of the protocol, while optionally having access to more
|
||||
private data from the servers.
|
||||
|
||||
Services are typically automatons used to provide some kind of
|
||||
service (not necessarily related to IRC itself) to users. An example
|
||||
is a service collecting statistics about the origin of users
|
||||
connected on the IRC network.
|
||||
|
||||
3. Architecture
|
||||
|
||||
An IRC network is defined by a group of servers connected to each
|
||||
other. A single server forms the simplest IRC network.
|
||||
|
||||
The only network configuration allowed for IRC servers is that of
|
||||
a spanning tree where each server acts as a central node for the rest
|
||||
of the network it sees.
|
||||
|
||||
1--\
|
||||
A D---4
|
||||
2--/ \ /
|
||||
B----C
|
||||
/ \
|
||||
3 E
|
||||
|
||||
Servers: A, B, C, D, E Clients: 1, 2, 3, 4
|
||||
|
||||
[ Fig. 1. Sample small IRC network ]
|
||||
|
||||
The IRC protocol provides no mean for two clients to directly
|
||||
communicate. All communication between clients is relayed by the
|
||||
server(s).
|
||||
|
||||
4. IRC Protocol Services
|
||||
|
||||
This section describes the services offered by the IRC protocol. The
|
||||
combination of these services allow real-time conferencing.
|
||||
|
||||
4.1 Client Locator
|
||||
|
||||
To be able to exchange messages, two clients must be able to locate
|
||||
each other.
|
||||
|
||||
Upon connecting to a server, a client registers using a label which
|
||||
is then used by other servers and clients to know where the client is
|
||||
located. Servers are responsible for keeping track of all the labels
|
||||
being used.
|
||||
|
||||
4.2 Message Relaying
|
||||
|
||||
The IRC protocol provides no mean for two clients to directly
|
||||
communicate. All communication between clients is relayed by the
|
||||
server(s).
|
||||
|
||||
4.3 Channel Hosting And Management
|
||||
|
||||
A channel is a named group of one or more users which will all
|
||||
receive messages addressed to that channel. A channel is
|
||||
characterized by its name and current members, it also has a set of
|
||||
properties which can be manipulated by (some of) its members.
|
||||
|
||||
Channels provide a mean for a message to be sent to several clients.
|
||||
Servers host channels, providing the necessary message multiplexing.
|
||||
Servers are also responsible for managing channels by keeping track
|
||||
of the channel members. The exact role of servers is defined in
|
||||
"Internet Relay Chat: Channel Management" [IRC-CHAN].
|
||||
|
||||
5. IRC Concepts
|
||||
|
||||
This section is devoted to describing the actual concepts behind the
|
||||
organization of the IRC protocol and how different classes of
|
||||
messages are delivered.
|
||||
|
||||
5.1 One-To-One Communication
|
||||
|
||||
Communication on a one-to-one basis is usually performed by clients,
|
||||
since most server-server traffic is not a result of servers talking
|
||||
only to each other. To provide a means for clients to talk to each
|
||||
other, it is REQUIRED that all servers be able to send a message in
|
||||
exactly one direction along the spanning tree in order to reach any
|
||||
client. Thus the path of a message being delivered is the shortest
|
||||
path between any two points on the spanning tree.
|
||||
|
||||
The following examples all refer to Figure 1 above.
|
||||
|
||||
Example 1: A message between clients 1 and 2 is only seen by server
|
||||
A, which sends it straight to client 2.
|
||||
|
||||
Example 2: A message between clients 1 and 3 is seen by servers A &
|
||||
B, and client 3. No other clients or servers are allowed see the
|
||||
message.
|
||||
|
||||
Example 3: A message between clients 2 and 4 is seen by servers A, B,
|
||||
C & D and client 4 only.
|
||||
|
||||
5.2 One-To-Many
|
||||
|
||||
The main goal of IRC is to provide a forum which allows easy and
|
||||
efficient conferencing (one to many conversations). IRC offers
|
||||
several means to achieve this, each serving its own purpose.
|
||||
|
||||
5.2.1 To A Channel
|
||||
|
||||
In IRC the channel has a role equivalent to that of the multicast
|
||||
group; their existence is dynamic and the actual conversation carried
|
||||
out on a channel MUST only be sent to servers which are supporting
|
||||
users on a given channel. Moreover, the message SHALL only be sent
|
||||
once to every local link as each server is responsible to fan the
|
||||
original message to ensure that it will reach all the recipients.
|
||||
|
||||
The following examples all refer to Figure 2.
|
||||
|
||||
Example 4: Any channel with 1 client in it. Messages to the channel
|
||||
go to the server and then nowhere else.
|
||||
|
||||
Example 5: 2 clients in a channel. All messages traverse a path as if
|
||||
they were private messages between the two clients outside a
|
||||
channel.
|
||||
|
||||
Example 6: Clients 1, 2 and 3 in a channel. All messages to the
|
||||
channel are sent to all clients and only those servers which must
|
||||
be traversed by the message if it were a private message to a
|
||||
single client. If client 1 sends a message, it goes back to
|
||||
client 2 and then via server B to client 3.
|
||||
|
||||
5.2.2 To A Host/Server Mask
|
||||
|
||||
To provide with some mechanism to send messages to a large body of
|
||||
related users, host and server mask messages are available. These
|
||||
messages are sent to users whose host or server information match
|
||||
that of the mask. The messages are only sent to locations where
|
||||
users are, in a fashion similar to that of channels.
|
||||
|
||||
5.2.3 To A List
|
||||
|
||||
The least efficient style of one-to-many conversation is through
|
||||
clients talking to a 'list' of targets (client, channel, mask). How
|
||||
this is done is almost self explanatory: the client gives a list of
|
||||
destinations to which the message is to be delivered and the server
|
||||
breaks it up and dispatches a separate copy of the message to each
|
||||
given destination.
|
||||
|
||||
This is not as efficient as using a channel since the destination
|
||||
list MAY be broken up and the dispatch sent without checking to make
|
||||
sure duplicates aren't sent down each path.
|
||||
|
||||
5.3 One-To-All
|
||||
|
||||
The one-to-all type of message is better described as a broadcast
|
||||
message, sent to all clients or servers or both. On a large network
|
||||
of users and servers, a single message can result in a lot of traffic
|
||||
being sent over the network in an effort to reach all of the desired
|
||||
destinations.
|
||||
|
||||
For some class of messages, there is no option but to broadcast it to
|
||||
all servers so that the state information held by each server is
|
||||
consistent between servers.
|
||||
|
||||
5.3.1 Client-to-Client
|
||||
|
||||
There is no class of message which, from a single message, results in
|
||||
a message being sent to every other client.
|
||||
|
||||
5.3.2 Client-to-Server
|
||||
|
||||
Most of the commands which result in a change of state information
|
||||
(such as channel membership, channel mode, user status, etc.) MUST be
|
||||
sent to all servers by default, and this distribution SHALL NOT be
|
||||
changed by the client.
|
||||
|
||||
5.3.3 Server-to-Server
|
||||
|
||||
While most messages between servers are distributed to all 'other'
|
||||
servers, this is only required for any message that affects a user,
|
||||
channel or server. Since these are the basic items found in IRC,
|
||||
nearly all messages originating from a server are broadcast to all
|
||||
other connected servers.
|
||||
|
||||
6. Current Problems
|
||||
|
||||
There are a number of recognized problems with this protocol, this
|
||||
section only addresses the problems related to the architecture of
|
||||
the protocol.
|
||||
|
||||
6.1 Scalability
|
||||
|
||||
It is widely recognized that this protocol does not scale
|
||||
sufficiently well when used in a large arena. The main problem comes
|
||||
from the requirement that all servers know about all other servers,
|
||||
clients and channels and that information regarding them be updated
|
||||
as soon as it changes.
|
||||
|
||||
6.2 Reliability
|
||||
|
||||
As the only network configuration allowed for IRC servers is that of
|
||||
a spanning tree, each link between two servers is an obvious and
|
||||
quite serious point of failure. This particular issue is addressed
|
||||
more in detail in "Internet Relay Chat: Server Protocol" [IRC-
|
||||
SERVER].
|
||||
|
||||
6.3 Network Congestion
|
||||
|
||||
Another problem related to the scalability and reliability issues, as
|
||||
well as the spanning tree architecture, is that the protocol and
|
||||
architecture for IRC are extremely vulnerable to network congestions.
|
||||
This problem is endemic, and should be solved for the next
|
||||
generation: if congestion and high traffic volume cause a link
|
||||
between two servers to fail, not only this failure generates more
|
||||
network traffic, but the reconnection (eventually elsewhere) of two
|
||||
servers also generates more traffic.
|
||||
|
||||
In an attempt to minimize the impact of these problems, it is
|
||||
strongly RECOMMENDED that servers do not automatically try to
|
||||
reconnect too fast, in order to avoid aggravating the situation.
|
||||
|
||||
6.4 Privacy
|
||||
|
||||
Besides not scaling well, the fact that servers need to know all
|
||||
information about other entities, the issue of privacy is also a
|
||||
concern. This is in particular true for channels, as the related
|
||||
information is quite a lot more revealing than whether a user is
|
||||
online or not.
|
||||
|
||||
7. Security Considerations
|
||||
|
||||
Asides from the privacy concerns mentioned in section 6.4 (Privacy),
|
||||
security is believed to be irrelevant to this document.
|
||||
|
||||
8. Current Support And Availability
|
||||
|
||||
Mailing lists for IRC related discussion:
|
||||
General discussion: ircd-users@irc.org
|
||||
Protocol development: ircd-dev@irc.org
|
||||
|
||||
Software implementations:
|
||||
ftp://ftp.irc.org/irc/server
|
||||
ftp://ftp.funet.fi/pub/unix/irc
|
||||
ftp://coombs.anu.edu.au/pub/irc
|
||||
|
||||
Newsgroup: alt.irc
|
||||
|
||||
9. Acknowledgements
|
||||
|
||||
Parts of this document were copied from the RFC 1459 [IRC] which
|
||||
first formally documented the IRC Protocol. It has also benefited
|
||||
from many rounds of review and comments. In particular, the
|
||||
following people have made significant contributions to this
|
||||
document:
|
||||
|
||||
Matthew Green, Michael Neumayer, Volker Paulsen, Kurt Roeckx, Vesa
|
||||
Ruokonen, Magnus Tjernstrom, Stefan Zehl.
|
||||
|
||||
10. References
|
||||
|
||||
[KEYWORDS] Bradner, S., "Key words for use in RFCs to Indicate
|
||||
Requirement Levels", BCP 14, RFC 2119, March 1997.
|
||||
|
||||
[IRC] Oikarinen, J. and D. Reed, "Internet Relay Chat
|
||||
Protocol", RFC 1459, May 1993.
|
||||
|
||||
[IRC-CLIENT] Kalt, C., "Internet Relay Chat: Client Protocol", RFC
|
||||
2812, April 2000.
|
||||
|
||||
[IRC-SERVER] Kalt, C., "Internet Relay Chat: Server Protocol", RFC
|
||||
2813, April 2000.
|
||||
|
||||
[IRC-CHAN] Kalt, C., "Internet Relay Chat: Channel Management", RFC
|
||||
2811, April 2000.
|
||||
|
||||
11. Author's Address
|
||||
|
||||
Christophe Kalt
|
||||
99 Teaneck Rd, Apt #117
|
||||
Ridgefield Park, NJ 07660
|
||||
USA
|
||||
|
||||
EMail: kalt@stealth.net
|
||||
|
||||
12. Full Copyright Statement
|
||||
|
||||
Copyright (C) The Internet Society (2000). All Rights Reserved.
|
||||
|
||||
This document and translations of it may be copied and furnished to
|
||||
others, and derivative works that comment on or otherwise explain it
|
||||
or assist in its implementation may be prepared, copied, published
|
||||
and distributed, in whole or in part, without restriction of any
|
||||
kind, provided that the above copyright notice and this paragraph are
|
||||
included on all such copies and derivative works. However, this
|
||||
document itself may not be modified in any way, such as by removing
|
||||
the copyright notice or references to the Internet Society or other
|
||||
Internet organizations, except as needed for the purpose of
|
||||
developing Internet standards in which case the procedures for
|
||||
copyrights defined in the Internet Standards process must be
|
||||
followed, or as required to translate it into languages other than
|
||||
English.
|
||||
|
||||
The limited permissions granted above are perpetual and will not be
|
||||
revoked by the Internet Society or its successors or assigns.
|
||||
|
||||
This document and the information contained herein is provided on an
|
||||
"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
|
||||
TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
|
||||
BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
|
||||
HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
|
||||
|
||||
Acknowledgement
|
||||
|
||||
Funding for the RFC Editor function is currently provided by the
|
||||
Internet Society.
|
||||
|
||||
|
||||
|
||||
|
||||
Comments about this RFC:
|
||||
|
||||
* RFC 2810: Hi, Here goes the text in section 5.2.1 : "The following
|
||||
examples all... by AkA (6/2/2007)
|
||||
|
||||
Previous: RFC 2809 - Implementation of Next: RFC 2811 - Internet Relay Chat:
|
||||
L2TP Compulsory Tunneling via RADIUS Channel Management
|
||||
|
||||
|
||||
|
||||
----------------------------------------------------------------------
|
||||
|
||||
[ RFC Index | RFC Search | Usenet FAQs | Web FAQs | Documents | Cities ]
|
|
@ -0,0 +1,866 @@
|
|||
RFC 2811 (RFC2811)
|
||||
|
||||
Internet RFC/STD/FYI/BCP Archives
|
||||
|
||||
[ RFC Index | RFC Search | Usenet FAQs | Web FAQs | Documents | Cities ]
|
||||
|
||||
Alternate Formats: rfc2811.txt | rfc2811.txt.pdf
|
||||
|
||||
RFC 2811 - Internet Relay Chat: Channel Management
|
||||
|
||||
----------------------------------------------------------------------
|
||||
|
||||
|
||||
Network Working Group C. Kalt
|
||||
Request for Comments: 2811 April 2000
|
||||
Updates: 1459
|
||||
Category: Informational
|
||||
|
||||
Internet Relay Chat: Channel Management
|
||||
|
||||
Status of this Memo
|
||||
|
||||
This memo provides information for the Internet community. It does
|
||||
not specify an Internet standard of any kind. Distribution of this
|
||||
memo is unlimited.
|
||||
|
||||
Copyright Notice
|
||||
|
||||
Copyright (C) The Internet Society (2000). All Rights Reserved.
|
||||
|
||||
Abstract
|
||||
|
||||
One of the most notable characteristics of the IRC (Internet Relay
|
||||
Chat) protocol is to allow for users to be grouped in forums, called
|
||||
channels, providing a mean for multiple users to communicate
|
||||
together.
|
||||
|
||||
There was originally a unique type of channels, but with the years,
|
||||
new types appeared either as a response to a need, or for
|
||||
experimental purposes.
|
||||
|
||||
This document specifies how channels, their characteristics and
|
||||
properties are managed by IRC servers.
|
||||
|
||||
Table of Contents
|
||||
|
||||
1. Introduction ............................................... 2
|
||||
2. Channel Characteristics .................................... 3
|
||||
2.1 Namespace .............................................. 3
|
||||
2.2 Channel Scope .......................................... 3
|
||||
2.3 Channel Properties ..................................... 4
|
||||
2.4 Privileged Channel Members ............................. 4
|
||||
2.4.1 Channel Operators ................................. 5
|
||||
2.4.2 Channel Creator ................................... 5
|
||||
3. Channel lifetime ........................................... 5
|
||||
3.1 Standard channels ...................................... 5
|
||||
3.2 Safe Channels .......................................... 6
|
||||
4. Channel Modes .............................................. 7
|
||||
4.1 Member Status .......................................... 7
|
||||
4.1.1 "Channel Creator" Status .......................... 7
|
||||
|
||||
4.1.2 Channel Operator Status ........................... 8
|
||||
4.1.3 Voice Privilege ................................... 8
|
||||
4.2 Channel Flags .......................................... 8
|
||||
4.2.1 Anonymous Flag .................................... 8
|
||||
4.2.2 Invite Only Flag .................................. 8
|
||||
4.2.3 Moderated Channel Flag ............................ 9
|
||||
4.2.4 No Messages To Channel From Clients On The Outside 9
|
||||
4.2.5 Quiet Channel ..................................... 9
|
||||
4.2.6 Private and Secret Channels ....................... 9
|
||||
4.2.7 Server Reop Flag .................................. 10
|
||||
4.2.8 Topic ............................................. 10
|
||||
4.2.9 User Limit ........................................ 10
|
||||
4.2.10 Channel Key ...................................... 10
|
||||
4.3 Channel Access Control ................................. 10
|
||||
4.3.1 Channel Ban and Exception ......................... 11
|
||||
4.3.2 Channel Invitation ................................ 11
|
||||
5. Current Implementations .................................... 11
|
||||
5.1 Tracking Recently Used Channels ........................ 11
|
||||
5.2 Safe Channels .......................................... 12
|
||||
5.2.1 Channel Identifier ................................ 12
|
||||
5.2.2 Channel Delay ..................................... 12
|
||||
5.2.3 Abuse Window ...................................... 13
|
||||
5.2.4 Preserving Sanity In The Name Space ............... 13
|
||||
5.2.5 Server Reop Mechanism ............................. 13
|
||||
6. Current problems ........................................... 14
|
||||
6.1 Labels ................................................. 14
|
||||
6.1.1 Channel Delay ..................................... 14
|
||||
6.1.2 Safe Channels ..................................... 15
|
||||
6.2 Mode Propagation Delays ................................ 15
|
||||
6.3 Collisions And Channel Modes ........................... 15
|
||||
6.4 Resource Exhaustion .................................... 16
|
||||
7. Security Considerations .................................... 16
|
||||
7.1 Access Control ......................................... 16
|
||||
7.2 Channel Privacy ........................................ 16
|
||||
7.3 Anonymity ............................................... 17
|
||||
8. Current support and availability ........................... 17
|
||||
9. Acknowledgements ........................................... 17
|
||||
10. References ................................................ 18
|
||||
11. Author's Address .......................................... 18
|
||||
12. Full Copyright Statement ................................... 19
|
||||
|
||||
1. Introduction
|
||||
|
||||
This document defines in detail on how channels are managed by the
|
||||
IRC servers and will be mostly useful to people working on
|
||||
implementing an IRC server.
|
||||
|
||||
While the concepts defined here are an important part of IRC, they
|
||||
remain non essential for implementing clients. While the trend seems
|
||||
to be towards more and more complex and "intelligent" clients which
|
||||
are able to take advantage of knowing the internal workings of
|
||||
channels to provide the users with a more friendly interface, simple
|
||||
clients can be implemented without reading this document.
|
||||
|
||||
Many of the concepts defined here were designed with the IRC
|
||||
architecture [IRC-ARCH] in mind and mostly make sense in this
|
||||
context. However, many others could be applied to other
|
||||
architectures in order to provide forums for a conferencing system.
|
||||
|
||||
Finally, it is to be noted that IRC users may find some of the
|
||||
following sections of interest, in particular sections 2 (Channel
|
||||
Characteristics) and 4 (Channel Modes).
|
||||
|
||||
2. Channel Characteristics
|
||||
|
||||
A channel is a named group of one or more users which will all
|
||||
receive messages addressed to that channel. A channel is
|
||||
characterized by its name, properties and current members.
|
||||
|
||||
2.1 Namespace
|
||||
|
||||
Channels names are strings (beginning with a '&', '#', '+' or '!'
|
||||
character) of length up to fifty (50) characters. Channel names are
|
||||
case insensitive.
|
||||
|
||||
Apart from the the requirement that the first character being either
|
||||
'&', '#', '+' or '!' (hereafter called "channel prefix"). The only
|
||||
restriction on a channel name is that it SHALL NOT contain any spaces
|
||||
(' '), a control G (^G or ASCII 7), a comma (',' which is used as a
|
||||
list item separator by the protocol). Also, a colon (':') is used as
|
||||
a delimiter for the channel mask. The exact syntax of a channel name
|
||||
is defined in "IRC Server Protocol" [IRC-SERVER].
|
||||
|
||||
The use of different prefixes effectively creates four (4) distinct
|
||||
namespaces for channel names. This is important because of the
|
||||
protocol limitations regarding namespaces (in general). See section
|
||||
6.1 (Labels) for more details on these limitations.
|
||||
|
||||
2.2 Channel Scope
|
||||
|
||||
A channel entity is known by one or more servers on the IRC network.
|
||||
A user can only become member of a channel known by the server to
|
||||
which the user is directly connected. The list of servers which know
|
||||
|
||||
of the existence of a particular channel MUST be a contiguous part of
|
||||
the IRC network, in order for the messages addressed to the channel
|
||||
to be sent to all the channel members.
|
||||
|
||||
Channels with '&' as prefix are local to the server where they are
|
||||
created.
|
||||
|
||||
Other channels are known to one (1) or more servers that are
|
||||
connected to the network, depending on the channel mask:
|
||||
|
||||
If there is no channel mask, then the channel is known to all
|
||||
the servers.
|
||||
|
||||
If there is a channel mask, then the channel MUST only be known
|
||||
to servers which has a local user on the channel, and to its
|
||||
neighbours if the mask matches both the local and neighbouring
|
||||
server names. Since other servers have absolutely no knowledge of
|
||||
the existence of such a channel, the area formed by the servers
|
||||
having a name matching the mask has to be contiguous for the
|
||||
channel to be known by all these servers. Channel masks are best
|
||||
used in conjunction with server hostmasking [IRC-SERVER].
|
||||
|
||||
2.3 Channel Properties
|
||||
|
||||
Each channel has its own properties, which are defined by channel
|
||||
modes. Channel modes can be manipulated by the channel members. The
|
||||
modes affect the way servers manage the channels.
|
||||
|
||||
Channels with '+' as prefix do not support channel modes. This means
|
||||
that all the modes are unset, with the exception of the 't' channel
|
||||
flag which is set.
|
||||
|
||||
2.4 Privileged Channel Members
|
||||
|
||||
In order for the channel members to keep some control over a channel,
|
||||
and some kind of sanity, some channel members are privileged. Only
|
||||
these members are allowed to perform the following actions on the
|
||||
channel:
|
||||
|
||||
INVITE - Invite a client to an invite-only channel (mode +i)
|
||||
KICK - Eject a client from the channel
|
||||
MODE - Change the channel's mode, as well as
|
||||
members' privileges
|
||||
PRIVMSG - Sending messages to the channel (mode +n, +m, +v)
|
||||
TOPIC - Change the channel topic in a mode +t channel
|
||||
|
||||
2.4.1 Channel Operators
|
||||
|
||||
The channel operators (also referred to as a "chop" or "chanop") on a
|
||||
given channel are considered to 'own' that channel. Ownership of a
|
||||
channel is shared among channel operators.
|
||||
|
||||
Channel operators are identified by the '@' symbol next to their
|
||||
nickname whenever it is associated with a channel (i.e., replies to
|
||||
the NAMES, WHO and WHOIS commands).
|
||||
|
||||
Since channels starting with the character '+' as prefix do not
|
||||
support channel modes, no member can therefore have the status of
|
||||
channel operator.
|
||||
|
||||
2.4.2 Channel Creator
|
||||
|
||||
A user who creates a channel with the character '!' as prefix is
|
||||
identified as the "channel creator". Upon creation of the channel,
|
||||
this user is also given channel operator status.
|
||||
|
||||
In recognition of this status, the channel creators are endowed with
|
||||
the ability to toggle certain modes of the channel which channel
|
||||
operators may not manipulate.
|
||||
|
||||
A "channel creator" can be distinguished from a channel operator by
|
||||
issuing the proper MODE command. See the "IRC Client Protocol"
|
||||
[IRC-CLIENT] for more information on this topic.
|
||||
|
||||
3. Channel lifetime
|
||||
|
||||
In regard to the lifetime of a channel, there are typically two
|
||||
groups of channels: standard channels which prefix is either '&', '#'
|
||||
or '+', and "safe channels" which prefix is '!'.
|
||||
|
||||
3.1 Standard channels
|
||||
|
||||
These channels are created implicitly when the first user joins it,
|
||||
and cease to exist when the last user leaves it. While the channel
|
||||
exists, any client can reference the channel using the name of the
|
||||
channel.
|
||||
|
||||
The user creating a channel automatically becomes channel operator
|
||||
with the notable exception of channels which name is prefixed by the
|
||||
character '+', see section 4 (Channel modes). See section 2.4.1
|
||||
(Channel Operators) for more details on this title.
|
||||
|
||||
In order to avoid the creation of duplicate channels (typically when
|
||||
the IRC network becomes disjoint because of a split between two
|
||||
servers), channel names SHOULD NOT be allowed to be reused by a user
|
||||
if a channel operator (See Section 2.4.1 (Channel Operators)) has
|
||||
recently left the channel because of a network split. If this
|
||||
happens, the channel name is temporarily unavailable. The duration
|
||||
while a channel remains unavailable should be tuned on a per IRC
|
||||
network basis. It is important to note that this prevents local
|
||||
users from creating a channel using the same name, but does not
|
||||
prevent the channel to be recreated by a remote user. The latter
|
||||
typically happens when the IRC network rejoins. Obviously, this
|
||||
mechanism only makes sense for channels which name begins with the
|
||||
character '#', but MAY be used for channels which name begins with
|
||||
the character '+'. This mechanism is commonly known as "Channel
|
||||
Delay".
|
||||
|
||||
3.2 Safe Channels
|
||||
|
||||
Unlike other channels, "safe channels" are not implicitly created. A
|
||||
user wishing to create such a channel MUST request the creation by
|
||||
sending a special JOIN command to the server in which the channel
|
||||
identifier (then unknown) is replaced by the character '!'. The
|
||||
creation process for this type of channel is strictly controlled.
|
||||
The user only chooses part of the channel name (known as the channel
|
||||
"short name"), the server automatically prepends the user provided
|
||||
name with a channel identifier consisting of five (5) characters.
|
||||
The channel name resulting from the combination of these two elements
|
||||
is unique, making the channel safe from abuses based on network
|
||||
splits.
|
||||
|
||||
The user who creates such a channel automatically becomes "channel
|
||||
creator". See section 2.4.2 (Channel Creator) for more details on
|
||||
this title.
|
||||
|
||||
A server MUST NOT allow the creation of a new channel if another
|
||||
channel with the same short name exists; or if another channel with
|
||||
the same short name existed recently AND any of its member(s) left
|
||||
because of a network split. Such channel ceases to exist after last
|
||||
user leaves AND no other member recently left the channel because of
|
||||
a network split.
|
||||
|
||||
Unlike the mechanism described in section 5.2.2 (Channel Delay), in
|
||||
this case, channel names do not become unavailable: these channels
|
||||
may continue to exist after the last user left. Only the user
|
||||
creating the channel becomes "channel creator", users joining an
|
||||
existing empty channel do not automatically become "channel creator"
|
||||
nor "channel operator".
|
||||
|
||||
To ensure the uniqueness of the channel names, the channel identifier
|
||||
created by the server MUST follow specific rules. For more details
|
||||
on this, see section 5.2.1 (Channel Identifier).
|
||||
|
||||
4. Channel Modes
|
||||
|
||||
The various modes available for channels are as follows:
|
||||
|
||||
O - give "channel creator" status;
|
||||
o - give/take channel operator privilege;
|
||||
v - give/take the voice privilege;
|
||||
|
||||
a - toggle the anonymous channel flag;
|
||||
i - toggle the invite-only channel flag;
|
||||
m - toggle the moderated channel;
|
||||
n - toggle the no messages to channel from clients on the
|
||||
outside;
|
||||
q - toggle the quiet channel flag;
|
||||
p - toggle the private channel flag;
|
||||
s - toggle the secret channel flag;
|
||||
r - toggle the server reop channel flag;
|
||||
t - toggle the topic settable by channel operator only flag;
|
||||
|
||||
k - set/remove the channel key (password);
|
||||
l - set/remove the user limit to channel;
|
||||
|
||||
b - set/remove ban mask to keep users out;
|
||||
e - set/remove an exception mask to override a ban mask;
|
||||
I - set/remove an invitation mask to automatically override
|
||||
the invite-only flag;
|
||||
|
||||
Unless mentioned otherwise below, all these modes can be manipulated
|
||||
by "channel operators" by using the MODE command defined in "IRC
|
||||
Client Protocol" [IRC-CLIENT].
|
||||
|
||||
4.1 Member Status
|
||||
|
||||
The modes in this category take a channel member nickname as argument
|
||||
and affect the privileges given to this user.
|
||||
|
||||
4.1.1 "Channel Creator" Status
|
||||
|
||||
The mode 'O' is only used in conjunction with "safe channels" and
|
||||
SHALL NOT be manipulated by users. Servers use it to give the user
|
||||
creating the channel the status of "channel creator".
|
||||
|
||||
4.1.2 Channel Operator Status
|
||||
|
||||
The mode 'o' is used to toggle the operator status of a channel
|
||||
member.
|
||||
|
||||
4.1.3 Voice Privilege
|
||||
|
||||
The mode 'v' is used to give and take voice privilege to/from a
|
||||
channel member. Users with this privilege can talk on moderated
|
||||
channels. (See section 4.2.3 (Moderated Channel Flag).
|
||||
|
||||
4.2 Channel Flags
|
||||
|
||||
The modes in this category are used to define properties which
|
||||
affects how channels operate.
|
||||
|
||||
4.2.1 Anonymous Flag
|
||||
|
||||
The channel flag 'a' defines an anonymous channel. This means that
|
||||
when a message sent to the channel is sent by the server to users,
|
||||
and the origin is a user, then it MUST be masked. To mask the
|
||||
message, the origin is changed to "anonymous!anonymous@anonymous."
|
||||
(e.g., a user with the nickname "anonymous", the username "anonymous"
|
||||
and from a host called "anonymous."). Because of this, servers MUST
|
||||
forbid users from using the nickname "anonymous". Servers MUST also
|
||||
NOT send QUIT messages for users leaving such channels to the other
|
||||
channel members but generate a PART message instead.
|
||||
|
||||
On channels with the character '&' as prefix, this flag MAY be
|
||||
toggled by channel operators, but on channels with the character '!'
|
||||
as prefix, this flag can be set (but SHALL NOT be unset) by the
|
||||
"channel creator" only. This flag MUST NOT be made available on
|
||||
other types of channels.
|
||||
|
||||
Replies to the WHOIS, WHO and NAMES commands MUST NOT reveal the
|
||||
presence of other users on channels for which the anonymous flag is
|
||||
set.
|
||||
|
||||
4.2.2 Invite Only Flag
|
||||
|
||||
When the channel flag 'i' is set, new members are only accepted if
|
||||
their mask matches Invite-list (See section 4.3.2) or they have been
|
||||
invited by a channel operator. This flag also restricts the usage of
|
||||
the INVITE command (See "IRC Client Protocol" [IRC-CLIENT]) to
|
||||
channel operators.
|
||||
|
||||
4.2.3 Moderated Channel Flag
|
||||
|
||||
The channel flag 'm' is used to control who may speak on a channel.
|
||||
When it is set, only channel operators, and members who have been
|
||||
given the voice privilege may send messages to the channel.
|
||||
|
||||
This flag only affects users.
|
||||
|
||||
4.2.4 No Messages To Channel From Clients On The Outside
|
||||
|
||||
When the channel flag 'n' is set, only channel members MAY send
|
||||
messages to the channel.
|
||||
|
||||
This flag only affects users.
|
||||
|
||||
4.2.5 Quiet Channel
|
||||
|
||||
The channel flag 'q' is for use by servers only. When set, it
|
||||
restricts the type of data sent to users about the channel
|
||||
operations: other user joins, parts and nick changes are not sent.
|
||||
From a user's point of view, the channel contains only one user.
|
||||
|
||||
This is typically used to create special local channels on which the
|
||||
server sends notices related to its operations. This was used as a
|
||||
more efficient and flexible way to replace the user mode 's' defined
|
||||
in RFC 1459 [IRC].
|
||||
|
||||
4.2.6 Private and Secret Channels
|
||||
|
||||
The channel flag 'p' is used to mark a channel "private" and the
|
||||
channel flag 's' to mark a channel "secret". Both properties are
|
||||
similar and conceal the existence of the channel from other users.
|
||||
|
||||
This means that there is no way of getting this channel's name from
|
||||
the server without being a member. In other words, these channels
|
||||
MUST be omitted from replies to queries like the WHOIS command.
|
||||
|
||||
When a channel is "secret", in addition to the restriction above, the
|
||||
server will act as if the channel does not exist for queries like the
|
||||
TOPIC, LIST, NAMES commands. Note that there is one exception to
|
||||
this rule: servers will correctly reply to the MODE command.
|
||||
Finally, secret channels are not accounted for in the reply to the
|
||||
LUSERS command (See "Internet Relay Chat: Client Protocol" [IRC-
|
||||
CLIENT]) when the <mask> parameter is specified.
|
||||
|
||||
The channel flags 'p' and 's' MUST NOT both be set at the same time.
|
||||
If a MODE message originating from a server sets the flag 'p' and the
|
||||
flag 's' is already set for the channel, the change is silently
|
||||
ignored. This should only happen during a split healing phase
|
||||
(mentioned in the "IRC Server Protocol" document [IRC-SERVER]).
|
||||
|
||||
4.2.7 Server Reop Flag
|
||||
|
||||
The channel flag 'r' is only available on channels which name begins
|
||||
with the character '!' and MAY only be toggled by the "channel
|
||||
creator".
|
||||
|
||||
This flag is used to prevent a channel from having no channel
|
||||
operator for an extended period of time. When this flag is set, any
|
||||
channel that has lost all its channel operators for longer than the
|
||||
"reop delay" period triggers a mechanism in servers to reop some or
|
||||
all of the channel inhabitants. This mechanism is described more in
|
||||
detail in section 5.2.4 (Channel Reop Mechanism).
|
||||
|
||||
4.2.8 Topic
|
||||
|
||||
The channel flag 't' is used to restrict the usage of the TOPIC
|
||||
command to channel operators.
|
||||
|
||||
4.2.9 User Limit
|
||||
|
||||
A user limit may be set on channels by using the channel flag 'l'.
|
||||
When the limit is reached, servers MUST forbid their local users to
|
||||
join the channel.
|
||||
|
||||
The value of the limit MUST only be made available to the channel
|
||||
members in the reply sent by the server to a MODE query.
|
||||
|
||||
4.2.10 Channel Key
|
||||
|
||||
When a channel key is set (by using the mode 'k'), servers MUST
|
||||
reject their local users request to join the channel unless this key
|
||||
is given.
|
||||
|
||||
The channel key MUST only be made visible to the channel members in
|
||||
the reply sent by the server to a MODE query.
|
||||
|
||||
4.3 Channel Access Control
|
||||
|
||||
The last category of modes is used to control access to the channel,
|
||||
they take a mask as argument.
|
||||
|
||||
In order to reduce the size of the global database for control access
|
||||
modes set for channels, servers MAY put a maximum limit on the number
|
||||
of such modes set for a particular channel. If such restriction is
|
||||
imposed, it MUST only affect user requests. The limit SHOULD be
|
||||
homogeneous on a per IRC network basis.
|
||||
|
||||
4.3.1 Channel Ban and Exception
|
||||
|
||||
When a user requests to join a channel, his local server checks if
|
||||
the user's address matches any of the ban masks set for the channel.
|
||||
If a match is found, the user request is denied unless the address
|
||||
also matches an exception mask set for the channel.
|
||||
|
||||
Servers MUST NOT allow a channel member who is banned from the
|
||||
channel to speak on the channel, unless this member is a channel
|
||||
operator or has voice privilege. (See Section 4.1.3 (Voice
|
||||
Privilege)).
|
||||
|
||||
A user who is banned from a channel and who carries an invitation
|
||||
sent by a channel operator is allowed to join the channel.
|
||||
|
||||
4.3.2 Channel Invitation
|
||||
|
||||
For channels which have the invite-only flag set (See Section 4.2.2
|
||||
(Invite Only Flag)), users whose address matches an invitation mask
|
||||
set for the channel are allowed to join the channel without any
|
||||
invitation.
|
||||
|
||||
5. Current Implementations
|
||||
|
||||
The only current implementation of these rules as part of the IRC
|
||||
protocol is the IRC server, version 2.10.
|
||||
|
||||
The rest of this section deals with issues that are mostly of
|
||||
importance to those who wish to implement a server but some parts may
|
||||
also be of interest for client writers.
|
||||
|
||||
5.1 Tracking Recently Used Channels
|
||||
|
||||
This mechanism is commonly known as "Channel Delay" and generally
|
||||
only applies to channels which names is prefixed with the character
|
||||
'#' (See Section 3.1 "Standard channels").
|
||||
|
||||
When a network split occurs, servers SHOULD keep track of which
|
||||
channels lost a "channel operator" as the result of the break. These
|
||||
channels are then in a special state which lasts for a certain period
|
||||
of time. In this particular state, the channels cannot cease to
|
||||
|
||||
exist. If all the channel members leave the channel, the channel
|
||||
becomes unavailable: the server local clients cannot join the channel
|
||||
as long as it is empty.
|
||||
|
||||
Once a channel is unavailable, it will become available again either
|
||||
because a remote user has joined the channel (most likely because the
|
||||
network is healing), or because the delay period has expired (in
|
||||
which case the channel ceases to exist and may be re-created).
|
||||
|
||||
The duration for which a channel death is delayed SHOULD be set
|
||||
considering many factors among which are the size (user wise) of the
|
||||
IRC network, and the usual duration of network splits. It SHOULD be
|
||||
uniform on all servers for a given IRC network.
|
||||
|
||||
5.2 Safe Channels
|
||||
|
||||
This document introduces the notion of "safe channels". These
|
||||
channels have a name prefixed with the character '!' and great effort
|
||||
is made to avoid collisions in this name space. Collisions are not
|
||||
impossible, however they are very unlikely.
|
||||
|
||||
5.2.1 Channel Identifier
|
||||
|
||||
The channel identifier is a function of the time. The current time
|
||||
(as defined under UNIX by the number of seconds elapsed since
|
||||
00:00:00 GMT, January 1, 1970) is converted in a string of five (5)
|
||||
characters using the following base:
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" (each character has a decimal
|
||||
value starting from 0 for 'A' to 35 for '0').
|
||||
|
||||
The channel identifier therefore has a periodicity of 36^5 seconds
|
||||
(about 700 days).
|
||||
|
||||
5.2.2 Channel Delay
|
||||
|
||||
These channels MUST be subject to the "channel delay" mechanism
|
||||
described in section 5.1 (Channel Delay). However, the mechanism is
|
||||
slightly adapted to fit better.
|
||||
|
||||
Servers MUST keep track of all such channels which lose members as
|
||||
the result of a network split, no matter whether the user is a
|
||||
"channel operator" or not.
|
||||
|
||||
However, these channels do NOT ever become unavailable, it is always
|
||||
possible to join them even when they are empty.
|
||||
|
||||
5.2.3 Abuse Window
|
||||
|
||||
Because the periodicity is so long, attacks on a particular channel
|
||||
(name) may only occur once in a very long while. However, with luck
|
||||
and patience, it is still possible for a user to cause a channel
|
||||
collision. In order to avoid this, servers MUST "look in the future"
|
||||
and keep a list of channel names which identifier is about to be used
|
||||
(in the coming few days for example). Such list should remain small,
|
||||
not be a burden for servers to maintain and be used to avoid channel
|
||||
collisions by preventing the re-creation of such channel for a longer
|
||||
period of time than channel delay does.
|
||||
|
||||
Eventually a server MAY choose to extend this procedure to forbid
|
||||
creation of channels with the same shortname only (then ignoring the
|
||||
channel identifier).
|
||||
|
||||
5.2.4 Preserving Sanity In The Name Space
|
||||
|
||||
The combination of the mechanisms described in sections 5.2.2 and
|
||||
5.2.3 makes it quite difficult for a user to create a channel
|
||||
collision. However, another type of abuse consists of creating many
|
||||
channels having the same shortname, but different identifiers. To
|
||||
prevent this from happening, servers MUST forbid the creation of a
|
||||
new channel which has the same shortname of a channel currently
|
||||
existing.
|
||||
|
||||
5.2.5 Server Reop Mechanism
|
||||
|
||||
When a channel has been opless for longer than the "reop delay"
|
||||
period and has the channel flag 'r' set (See Section 4.2.7 (Server
|
||||
Reop Flag)), IRC servers are responsible for giving the channel
|
||||
operator status randomly to some of the members.
|
||||
|
||||
The exact logic used for this mechanism by the current implementation
|
||||
is described below. Servers MAY use a different logic, but that it
|
||||
is strongly RECOMMENDED that all servers use the same logic on a
|
||||
particular IRC network to maintain coherence as well as fairness.
|
||||
For the same reason, the "reop delay" SHOULD be uniform on all
|
||||
servers for a given IRC network. As for the "channel delay", the
|
||||
value of the "reop delay" SHOULD be set considering many factors
|
||||
among which are the size (user wise) of the IRC network, and the
|
||||
usual duration of network splits.
|
||||
|
||||
a) the reop mechanism is triggered after a random time following the
|
||||
expiration of the "reop delay". This should limit the eventuality
|
||||
of the mechanism being triggered at the same time (for the same
|
||||
channel) on two separate servers.
|
||||
|
||||
b) If the channel is small (five (5) users or less), and the "channel
|
||||
delay" for this channel has expired,
|
||||
Then reop all channel members if at least one member is local to
|
||||
the server.
|
||||
|
||||
c) If the channel is small (five (5) users or less), and the "channel
|
||||
delay" for this channel has expired, and the "reop delay" has
|
||||
expired for longer than its value,
|
||||
Then reop all channel members.
|
||||
|
||||
d) For other cases, reop at most one member on the channel, based on
|
||||
some method build into the server. If you don't reop a member, the
|
||||
method should be such that another server will probably op
|
||||
someone. The method SHOULD be the same over the whole network. A
|
||||
good heuristic could be just random reop.
|
||||
(The current implementation actually tries to choose a member
|
||||
local to the server who has not been idle for too long, eventually
|
||||
postponing action, therefore letting other servers have a chance
|
||||
to find a "not too idle" member. This is over complicated due to
|
||||
the fact that servers only know the "idle" time of their local
|
||||
users)
|
||||
|
||||
6. Current problems
|
||||
|
||||
There are a number of recognized problems with the way IRC channels
|
||||
are managed. Some of these can be directly attributed to the rules
|
||||
defined in this document, while others are the result of the
|
||||
underlying "IRC Server Protocol" [IRC-SERVER]. Although derived from
|
||||
RFC 1459 [IRC], this document introduces several novelties in an
|
||||
attempt to solve some of the known problems.
|
||||
|
||||
6.1 Labels
|
||||
|
||||
This document defines one of the many labels used by the IRC
|
||||
protocol. Although there are several distinct namespaces (based on
|
||||
the channel name prefix), duplicates inside each of these are not
|
||||
allowed. Currently, it is possible for users on different servers to
|
||||
pick the label which may result in collisions (with the exception of
|
||||
channels known to only one server where they can be averted).
|
||||
|
||||
6.1.1 Channel Delay
|
||||
|
||||
The channel delay mechanism described in section 5.1 (Tracking
|
||||
Recently Used Channels) and used for channels prefixed with the
|
||||
character '#' is a simple attempt at preventing collisions from
|
||||
happening. Experience has shown that, under normal circumstances, it
|
||||
|
||||
is very efficient; however, it obviously has severe limitations
|
||||
keeping it from being an adequate solution to the problem discussed
|
||||
here.
|
||||
|
||||
6.1.2 Safe Channels
|
||||
|
||||
"Safe channels" described in section 3.2 (Safe Channels) are a better
|
||||
way to prevent collisions from happening as it prevents users from
|
||||
having total control over the label they choose. The obvious
|
||||
drawback for such labels is that they are not user friendly.
|
||||
However, it is fairly trivial for a client program to improve on
|
||||
this.
|
||||
|
||||
6.2 Mode Propagation Delays
|
||||
|
||||
Because of network delays induced by the network, and because each
|
||||
server on the path is REQUIRED to check the validity of mode changes
|
||||
(e.g., user exists and has the right privileges), it is not unusual
|
||||
for a MODE message to only affect part of the network, often creating
|
||||
a discrepancy between servers on the current state of a channel.
|
||||
|
||||
While this may seem easy to fix (by having only the original server
|
||||
check the validity of mode changes), it was decided not to do so for
|
||||
various reasons. One concern is that servers cannot trust each
|
||||
other, and that a misbehaving servers can easily be detected. This
|
||||
way of doing so also stops wave effects on channels which are out of
|
||||
synch when mode changes are issued from different directions.
|
||||
|
||||
6.3 Collisions And Channel Modes
|
||||
|
||||
The "Internet Relay Chat: Server Protocol" document [IRC-SERVER]
|
||||
describes how channel data is exchanged when two servers connect to
|
||||
each other. Channel collisions (either legitimate or not) are
|
||||
treated as inclusive events, meaning that the resulting channel has
|
||||
for members all the users who are members of the channel on either
|
||||
server prior to the connection.
|
||||
|
||||
Similarly, each server sends the channel modes to the other one.
|
||||
Therefore, each server also receives these channel modes. There are
|
||||
three types of modes for a given channel: flags, masks, and data.
|
||||
The first two types are easy to deal with as they are either set or
|
||||
unset. If such a mode is set on one server, it MUST be set on the
|
||||
other server as a result of the connection.
|
||||
|
||||
As topics are not sent as part of this exchange, they are not a
|
||||
problem. However, channel modes 'l' and 'k' are exchanged, and if
|
||||
they are set on both servers prior to the connection, there is no
|
||||
mechanism to decide which of the two values takes precedence. It is
|
||||
left up to the users to fix the resulting discrepancy.
|
||||
|
||||
6.4 Resource Exhaustion
|
||||
|
||||
The mode based on masks defined in section 4.3 make the IRC servers
|
||||
(and network) vulnerable to a simple abuse of the system: a single
|
||||
channel operator can set as many different masks as possible on a
|
||||
particular channel. This can easily cause the server to waste
|
||||
memory, as well as network bandwidth (since the info is propagated to
|
||||
other servers). For this reason it is RECOMMENDED that a limit be
|
||||
put on the number of such masks per channels as mentioned in section
|
||||
4.3.
|
||||
|
||||
Moreover, more complex mechanisms MAY be used to avoid having
|
||||
redundant masks set for the same channel.
|
||||
|
||||
7. Security Considerations
|
||||
|
||||
7.1 Access Control
|
||||
|
||||
One of the main ways to control access to a channel is to use masks
|
||||
which are based on the username and hostname of the user connections.
|
||||
This mechanism can only be efficient and safe if the IRC servers have
|
||||
an accurate way of authenticating user connections, and if users
|
||||
cannot easily get around it. While it is in theory possible to
|
||||
implement such a strict authentication mechanism, most IRC networks
|
||||
(especially public networks) do not have anything like this in place
|
||||
and provide little guaranty about the accuracy of the username and
|
||||
hostname for a particular client connection.
|
||||
|
||||
Another way to control access is to use a channel key, but since this
|
||||
key is sent in plaintext, it is vulnerable to traditional man in the
|
||||
middle attacks.
|
||||
|
||||
7.2 Channel Privacy
|
||||
|
||||
Because channel collisions are treated as inclusive events (See
|
||||
Section 6.3), it is possible for users to join a channel overriding
|
||||
its access control settings. This method has long been used by
|
||||
individuals to "take over" channels by "illegitimately" gaining
|
||||
channel operator status on the channel. The same method can be used
|
||||
to find out the exact list of members of a channel, as well as to
|
||||
eventually receive some of the messages sent to the channel.
|
||||
|
||||
7.3 Anonymity
|
||||
|
||||
The anonymous channel flag (See Section 4.2.1) can be used to render
|
||||
all users on such channel "anonymous" by presenting all messages to
|
||||
the channel as originating from a pseudo user which nickname is
|
||||
"anonymous". This is done at the client-server level, and no
|
||||
anonymity is provided at the server-server level.
|
||||
|
||||
It should be obvious to readers, that the level of anonymity offered
|
||||
is quite poor and insecure, and that clients SHOULD display strong
|
||||
warnings for users joining such channels.
|
||||
|
||||
8. Current support and availability
|
||||
|
||||
Mailing lists for IRC related discussion:
|
||||
General discussion: ircd-users@irc.org
|
||||
Protocol development: ircd-dev@irc.org
|
||||
|
||||
Software implementations:
|
||||
ftp://ftp.irc.org/irc/server
|
||||
ftp://ftp.funet.fi/pub/unix/irc
|
||||
ftp://coombs.anu.edu.au/pub/irc
|
||||
|
||||
Newsgroup: alt.irc
|
||||
|
||||
9. Acknowledgements
|
||||
|
||||
Parts of this document were copied from the RFC 1459 [IRC] which
|
||||
first formally documented the IRC Protocol. It has also benefited
|
||||
from many rounds of review and comments. In particular, the
|
||||
following people have made significant contributions to this
|
||||
document:
|
||||
|
||||
Matthew Green, Michael Neumayer, Volker Paulsen, Kurt Roeckx, Vesa
|
||||
Ruokonen, Magnus Tjernstrom, Stefan Zehl.
|
||||
|
||||
10. References
|
||||
|
||||
[KEYWORDS] Bradner, S., "Key words for use in RFCs to Indicate
|
||||
Requirement Levels", BCP 14, RFC 2119, March 1997.
|
||||
|
||||
[IRC] Oikarinen, J. and D. Reed, "Internet Relay Chat
|
||||
Protocol", RFC 1459, May 1993.
|
||||
|
||||
[IRC-ARCH] Kalt, C., "Internet Relay Chat: Architecture", RFC 2810,
|
||||
April 2000.
|
||||
|
||||
[IRC-CLIENT] Kalt, C., "Internet Relay Chat: Client Protocol", RFC
|
||||
2812, April 2000.
|
||||
|
||||
[IRC-SERVER] Kalt, C., "Internet Relay Chat: Server Protocol", RFC
|
||||
2813, April 2000.
|
||||
|
||||
11. Author's Address
|
||||
|
||||
Christophe Kalt
|
||||
99 Teaneck Rd, Apt #117
|
||||
Ridgefield Park, NJ 07660
|
||||
USA
|
||||
|
||||
EMail: kalt@stealth.net
|
||||
|
||||
12. Full Copyright Statement
|
||||
|
||||
Copyright (C) The Internet Society (2000). All Rights Reserved.
|
||||
|
||||
This document and translations of it may be copied and furnished to
|
||||
others, and derivative works that comment on or otherwise explain it
|
||||
or assist in its implementation may be prepared, copied, published
|
||||
and distributed, in whole or in part, without restriction of any
|
||||
kind, provided that the above copyright notice and this paragraph are
|
||||
included on all such copies and derivative works. However, this
|
||||
document itself may not be modified in any way, such as by removing
|
||||
the copyright notice or references to the Internet Society or other
|
||||
Internet organizations, except as needed for the purpose of
|
||||
developing Internet standards in which case the procedures for
|
||||
copyrights defined in the Internet Standards process must be
|
||||
followed, or as required to translate it into languages other than
|
||||
English.
|
||||
|
||||
The limited permissions granted above are perpetual and will not be
|
||||
revoked by the Internet Society or its successors or assigns.
|
||||
|
||||
This document and the information contained herein is provided on an
|
||||
"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
|
||||
TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
|
||||
BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
|
||||
HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
|
||||
|
||||
Acknowledgement
|
||||
|
||||
Funding for the RFC Editor function is currently provided by the
|
||||
Internet Society.
|
||||
|
||||
|
||||
|
||||
|
||||
Previous: RFC 2810 - Internet Relay Next: RFC 2812 - Internet Relay Chat:
|
||||
Chat: Architecture Client Protocol
|
||||
|
||||
|
||||
|
||||
----------------------------------------------------------------------
|
||||
|
||||
[ RFC Index | RFC Search | Usenet FAQs | Web FAQs | Documents | Cities ]
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,43 @@
|
|||
from util import hook
|
||||
import random
|
||||
import re
|
||||
|
||||
r = "\x02\x0305" # red
|
||||
g = "\x02\x0303" # green
|
||||
y = "\x02\x0308" # yellow
|
||||
|
||||
answers = [g + "As I see it, yes",
|
||||
g + "It is certain",
|
||||
g + "It is decidedly so",
|
||||
g + "Most likely",
|
||||
g + "Outlook good",
|
||||
g + "Signs point to yes",
|
||||
g + "One would be wise to think so",#
|
||||
g + "Naturally",#
|
||||
g + "Without a doubt",
|
||||
g + "Yes",
|
||||
g + "Yes, definitely",
|
||||
g + "You may rely on it",
|
||||
y + "Reply hazy, try again",
|
||||
y + "Ask again later",
|
||||
y + "Better not tell you now",
|
||||
y + "Cannot predict now",
|
||||
y + "Concentrate and ask again",
|
||||
y + "You know the answer better than I",#
|
||||
y + "Maybe...",#
|
||||
r + "You're kidding, right?",#
|
||||
r + "Don't count on it",
|
||||
r + "In your dreams", #
|
||||
r + "My reply is no",
|
||||
r + "My sources say no",
|
||||
r + "Outlook not so good",
|
||||
r + "Very doubtful"]
|
||||
|
||||
@hook.command('8ball')
|
||||
def ask(inp, me=None):
|
||||
".8ball <question> - The all knowing magic eight ball, in electronic form. Ask a question and the answer shall be provided."
|
||||
global nextresponsenumber
|
||||
inp = inp.strip()
|
||||
if re.match("[a-zA-Z0-9]", inp[-1]):
|
||||
inp += "?"
|
||||
me("shakes the magic 8 ball... %s" % (random.choice(answers)))
|
|
@ -0,0 +1,119 @@
|
|||
# Shitty plugin made by iloveportalz0r
|
||||
# Broken by The Noodle
|
||||
from util import hook
|
||||
|
||||
@hook.command
|
||||
def join(inp, input=None, db=None, notice=None):
|
||||
".join <channel> -- joins a channel"
|
||||
if input.nick not in input.bot.config["admins"]:
|
||||
notice("Only bot admins can use this command!")
|
||||
return
|
||||
chan = inp.split(' ', 1)
|
||||
#if len(chan) != 1:
|
||||
#return "Usage: omg please join <channel>"
|
||||
notice("Joining " + inp)
|
||||
input.conn.send("JOIN " + inp)
|
||||
|
||||
@hook.command
|
||||
def cycle(inp, input=None, db=None, notice=None):
|
||||
".cycle <channel> -- cycles a channel"
|
||||
if input.nick not in input.bot.config["admins"]:
|
||||
notice("Only bot admins can use this command!")
|
||||
return
|
||||
notice("Cycling " + inp + ".")
|
||||
input.conn.send("PART " + inp)
|
||||
input.conn.send("JOIN " + inp)
|
||||
|
||||
@hook.command
|
||||
def part(inp, input=None, notice=None):
|
||||
".part <channel> -- leaves a channel"
|
||||
if input.nick not in input.bot.config["admins"]:
|
||||
notice("Only bot admins can use this command!")
|
||||
return
|
||||
chan = inp.split(' ', 1)
|
||||
#if len(chan) != 1:
|
||||
#return "Usage: omg please part <channel>"
|
||||
notice("Parting from " + inp + ".")
|
||||
input.conn.send("PART " + inp)
|
||||
|
||||
@hook.command
|
||||
def chnick(inp, input=None, notice=None):
|
||||
".chnick <nick> - Change the nick!"
|
||||
if input.nick not in input.bot.config["admins"]:
|
||||
notice("Only bot admins can use this command!")
|
||||
return
|
||||
chan = inp.split(' ', 1)
|
||||
#if len(chan) != 1:
|
||||
#return "Usage: omg please part <channel>"
|
||||
notice("Changing nick to " + inp + ".")
|
||||
input.conn.send("NICK " + inp)
|
||||
|
||||
@hook.command
|
||||
def raw(inp, input=None, notice=None):
|
||||
".raw <command> - Send a RAW IRC command!"
|
||||
if input.nick not in input.bot.config["admins"]:
|
||||
notice("Only bot admins can use this command!")
|
||||
return
|
||||
chan = inp.split(' ', 1)
|
||||
notice("Raw command sent.")
|
||||
input.conn.send(inp)
|
||||
|
||||
@hook.command
|
||||
def kick(inp, input=None, notice=None):
|
||||
".kick [channel] <user> [reason] -- kick a user!"
|
||||
if input.nick not in input.bot.config["admins"]:
|
||||
notice("Only bot admins can use this command!")
|
||||
return
|
||||
stuff = inp.split(" ")
|
||||
if stuff[0][0] == "#":
|
||||
out = "KICK " + stuff[0] + " " + stuff[1]
|
||||
if len(stuff) > 2:
|
||||
reason = ""
|
||||
for x in stuff[2:]:
|
||||
reason = reason + x + " "
|
||||
reason = reason[:-1]
|
||||
out = out+" :"+reason
|
||||
else:
|
||||
out = "KICK " + input.chan + " " + stuff[0]
|
||||
if len(stuff) > 1:
|
||||
reason = ""
|
||||
for x in stuff[1:]:
|
||||
reason = reason + x + " "
|
||||
reason = reason[:-1]
|
||||
out = out + " :" + reason
|
||||
|
||||
input.conn.send(out)
|
||||
|
||||
@hook.command
|
||||
def say(inp, input=None, notice=None):
|
||||
".say [channel] <message> -- makes the bot say <message> in [channel]. if [channel] is blank the bot will say the <message> in the channel the command was used in."
|
||||
if input.nick not in input.bot.config["admins"]:
|
||||
notice("Only bot admins can use this command!")
|
||||
return
|
||||
stuff = inp.split(" ")
|
||||
if stuff[0][0] == "#":
|
||||
message = ""
|
||||
for x in stuff[1:]:
|
||||
message = message + x + " "
|
||||
message = message[:-1]
|
||||
out = "PRIVMSG " + stuff[0] + " :" + message
|
||||
else:
|
||||
message = ""
|
||||
for x in stuff[0:]:
|
||||
message = message + x + " "
|
||||
message = message[:-1]
|
||||
out = "PRIVMSG " + input.chan + " :" + message
|
||||
input.conn.send(out)
|
||||
|
||||
@hook.command
|
||||
def topic(inp, input=None, notice=None):
|
||||
".topic [channel] <topic> -- change the topic of a channel"
|
||||
if input.nick not in input.bot.config["admins"]:
|
||||
notice("Only bot admins can use this command!")
|
||||
return
|
||||
stuff = inp.split(" ")
|
||||
if stuff[0][0] == "#":
|
||||
out = "TOPIC " + stuff[0] + " :" + stuff[1]
|
||||
else:
|
||||
out = "TOPIC " + input.chan + " :" + stuff[0]
|
||||
input.conn.send(out)
|
|
@ -0,0 +1,33 @@
|
|||
def yaml_load(filename):
|
||||
import yaml
|
||||
fileHandle = open(filename, 'r')
|
||||
stuff = yaml.load(fileHandle.read())
|
||||
fileHandle.close()
|
||||
return stuff
|
||||
|
||||
def yaml_save(stuff, filename):
|
||||
import yaml
|
||||
fileHandle = open (filename, 'w' )
|
||||
fileHandle.write (yaml.dump(stuff))
|
||||
fileHandle.close()
|
||||
|
||||
from util import hook
|
||||
|
||||
@hook.event('*')
|
||||
def tellinput(paraml, input=None, say=None):
|
||||
# import time
|
||||
# now = time.time()
|
||||
# spam = yaml_load('spam')
|
||||
# if spam[input.nick]:
|
||||
# spam[input.nick].append(time.time())
|
||||
# else:
|
||||
# spam[input.nick] = [time.time()]
|
||||
# for x in spam[input.nick]:
|
||||
# if now - x > 5:
|
||||
# spam[input.nick].pop(x)
|
||||
# if len(spam[input.nick]) > 8:
|
||||
# say(":O")
|
||||
# say("HOW COULD YOU "+input.nick)
|
||||
# say("lol!")
|
||||
# yaml_save(spam,'spam')
|
||||
return
|
|
@ -0,0 +1,88 @@
|
|||
'''brainfuck interpreter adapted from (public domain) code at
|
||||
http://brainfuck.sourceforge.net/brain.py'''
|
||||
|
||||
import re
|
||||
import random
|
||||
|
||||
from util import hook
|
||||
|
||||
|
||||
BUFFER_SIZE = 5000
|
||||
MAX_STEPS = 1000000
|
||||
|
||||
|
||||
@hook.command
|
||||
def bf(inp):
|
||||
".bf <prog> -- executes brainfuck program <prog>"""
|
||||
|
||||
program = re.sub('[^][<>+-.,]', '', inp)
|
||||
|
||||
# create a dict of brackets pairs, for speed later on
|
||||
brackets = {}
|
||||
open_brackets = []
|
||||
for pos in range(len(program)):
|
||||
if program[pos] == '[':
|
||||
open_brackets.append(pos)
|
||||
elif program[pos] == ']':
|
||||
if len(open_brackets) > 0:
|
||||
brackets[pos] = open_brackets[-1]
|
||||
brackets[open_brackets[-1]] = pos
|
||||
open_brackets.pop()
|
||||
else:
|
||||
return 'unbalanced brackets'
|
||||
if len(open_brackets) != 0:
|
||||
return 'unbalanced brackets'
|
||||
|
||||
# now we can start interpreting
|
||||
ip = 0 # instruction pointer
|
||||
mp = 0 # memory pointer
|
||||
steps = 0
|
||||
memory = [0] * BUFFER_SIZE # initial memory area
|
||||
rightmost = 0
|
||||
output = "" # we'll save the output here
|
||||
|
||||
# the main program loop:
|
||||
while ip < len(program):
|
||||
c = program[ip]
|
||||
if c == '+':
|
||||
memory[mp] = memory[mp] + 1 % 256
|
||||
elif c == '-':
|
||||
memory[mp] = memory[mp] - 1 % 256
|
||||
elif c == '>':
|
||||
mp += 1
|
||||
if mp > rightmost:
|
||||
rightmost = mp
|
||||
if mp >= len(memory):
|
||||
# no restriction on memory growth!
|
||||
memory.extend([0] * BUFFER_SIZE)
|
||||
elif c == '<':
|
||||
mp = mp - 1 % len(memory)
|
||||
elif c == '.':
|
||||
output += chr(memory[mp])
|
||||
if len(output) > 500:
|
||||
break
|
||||
elif c == ',':
|
||||
memory[mp] = random.randint(1, 255)
|
||||
elif c == '[':
|
||||
if memory[mp] == 0:
|
||||
ip = brackets[ip]
|
||||
elif c == ']':
|
||||
if memory[mp] != 0:
|
||||
ip = brackets[ip]
|
||||
|
||||
ip += 1
|
||||
steps += 1
|
||||
if steps > MAX_STEPS:
|
||||
if output == '':
|
||||
output = '(no output)'
|
||||
output += '[exceeded %d iterations]' % MAX_STEPS
|
||||
break
|
||||
|
||||
stripped_output = re.sub(r'[\x00-\x1F]', '', output)
|
||||
|
||||
if stripped_output == '':
|
||||
if output != '':
|
||||
return 'no printable output'
|
||||
return 'no output'
|
||||
|
||||
return stripped_output[:430].decode('utf8', 'ignore')
|
|
@ -0,0 +1,10 @@
|
|||
from util import http, hook
|
||||
|
||||
|
||||
@hook.command(autohelp=False)
|
||||
def bitcoin(inp, say=None):
|
||||
".bitcoin -- gets current exchange rate for bitcoins from mtgox"
|
||||
data = http.get_json("https://mtgox.com/code/data/ticker.php")
|
||||
ticker = data['ticker']
|
||||
say("Current: \x0307$%(buy).2f\x0f - High: \x0307$%(high).2f\x0f"
|
||||
" - Low: \x0307$%(low).2f\x0f - Volume: %(vol)s" % ticker)
|
|
@ -0,0 +1,17 @@
|
|||
import re
|
||||
import random
|
||||
|
||||
from util import hook
|
||||
|
||||
|
||||
@hook.command
|
||||
def choose(inp):
|
||||
".choose <choice1>, <choice2>, ... <choicen> -- makes a decision"
|
||||
|
||||
c = re.findall(r'([^,]+)', inp)
|
||||
if len(c) == 1:
|
||||
c = re.findall(r'(\S+)', inp)
|
||||
if len(c) == 1:
|
||||
return 'the decision is up to you'
|
||||
|
||||
return random.choice(c).strip()
|
|
@ -0,0 +1,38 @@
|
|||
# # Lukeroge
|
||||
from util import hook
|
||||
import random
|
||||
|
||||
@hook.command(autohelp=False)
|
||||
def coin(inp):
|
||||
".coin - Flips a coin and shares the result."
|
||||
|
||||
flip = random.randint(0,1)
|
||||
if flip == 1:
|
||||
sidename = "heads"
|
||||
else:
|
||||
sidename = "tails"
|
||||
|
||||
message = "You flip a coin and it lands on " + sidename + "!"
|
||||
|
||||
|
||||
return message
|
||||
|
||||
@hook.command(autohelp=False)
|
||||
def coins(inp):
|
||||
".coins - Flips two coins and shares the results."
|
||||
|
||||
flip2 = random.randint(0,1)
|
||||
if flip2 == 1:
|
||||
sidename2 = "heads"
|
||||
else:
|
||||
sidename2 = "tails"
|
||||
flip = random.randint(0,1)
|
||||
if flip == 1:
|
||||
sidename = "heads"
|
||||
else:
|
||||
sidename = "tails"
|
||||
|
||||
message = "You flip two coins. You get a " + sidename + ", and a " + sidename2 + "!"
|
||||
|
||||
|
||||
return message
|
|
@ -0,0 +1,89 @@
|
|||
"""
|
||||
dice.py: written by Scaevolus 2008, updated 2009
|
||||
simulates dicerolls
|
||||
"""
|
||||
import re
|
||||
import random
|
||||
|
||||
from util import hook
|
||||
|
||||
|
||||
whitespace_re = re.compile(r'\s+')
|
||||
valid_diceroll = r'^([+-]?(?:\d+|\d*d(?:\d+|F))(?:[+-](?:\d+|\d*d(?:\d+|F)))*)( .+)?$'
|
||||
valid_diceroll_re = re.compile(valid_diceroll, re.I)
|
||||
sign_re = re.compile(r'[+-]?(?:\d*d)?(?:\d+|F)', re.I)
|
||||
split_re = re.compile(r'([\d+-]*)d?(F|\d*)', re.I)
|
||||
|
||||
|
||||
def nrolls(count, n):
|
||||
"roll an n-sided die count times"
|
||||
if n == "F":
|
||||
return [random.randint(-1, 1) for x in xrange(min(count, 100))]
|
||||
if n < 2: # it's a coin
|
||||
if count < 100:
|
||||
return [random.randint(0, 1) for x in xrange(count)]
|
||||
else: # fake it
|
||||
return [int(random.normalvariate(.5*count, (.75*count)**.5))]
|
||||
else:
|
||||
if count < 100:
|
||||
return [random.randint(1, n) for x in xrange(count)]
|
||||
else: # fake it
|
||||
return [int(random.normalvariate(.5*(1+n)*count,
|
||||
(((n+1)*(2*n+1)/6.-(.5*(1+n))**2)*count)**.5))]
|
||||
|
||||
|
||||
@hook.command('roll')
|
||||
#@hook.regex(valid_diceroll, re.I)
|
||||
@hook.command
|
||||
def dice(inp):
|
||||
".dice <diceroll> -- simulates dicerolls, e.g. .dice 2d20-d5+4 roll 2 " \
|
||||
"D20s, subtract 1D5, add 4"
|
||||
|
||||
try: # if inp is a re.match object...
|
||||
(inp, desc) = inp.groups()
|
||||
except AttributeError:
|
||||
(inp, desc) = valid_diceroll_re.match(inp).groups()
|
||||
|
||||
if "d" not in inp:
|
||||
return
|
||||
|
||||
spec = whitespace_re.sub('', inp)
|
||||
if not valid_diceroll_re.match(spec):
|
||||
return "Invalid diceroll"
|
||||
groups = sign_re.findall(spec)
|
||||
|
||||
total = 0
|
||||
rolls = []
|
||||
|
||||
for roll in groups:
|
||||
count, side = split_re.match(roll).groups()
|
||||
count = int(count) if count not in " +-" else 1
|
||||
if side.upper() == "F": # fudge dice are basically 1d3-2
|
||||
for fudge in nrolls(count, "F"):
|
||||
if fudge == 1:
|
||||
rolls.append("\x033+\x0F")
|
||||
elif fudge == -1:
|
||||
rolls.append("\x034-\x0F")
|
||||
else:
|
||||
rolls.append("0")
|
||||
total += fudge
|
||||
elif side == "":
|
||||
total += count
|
||||
else:
|
||||
side = int(side)
|
||||
try:
|
||||
if count > 0:
|
||||
dice = nrolls(count, side)
|
||||
rolls += map(str, dice)
|
||||
total += sum(dice)
|
||||
else:
|
||||
dice = nrolls(-count, side)
|
||||
rolls += [str(-x) for x in dice]
|
||||
total -= sum(dice)
|
||||
except OverflowError:
|
||||
return "Thanks for overflowing a float, jerk >:["
|
||||
|
||||
if desc:
|
||||
return "%s: %d (%s=%s)" % (desc.strip(), total, inp, ", ".join(rolls))
|
||||
else:
|
||||
return "%d (%s=%s)" % (total, inp, ", ".join(rolls))
|
|
@ -0,0 +1,110 @@
|
|||
import re
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
@hook.command('u')
|
||||
@hook.command
|
||||
def urban(inp):
|
||||
'''.u/.urban <phrase> -- looks up <phrase> on urbandictionary.com'''
|
||||
|
||||
url = 'http://www.urbandictionary.com/define.php'
|
||||
page = http.get_html(url, term=inp)
|
||||
words = page.xpath("//td[@class='word']")
|
||||
defs = page.xpath("//div[@class='definition']")
|
||||
|
||||
if not defs:
|
||||
return 'No definitions found :('
|
||||
|
||||
out = '' + words[0].text_content().strip() + ': ' + ' '.join(
|
||||
defs[0].text_content().split())
|
||||
|
||||
if len(out) > 400:
|
||||
out = out[:out.rfind(' ', 0, 400)] + '...'
|
||||
|
||||
return out
|
||||
|
||||
|
||||
# define plugin by GhettoWizard & Scaevolus
|
||||
@hook.command('dictionary')
|
||||
@hook.command
|
||||
def define(inp):
|
||||
".define/.dictionary <word> -- fetches definition of <word>"
|
||||
|
||||
url = 'http://ninjawords.com/'
|
||||
|
||||
h = http.get_html(url + http.quote_plus(inp))
|
||||
|
||||
definition = h.xpath('//dd[@class="article"] | '
|
||||
'//div[@class="definition"] |'
|
||||
'//div[@class="example"]')
|
||||
|
||||
if not definition:
|
||||
return 'No results for ' + inp + ' :('
|
||||
|
||||
def format_output(show_examples):
|
||||
result = '%s: ' % h.xpath('//dt[@class="title-word"]/a/text()')[0]
|
||||
|
||||
correction = h.xpath('//span[@class="correct-word"]/text()')
|
||||
if correction:
|
||||
result = 'definition for "%s": ' % correction[0]
|
||||
|
||||
sections = []
|
||||
for section in definition:
|
||||
if section.attrib['class'] == 'article':
|
||||
sections += [[section.text_content() + ': ']]
|
||||
elif section.attrib['class'] == 'example':
|
||||
if show_examples:
|
||||
sections[-1][-1] += ' ' + section.text_content()
|
||||
else:
|
||||
sections[-1] += [section.text_content()]
|
||||
|
||||
for article in sections:
|
||||
result += article[0]
|
||||
if len(article) > 2:
|
||||
result += ' '.join('%d. %s' % (n + 1, section)
|
||||
for n, section in enumerate(article[1:]))
|
||||
else:
|
||||
result += article[1] + ' '
|
||||
|
||||
synonyms = h.xpath('//dd[@class="synonyms"]')
|
||||
if synonyms:
|
||||
result += synonyms[0].text_content()
|
||||
|
||||
result = re.sub(r'\s+', ' ', result)
|
||||
result = re.sub('\xb0', '', result)
|
||||
return result
|
||||
|
||||
result = format_output(True)
|
||||
if len(result) > 450:
|
||||
result = format_output(False)
|
||||
|
||||
if len(result) > 450:
|
||||
result = result[:result.rfind(' ', 0, 450)]
|
||||
result = re.sub(r'[^A-Za-z]+\.?$', '', result) + ' ...'
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@hook.command('e')
|
||||
@hook.command
|
||||
def etymology(inp):
|
||||
".e/.etymology <word> -- Retrieves the etymology of chosen word"
|
||||
|
||||
url = 'http://www.etymonline.com/index.php'
|
||||
|
||||
h = http.get_html(url, term=inp)
|
||||
|
||||
etym = h.xpath('//dl')
|
||||
|
||||
if not etym:
|
||||
return 'No etymology found for ' + inp + ' :('
|
||||
|
||||
etym = etym[0].text_content()
|
||||
|
||||
etym = ' '.join(etym.split())
|
||||
|
||||
if len(etym) > 400:
|
||||
etym = etym[:etym.rfind(' ', 0, 400)] + ' ...'
|
||||
|
||||
return etym
|
|
@ -0,0 +1,20 @@
|
|||
import urlparse
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
@hook.command
|
||||
def down(inp):
|
||||
'''.down <url> -- checks to see if the site is down'''
|
||||
|
||||
if 'http://' not in inp:
|
||||
inp = 'http://' + inp
|
||||
|
||||
inp = 'http://' + urlparse.urlparse(inp).netloc
|
||||
|
||||
# http://mail.python.org/pipermail/python-list/2006-December/589854.html
|
||||
try:
|
||||
http.get(inp, get_method='HEAD')
|
||||
return inp + ' seems to be up'
|
||||
except http.URLError:
|
||||
return inp + ' seems to be down'
|
|
@ -0,0 +1,104 @@
|
|||
"""
|
||||
remember.py: written by Scaevolus 20101
|
||||
"""
|
||||
|
||||
from util import hook
|
||||
import re
|
||||
|
||||
|
||||
def db_init(db):
|
||||
db.execute("create table if not exists mem(word, data, nick,"
|
||||
" primary key(word))")
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_memory(db, word):
|
||||
|
||||
row = db.execute("select data from mem where word=lower(?)", [word]).fetchone()
|
||||
if row:
|
||||
return row[0]
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
@hook.regex(r'^\+ ?(.*)')
|
||||
@hook.command("r")
|
||||
def remember(inp, nick='', db=None, say=None, input=None, notice=None):
|
||||
"+<word> [+]<data> -- maps word to data in the memory"
|
||||
if input.nick not in input.bot.config["admins"]:
|
||||
return
|
||||
binp = inp.group(0)
|
||||
bind = binp.replace('+', '', 1)
|
||||
db_init(db)
|
||||
|
||||
|
||||
append = False
|
||||
|
||||
try:
|
||||
head, tail = bind.split(None, 1)
|
||||
except ValueError:
|
||||
return remember.__doc__
|
||||
|
||||
data = get_memory(db, head)
|
||||
|
||||
if tail[0] == '+':
|
||||
append = True
|
||||
# ignore + symbol
|
||||
new = tail[1:]
|
||||
_head, _tail = data.split(None, 1)
|
||||
# data is stored with the input so ignore it when re-adding it
|
||||
import string
|
||||
if len(tail) > 1 and tail[1] in (string.punctuation + ' '):
|
||||
tail = _tail + new
|
||||
else:
|
||||
tail = _tail + ' ' + new
|
||||
|
||||
db.execute("replace into mem(word, data, nick) values"
|
||||
" (lower(?),?,?)", (head, tail, nick))
|
||||
db.commit()
|
||||
|
||||
if data:
|
||||
if append:
|
||||
notice("Appending %s to %s" % (new, data.replace('"', "''")))
|
||||
else:
|
||||
notice('Forgetting existing data (%s), remembering this instead!' % \
|
||||
data.replace('"', "''"))
|
||||
return
|
||||
else:
|
||||
notice('Remembered!')
|
||||
return
|
||||
|
||||
|
||||
@hook.command
|
||||
def forget(inp, db=None):
|
||||
"-<word> -- forgets the mapping that word had"
|
||||
|
||||
binp = inp.group(0)
|
||||
bind = binp.replace('-', '', 1)
|
||||
print bind
|
||||
|
||||
try:
|
||||
head, tail = bind.split(None, 1)
|
||||
except ValueError:
|
||||
return remember.__doc__
|
||||
|
||||
db_init(db)
|
||||
data = get_memory(db, binp)
|
||||
|
||||
if data:
|
||||
db.execute("delete from mem where word=lower(?)",
|
||||
(inp))
|
||||
db.commit()
|
||||
return 'forgot `%s`' % data.replace('`', "'")
|
||||
else:
|
||||
return "I don't know about that."
|
||||
|
||||
@hook.command("info")
|
||||
@hook.regex(r'^\? ?(.+)')
|
||||
def question(inp, say=None, db=None):
|
||||
"?<word> -- shows what data is associated with word"
|
||||
db_init(db)
|
||||
|
||||
data = get_memory(db, inp.group(1).strip())
|
||||
if data:
|
||||
say(data)
|
|
@ -0,0 +1,67 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from util import hook
|
||||
import random
|
||||
|
||||
@hook.command
|
||||
def flip(inp, flip_count=0, say = None):
|
||||
".flip <text> -- flips the given text"
|
||||
guy = unicode(random.choice(flips), 'utf8')
|
||||
inp = inp.lower()
|
||||
inp = inp[::-1]
|
||||
reps = 0
|
||||
for n in xrange(len(inp)):
|
||||
rep = character_replacements.get(inp[n])
|
||||
if rep:
|
||||
inp = inp[:n] + rep.decode('utf8') + inp[n + 1:]
|
||||
reps += 1
|
||||
if reps == flip_count:
|
||||
break
|
||||
say(guy + u" ︵ " + inp)
|
||||
|
||||
flips = ["(屮ಠ︵ಠ)屮",
|
||||
"( ノ♉︵♉ )ノ",
|
||||
"(╯°□°)╯",
|
||||
"( ノ⊙︵⊙)ノ"]
|
||||
|
||||
character_replacements = {
|
||||
'a': 'ɐ',
|
||||
'b': 'q',
|
||||
'c': 'ɔ',
|
||||
'd': 'p',
|
||||
'e': 'ǝ',
|
||||
'f': 'ɟ',
|
||||
'g': 'b',
|
||||
'h': 'ɥ',
|
||||
'i': 'ı',
|
||||
'j': 'ظ',
|
||||
'k': 'ʞ',
|
||||
'l': 'ן',
|
||||
'm': 'ɯ',
|
||||
'n': 'u',
|
||||
'o': 'o',
|
||||
'p': 'd',
|
||||
'q': 'b',
|
||||
'r': 'ɹ',
|
||||
's': 's',
|
||||
't': 'ʇ',
|
||||
'u': 'n',
|
||||
'v': 'ʌ',
|
||||
'w': 'ʍ',
|
||||
'x': 'x',
|
||||
'y': 'ʎ',
|
||||
'z': 'z',
|
||||
'?': '¿',
|
||||
'.': '˙',
|
||||
'/': '\\',
|
||||
'\\': '/',
|
||||
'(': ')',
|
||||
')': '(',
|
||||
'<': '>',
|
||||
'>': '<',
|
||||
'[': ']',
|
||||
']': '[',
|
||||
'{': '}',
|
||||
'}': '{',
|
||||
'\'': ',',
|
||||
'_': '‾'}
|
|
@ -0,0 +1,59 @@
|
|||
from util import hook
|
||||
import re
|
||||
import random
|
||||
|
||||
flirts = ["I bet your name's Mickey, 'cause you're so fine.",
|
||||
"Hey, pretty mama. You smell kinda pretty, wanna smell me?",
|
||||
"I better get out my library card, 'cause I'm checkin' you out.",
|
||||
"If you were a booger, I'd pick you.",
|
||||
"If I could rearrange the alphabet, I would put U and I together.",
|
||||
"I've been bad, take me to your room.",
|
||||
"I think Heaven's missing an angel.",
|
||||
"That shirt looks good on you, it'd look better on my bedroom floor.",
|
||||
"I cant help to notice but you look a lot like my next girlfriend",
|
||||
"Aren't your feet tired? Because you've been running through my mind all day.",
|
||||
"I must be asleep, 'cause you are a dream come true. Also, I'm slightly damp.",
|
||||
"I like large posteriors and I cannot prevaricate.",
|
||||
"How you doin'?",
|
||||
"If I said you had a good body, would you hold it against me?",
|
||||
"Hey, baby cakes.",
|
||||
"Nice butt.",
|
||||
"I love you like a fat kid loves cake.",
|
||||
"Do you believe in love at first sight? Or should I walk by again...?",
|
||||
"Want to see my good side? Hahaha, that was a trick question, all I have are good sides.",
|
||||
"You look like a woman who appreciates the finer things in life. Come over here and feel my velour bedspread.",
|
||||
"Now you're officially my woman. Kudos! I can't say I don't envy you.",
|
||||
"I find that the most erotic part of a woman is the boobies.",
|
||||
"If you want to climb aboard the Love Train, you've got to stand on the Love Tracks. But you might just get smushed by a very sensual cow-catcher.",
|
||||
"Lets say you and I knock some very /sensual/ boots.",
|
||||
"I lost my phone number, can I have yours?",
|
||||
"Does this rag smell like chloroform to you? ",
|
||||
"I'm here, where are your other two wishes?",
|
||||
"Apart from being sexy, what do you do for a living?",
|
||||
"Hi, I'm Mr. Right. Someone said you were looking for me. ",
|
||||
"You got something on your chest: My eyes.",
|
||||
"Are you from Tennessee? Cause you're the only TEN I see.",
|
||||
"Are you an alien? Because you just abducted my heart.",
|
||||
"Excuse me, but I think you dropped something!!! MY JAW!!",
|
||||
"If I followed you home, would you keep me?",
|
||||
"Where have you been all my life?",
|
||||
"I'm just a love machine, and I don't work for nobody but you",
|
||||
"Do you live on a chicken farm? Because you sure know how to raise cocks.",
|
||||
"Are you wearing space pants? Because your ass is out of this world.",
|
||||
"Nice legs. What time do they open?",
|
||||
"Your daddy must have been a baker, because you've got a nice set of buns."]
|
||||
|
||||
@hook.command(autohelp=False)
|
||||
def flirt(inp, nick=None, me=None, input=None):
|
||||
".flirt -- make mau5bot flirt!"
|
||||
|
||||
msg = "flirts with " + nick + "... \"" + random.choice(flirts) + "\""
|
||||
if re.match("^[A-Za-z0-9_|.-\]\[]*$", inp.lower()) and inp != "":
|
||||
msg = "flirts with " + inp + "... \"" + random.choice(flirts) + "\""
|
||||
|
||||
if inp == input.conn.nick.lower() or inp == "itself":
|
||||
msg = "flirts with itself"
|
||||
|
||||
me(msg)
|
||||
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
import re
|
||||
|
||||
from util import hook, http, misc
|
||||
from urlparse import urljoin
|
||||
from BeautifulSoup import BeautifulSoup
|
||||
|
||||
|
||||
base_url = 'http://www.fmylife.com/'
|
||||
rand_url = urljoin(base_url, 'random')
|
||||
spec_url = urljoin(base_url, '%d')
|
||||
error = 'Today I couldn\'t seem to access fmylife.com.. FML'
|
||||
|
||||
@hook.command(autohelp=False)
|
||||
@hook.command("fml")
|
||||
def fmylife(inp):
|
||||
|
||||
page = http.get(rand_url)
|
||||
soup = BeautifulSoup(page)
|
||||
|
||||
soup.find('div', id='submit').extract()
|
||||
post = soup.body.find('div', 'post')
|
||||
id = int(post.find('a', 'fmllink')['href'].split('/')[-1])
|
||||
body = strip_html(decode(' '.join(link.renderContents() for link in post('a', 'fmllink')), 'utf-8'))
|
||||
return u'%s: (%d) %s' % (nick, id, body)
|
|
@ -0,0 +1,67 @@
|
|||
from util import hook
|
||||
import re
|
||||
import random
|
||||
|
||||
fortunes = ["Help! I'm stuck in the fortune cookie factory!",
|
||||
"He who laughs at himself never runs out of things to laugh at.",
|
||||
"The world is your oyster.",
|
||||
"Today will be a good day.",
|
||||
"Only listen to the Hoss Fortune Cookies. Disregard all other fortune telling units.",
|
||||
"Life's short, party naked.",
|
||||
"Haters gonna hate.",
|
||||
"You are amazing and let no one tell you otherwise.",
|
||||
"A starship ride has been promised to you by the galactic wizard.",
|
||||
"That wasn’t chicken.",
|
||||
"Don’t fry bacon in the nude.",
|
||||
"Take calculated risks. That is quite different from being rash.",
|
||||
"DO THE IMPOSSIBLE, SEE THE INVISIBLE.",
|
||||
"You cannot plough a field by turning it over in your mind. Unless you have telekinesis.",
|
||||
"No one can make you feel inferior without your consent.",
|
||||
"Never lose the ability to find beauty in ordinary things.",
|
||||
"Ignore previous fortune.",
|
||||
"Smile more.",
|
||||
"You are the dancing queen.",
|
||||
"YOU'RE THE BEST AROUND, NOTHIN'S GONNA EVER KEEP YA DOWN.",
|
||||
"The cake is a lie.",
|
||||
"Never take life seriously. Nobody gets out alive anyway.",
|
||||
"Friendship is like peeing on yourself: everyone can see it, but only you get the warm feeling that it brings.",
|
||||
"Never go to a doctor whose office plants have died.",
|
||||
"Always remember you're unique, just like everyone else.",
|
||||
"What if everything is an illusion and nothing exists? In that case, I definitely overpaid for my carpet.",
|
||||
"Even if you are on the right track, you will get run over if you just sit there.",
|
||||
"Think like a man of action, and act like a man of thought.",
|
||||
"When in doubt, lubricate.",
|
||||
"It is time for you to live up to your family name and face FULL LIFE CONSEQUENCES.",
|
||||
"It's a good day to do what has to be done.",
|
||||
"Move near the countryside and you will be friends of John Freeman.",
|
||||
"If you can't beat 'em, mock 'em.",
|
||||
"Use gun. And if that don't work, use more gun.",
|
||||
"LOOK OUT BEHIND YOU",
|
||||
"This message will self destruct in 10 seconds.",
|
||||
"You'll never know what you can do until you try.",
|
||||
"You are talented in many ways",
|
||||
"Be both a speaker of words and a doer of deeds.",
|
||||
"A visit to a strange place will bring you renewed perspective.",
|
||||
"A passionate new romance will appear in your life when you least expect it.",
|
||||
"If you care enough for a result, you will most certainly attain it.",
|
||||
"To be loved, be loveable.",
|
||||
"Step away from the power position for one day.",
|
||||
"If you want to get a sure crop with a big yield, sow wild oats.",
|
||||
"It doesn't take guts to quit.",
|
||||
"You can expect a change for the better in job or status in the future.",
|
||||
"As the wallet grows, so do the needs.",
|
||||
"You have a reputation for being straightforward and honest.",
|
||||
"Learn a new language and get a new soul.",
|
||||
"A tall dark stranger will soon enter our life.",
|
||||
"Keep staring. I'll do a trick."]
|
||||
|
||||
@hook.command(autohelp=False)
|
||||
def fortune(inp, nick=None, say=None, input=None):
|
||||
".fortune -- get your fortune"
|
||||
|
||||
msg = "(" + nick + ") " + random.choice(fortunes)
|
||||
if re.match("^[A-Za-z0-9_|.-\]\[]*$", inp.lower()) and inp != "":
|
||||
msg = "(@" + inp + ") " + random.choice(fortunes)
|
||||
|
||||
say(msg)
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import re
|
||||
|
||||
from util import hook, http, misc
|
||||
from BeautifulSoup import BeautifulSoup
|
||||
|
||||
@hook.command("calc")
|
||||
@hook.command("math")
|
||||
def calc(inp):
|
||||
'''.calc <term> -- returns Google Calculator result'''
|
||||
|
||||
white_re = re.compile(r'\s+')
|
||||
|
||||
page = http.get('http://www.google.com/search', q=inp)
|
||||
|
||||
soup = BeautifulSoup(page)
|
||||
|
||||
response = soup.find('h2', {'class' : 'r'})
|
||||
|
||||
if response is None:
|
||||
return "Could not calculate " + inp
|
||||
|
||||
output = response.renderContents()
|
||||
|
||||
output = ' '.join(output.splitlines())
|
||||
output = output.replace("\xa0", ",")
|
||||
output = white_re.sub(' ', output.strip())
|
||||
|
||||
output = output.decode('utf-8', 'ignore')
|
||||
output = misc.strip_html(output)
|
||||
|
||||
return output
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
#-*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (C) 2011 by Guilherme Pinto Gonçalves, Ivan Sichmman Freitas
|
||||
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
# THE SOFTWARE.
|
||||
|
||||
from util import hook
|
||||
import sys
|
||||
import subprocess
|
||||
from functools import partial
|
||||
|
||||
fortunes = {
|
||||
'fortunes': 'fortunes',
|
||||
'fortune': 'fortunes',
|
||||
'quotes': 'literature',
|
||||
'quote': 'literature',
|
||||
'riddle': 'riddles',
|
||||
'riddles': 'riddles',
|
||||
'cookie': 'cookie',
|
||||
'cookies': 'cookie',
|
||||
'disclaimer': 'disclaimer',
|
||||
'f': 'fortunes',
|
||||
'q': 'literature',
|
||||
'r': 'riddles'
|
||||
}
|
||||
|
||||
# Use this later to replace the fortunes list workaaround
|
||||
def get_installed_fortunes():
|
||||
try:
|
||||
proc = subprocess.Popen(("/usr/bin/fortune", "-f"),
|
||||
stderr = subprocess.PIPE)
|
||||
except OSError:
|
||||
return set()
|
||||
|
||||
return set(proc.stderr)
|
||||
|
||||
# Use this later to replace the fortunes list workaaround
|
||||
def get_fortune(inp):
|
||||
try:
|
||||
proc = subprocess.Popen(("fortune", "-a", inp),
|
||||
stderr = subprocess.PIPE,
|
||||
stdout = subprocess.PIPE)
|
||||
except OSError:
|
||||
return set()
|
||||
|
||||
return set(proc.stderr)
|
||||
|
||||
@hook.command()
|
||||
def get(inp, say=None):
|
||||
".get <what> -- uses fortune-mod to get something. <what> can be riddle, quote or fortune"
|
||||
fortune = get_fortune(fortune[inp])
|
||||
|
||||
while fortune.length() =< 5:
|
||||
fortune = get_fortune(fortune[inp])
|
||||
|
||||
if proc.wait() == 0:
|
||||
|
||||
for line in proc.stdout:
|
||||
say(line.lstrip())
|
||||
else:
|
||||
return "Fortune failed: " + proc.stderr.read()
|
|
@ -0,0 +1,82 @@
|
|||
import random
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
def api_get(kind, query):
|
||||
url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \
|
||||
'v=1.0&safe=off'
|
||||
return http.get_json(url % kind, q=query)
|
||||
|
||||
|
||||
@hook.command
|
||||
def gis(inp):
|
||||
'''.gis <term> -- returns first google image result (safesearch off)'''
|
||||
|
||||
parsed = api_get('images', inp)
|
||||
if not 200 <= parsed['responseStatus'] < 300:
|
||||
raise IOError('error searching for images: %d: %s' % (
|
||||
parsed['responseStatus'], ''))
|
||||
if not parsed['responseData']['results']:
|
||||
return 'no images found'
|
||||
return random.choice(parsed['responseData']['results'][:10]) \
|
||||
['unescapedUrl'] # squares is dumb
|
||||
|
||||
|
||||
@hook.command('g')
|
||||
@hook.command
|
||||
def google(inp):
|
||||
'''.g/.google <query> -- returns first google search result'''
|
||||
|
||||
parsed = api_get('web', inp)
|
||||
if not 200 <= parsed['responseStatus'] < 300:
|
||||
raise IOError('error searching for pages: %d: %s' % (
|
||||
parsed['responseStatus'], ''))
|
||||
if not parsed['responseData']['results']:
|
||||
return 'no results found'
|
||||
|
||||
result = parsed['responseData']['results'][0]
|
||||
|
||||
title = http.unescape(result['titleNoFormatting'])
|
||||
content = http.unescape(result['content'])
|
||||
|
||||
if len(content) == 0:
|
||||
content = "No description available"
|
||||
else:
|
||||
content = http.html.fromstring(content).text_content()
|
||||
|
||||
out = '%s -- \x02%s\x02: "%s"' % (result['unescapedUrl'], title, content)
|
||||
|
||||
out = ' '.join(out.split())
|
||||
|
||||
if len(out) > 300:
|
||||
out = out[:out.rfind(' ')] + '..."'
|
||||
|
||||
return out
|
||||
|
||||
def googleno(inp):
|
||||
|
||||
parsed = api_get('web', inp)
|
||||
if not 200 <= parsed['responseStatus'] < 300:
|
||||
raise IOError('error searching for pages: %d: %s' % (
|
||||
parsed['responseStatus'], ''))
|
||||
if not parsed['responseData']['results']:
|
||||
return 'no results found'
|
||||
|
||||
result = parsed['responseData']['results'][0]
|
||||
|
||||
title = http.unescape(result['titleNoFormatting'])
|
||||
content = http.unescape(result['content'])
|
||||
|
||||
if len(content) == 0:
|
||||
content = "No description available"
|
||||
else:
|
||||
content = http.html.fromstring(content).text_content()
|
||||
|
||||
out = '%s\x02: "%s"' % (title, content)
|
||||
out = ' '.join(out.split())
|
||||
|
||||
if len(out) > 300:
|
||||
out = out[:out.rfind(' ')] + '..."'
|
||||
|
||||
return out
|
|
@ -0,0 +1,34 @@
|
|||
import re
|
||||
|
||||
from util import hook, http
|
||||
from BeautifulSoup import BeautifulSoup
|
||||
|
||||
|
||||
@hook.command("time")
|
||||
def clock(inp, say=None):
|
||||
'''.time <area> -- gets the time in <area>'''
|
||||
|
||||
white_re = re.compile(r'\s+')
|
||||
tags_re = re.compile(r'<[^<]*?>')
|
||||
|
||||
page = http.get('http://www.google.com/search', q="time in " + inp)
|
||||
|
||||
soup = BeautifulSoup(page)
|
||||
|
||||
response = soup.find('td', {'style' : 'font-size:medium'})
|
||||
|
||||
if response is None:
|
||||
return "Could not get the time for " + inp + "!"
|
||||
|
||||
output = response.renderContents()
|
||||
|
||||
output = ' '.join(output.splitlines())
|
||||
output = output.replace("\xa0", ",")
|
||||
|
||||
output = white_re.sub(' ', output.strip())
|
||||
output = tags_re.sub('\x02', output.strip())
|
||||
|
||||
output = output.decode('utf-8', 'ignore')
|
||||
|
||||
return output
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import hashlib
|
||||
from util import hook
|
||||
|
||||
@hook.command
|
||||
def md5(inp):
|
||||
".hash <text> -- returns a md5 hash of <text>"
|
||||
return hashlib.md5(inp).hexdigest()
|
||||
|
||||
@hook.command
|
||||
def sha1(inp):
|
||||
".hash <text> -- returns a sha1 hash of <text>"
|
||||
return hashlib.sha1(inp).hexdigest()
|
||||
|
||||
@hook.command
|
||||
def sha256(inp):
|
||||
".hash <text> -- returns a sha256 hash of <text>"
|
||||
return hashlib.sha256(inp).hexdigest()
|
||||
|
||||
@hook.command
|
||||
def sha512(inp):
|
||||
".hash <text> -- returns a sha512 hash of <text>"
|
||||
return hashlib.sha512(inp).hexdigest()
|
||||
|
||||
@hook.command
|
||||
def hash(inp):
|
||||
".hash <text> -- returns hashes of <text>"
|
||||
return ', '.join(x + ": " + getattr(hashlib, x)(inp).hexdigest()
|
||||
for x in 'md5 sha1 sha256'.split())
|
|
@ -0,0 +1,51 @@
|
|||
import re
|
||||
|
||||
from util import hook
|
||||
|
||||
# Standard automatic help command
|
||||
@hook.command(autohelp=False)
|
||||
def help(inp, input=None, bot=None, say=None, notice=None):
|
||||
".help -- gives a list of commands/help for a command"
|
||||
|
||||
funcs = {}
|
||||
disabled = bot.config.get('disabled_plugins', [])
|
||||
disabled_comm = bot.config.get('disabled_commands', [])
|
||||
for command, (func, args) in bot.commands.iteritems():
|
||||
fn = re.match(r'^plugins.(.+).py$', func._filename)
|
||||
if fn.group(1).lower() not in disabled:
|
||||
if command not in disabled_comm:
|
||||
if func.__doc__ is not None:
|
||||
if func in funcs:
|
||||
if len(funcs[func]) < len(command):
|
||||
funcs[func] = command
|
||||
else:
|
||||
funcs[func] = command
|
||||
|
||||
hidden = ["part", "stfu", "kthx", "chnick", "join", "8ballnooxt"]
|
||||
|
||||
commands = dict((value, key) for key, value in funcs.iteritems() if key not in hidden)
|
||||
|
||||
if not inp:
|
||||
length = 0
|
||||
out = ["",""]
|
||||
well = []
|
||||
for x in commands:
|
||||
if x not in hidden:
|
||||
well.append(x)
|
||||
well.sort()
|
||||
for x in well:
|
||||
if len(out[0]) + len(str(x)) > 440:
|
||||
out[1] += " " + str(x)
|
||||
else:
|
||||
out[0] += " " + str(x)
|
||||
|
||||
notice(out[0][1:])
|
||||
if out[1]:
|
||||
notice(out[1][1:])
|
||||
|
||||
|
||||
|
||||
else:
|
||||
if inp in commands:
|
||||
input.say(commands[inp].__doc__)
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
# IMDb lookup plugin by Ghetto Wizard (2011).
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
@hook.command
|
||||
def imdb(inp):
|
||||
'''.imdb <movie> -- gets information about <movie> from IMDb'''
|
||||
|
||||
content = http.get_json("http://www.imdbapi.com/", t=inp)
|
||||
|
||||
if content['Response'] == 'Movie Not Found':
|
||||
return 'movie not found'
|
||||
elif content['Response'] == 'True':
|
||||
content['URL'] = 'http://www.imdb.com/title/%(ID)s' % content
|
||||
|
||||
out = '\x02%(Title)s\x02 (%(Year)s) (%(Genre)s): %(Plot)s'
|
||||
if content['Runtime'] != 'N/A':
|
||||
out += ' \x02%(Runtime)s\x02.'
|
||||
if content['Rating'] != 'N/A' and content['Votes'] != 'N/A':
|
||||
out += ' \x02%(Rating)s/10\x02 with \x02%(Votes)s\x02 votes.'
|
||||
out += ' %(URL)s'
|
||||
return out % content
|
||||
else:
|
||||
return 'unknown error'
|
|
@ -0,0 +1,50 @@
|
|||
from util import hook
|
||||
import re
|
||||
import random
|
||||
|
||||
insults = ["You are the son of a motherless ogre.",
|
||||
"Your mother was a hamster and your father smelled of elderberries.",
|
||||
"I once owned a dog that was smarter than you. ",
|
||||
"Go climb a wall of dicks.",
|
||||
"You fight like a dairy farmer.",
|
||||
"I've spoken to apes more polite than you.",
|
||||
"Go and boil your bottom! Son of a silly person! ",
|
||||
"I fart in your general direction.",
|
||||
"Go away or I shall taunt you a second time. ",
|
||||
"Shouldn't you have a license for being that ugly?",
|
||||
"Calling you an idiot would be an insult to all the stupid people.",
|
||||
"Why don't you slip into something more comfortable...like a coma.",
|
||||
"Well, they do say opposites attact...so I sincerely hope you meet somebody who is attractive, honest, intelligent, and cultured..",
|
||||
"Are you always this stupid or are you just making a special effort today?",
|
||||
"Yo momma so fat when she sits around the house she sits AROUND the house.",
|
||||
"Yo momma so ugly she made an onion cry.",
|
||||
"Is your name Maple Syrup? It should be, you sap.",
|
||||
"Bite my shiny metal ass!",
|
||||
"Up yours, meatbag.",
|
||||
"Jam a bastard in it you crap!",
|
||||
"Don't piss me off today, I'm running out of places to hide to bodies",
|
||||
"Why don't you go outside and play hide and go fuck yourself",
|
||||
"I'll use small words you're sure to understand, you warthog-faced buffoon.",
|
||||
"You are a sad, strange little man, and you have my pity.",
|
||||
"Sit your five dollar ass down before I make change.",
|
||||
"What you've just said is one of the most insanely idiotic things I've ever heard. Everyone in this room is now dumber for having listened to it. May God have mercy on your soul.",
|
||||
"Look up Idiot in the dictionary. Know what you'll find? The definition of the word IDIOT, which you are.",
|
||||
"You're dumber than a bag of hammers.",
|
||||
"Why don't you go back to your home on Whore Island?",
|
||||
"If I had a dick this is when I'd tell you to suck it.",
|
||||
"Go play in traffic.",
|
||||
"The village called, they want their idiot back."]
|
||||
|
||||
@hook.command(autohelp=False)
|
||||
def insult(inp, nick=None, say=None, input=None):
|
||||
".insult [user] -- insult someone!"
|
||||
|
||||
msg = "(" + nick + ") " + random.choice(insults)
|
||||
if re.match("^[A-Za-z0-9_|.-\]\[]*$", inp.lower()) and inp != "":
|
||||
msg = "(@" + inp + ") " + random.choice(insults)
|
||||
|
||||
if inp == input.conn.nick.lower() or inp == "itself":
|
||||
msg = "*stares at " + nick + "*"
|
||||
|
||||
say(msg)
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
from util import hook, http
|
||||
|
||||
|
||||
api_key = ""
|
||||
|
||||
api_url = "http://ws.audioscrobbler.com/2.0/?format=json"
|
||||
|
||||
|
||||
@hook.command
|
||||
def lastfm(inp, nick='', say=None):
|
||||
if inp:
|
||||
user = inp
|
||||
else:
|
||||
user = nick
|
||||
|
||||
response = http.get_json(api_url, method="user.getrecenttracks",
|
||||
api_key=api_key, user=user, limit=1)
|
||||
|
||||
if 'error' in response:
|
||||
if inp: # specified a user name
|
||||
return "error: %s" % response["message"]
|
||||
else:
|
||||
return "your nick is not a LastFM account. try '.lastfm username'."
|
||||
|
||||
tracks = response["recenttracks"]["track"]
|
||||
|
||||
if len(tracks) == 0:
|
||||
return "no recent tracks for user %r found" % user
|
||||
|
||||
if type(tracks) == list:
|
||||
# if the user is listening to something, the tracks entry is a list
|
||||
# the first item is the current track
|
||||
track = tracks[0]
|
||||
status = 'current track'
|
||||
elif type(tracks) == dict:
|
||||
# otherwise, they aren't listening to anything right now, and
|
||||
# the tracks entry is a dict representing the most recent track
|
||||
track = tracks
|
||||
status = 'last track'
|
||||
else:
|
||||
return "error parsing track listing"
|
||||
|
||||
title = track["name"]
|
||||
album = track["album"]["#text"]
|
||||
artist = track["artist"]["#text"]
|
||||
|
||||
ret = "\x02%s\x0F's %s - \x02%s\x0f" % (user, status, title)
|
||||
if artist:
|
||||
ret += " by \x02%s\x0f" % artist
|
||||
if album:
|
||||
ret += " on \x02%s\x0f" % album
|
||||
|
||||
say(ret)
|
|
@ -0,0 +1,36 @@
|
|||
from util import hook
|
||||
|
||||
def find_location(ip):
|
||||
import string
|
||||
import urllib
|
||||
api = "6ddac03a5a67a534045f59908e5c17fd68169609b453e3c6398823fff86a87c0"
|
||||
response = urllib.urlopen("http://api.ipinfodb.com/v3/ip-city/?key="+api+"&ip="+ip).read()
|
||||
response = response.split(";")
|
||||
give = {}
|
||||
give["country"] = response[4].title()
|
||||
give["country_short"] = response[3].upper()
|
||||
give["state"] = response[5].title()
|
||||
give["city"] = response[6].title()
|
||||
give["timezone"] = response[10].title()
|
||||
return give
|
||||
|
||||
def timezone(ip):
|
||||
time = find_location(ip)["timezone"]
|
||||
time = time.replace(":",".")
|
||||
time = time.replace(".00","")
|
||||
return int(time)
|
||||
|
||||
@hook.command
|
||||
def location(inp, say = None, me = None):
|
||||
".location <ip> - Performs a GeoIP check on the ip given."
|
||||
give = find_location(inp)
|
||||
if give["country"] not in [""," ","-"," - "]:
|
||||
if give["state"] == give["city"]:
|
||||
localstring = give["city"]
|
||||
else:
|
||||
localstring = give["city"] + ", " + give["state"]
|
||||
say("That IP comes from " + give["country"] + " (" + give["country_short"] + ")")
|
||||
say("I think it's in " + localstring + " with a timezone of " + give["timezone"] + "GMT")
|
||||
else:
|
||||
say("Either that wasn't an IP or I cannot locate it in my database. :(")
|
||||
return
|
|
@ -0,0 +1,106 @@
|
|||
"""
|
||||
log.py: written by Scaevolus 2009
|
||||
"""
|
||||
|
||||
import os
|
||||
import codecs
|
||||
import time
|
||||
import re
|
||||
|
||||
from util import hook
|
||||
|
||||
|
||||
log_fds = {} # '%(net)s %(chan)s' : (filename, fd)
|
||||
|
||||
timestamp_format = '%H:%M:%S'
|
||||
|
||||
formats = {'PRIVMSG': '<%(nick)s> %(msg)s',
|
||||
'PART': '-!- %(nick)s [%(user)s@%(host)s] has left %(chan)s',
|
||||
'JOIN': '-!- %(nick)s [%(user)s@%(host)s] has joined %(param0)s',
|
||||
'MODE': '-!- mode/%(chan)s [%(param_tail)s] by %(nick)s',
|
||||
'KICK': '-!- %(param1)s was kicked from %(chan)s by %(nick)s [%(msg)s]',
|
||||
'TOPIC': '-!- %(nick)s changed the topic of %(chan)s to: %(msg)s',
|
||||
'QUIT': '-!- %(nick)s has quit [%(msg)s]',
|
||||
'PING': '',
|
||||
'NOTICE': ''
|
||||
}
|
||||
|
||||
ctcp_formats = {'ACTION': '* %(nick)s %(ctcpmsg)s'}
|
||||
|
||||
irc_color_re = re.compile(r'(\x03(\d+,\d+|\d)|[\x0f\x02\x16\x1f])')
|
||||
|
||||
|
||||
def get_log_filename(dir, server, chan):
|
||||
return os.path.join(dir, 'log', gmtime('%Y'), server,
|
||||
(gmtime('%%s.%m-%d.log') % chan).lower())
|
||||
|
||||
|
||||
def gmtime(format):
|
||||
return time.strftime(format, time.gmtime())
|
||||
|
||||
|
||||
def beautify(input):
|
||||
format = formats.get(input.command, '%(raw)s')
|
||||
args = dict(input)
|
||||
|
||||
leng = len(args['paraml'])
|
||||
for n, p in enumerate(args['paraml']):
|
||||
args['param' + str(n)] = p
|
||||
args['param_' + str(abs(n - leng))] = p
|
||||
|
||||
args['param_tail'] = ' '.join(args['paraml'][1:])
|
||||
args['msg'] = irc_color_re.sub('', args['msg'])
|
||||
|
||||
if input.command == 'PRIVMSG' and input.msg.count('\x01') >= 2:
|
||||
ctcp = input.msg.split('\x01', 2)[1].split(' ', 1)
|
||||
if len(ctcp) == 1:
|
||||
ctcp += ['']
|
||||
args['ctcpcmd'], args['ctcpmsg'] = ctcp
|
||||
format = ctcp_formats.get(args['ctcpcmd'],
|
||||
'%(nick)s [%(user)s@%(host)s] requested unknown CTCP '
|
||||
'%(ctcpcmd)s from %(chan)s: %(ctcpmsg)s')
|
||||
|
||||
return format % args
|
||||
|
||||
|
||||
def get_log_fd(dir, server, chan):
|
||||
fn = get_log_filename(dir, server, chan)
|
||||
cache_key = '%s %s' % (server, chan)
|
||||
filename, fd = log_fds.get(cache_key, ('', 0))
|
||||
|
||||
if fn != filename: # we need to open a file for writing
|
||||
if fd != 0: # is a valid fd
|
||||
fd.flush()
|
||||
fd.close()
|
||||
dir = os.path.split(fn)[0]
|
||||
if not os.path.exists(dir):
|
||||
os.makedirs(dir)
|
||||
fd = codecs.open(fn, 'a', 'utf-8')
|
||||
log_fds[cache_key] = (fn, fd)
|
||||
|
||||
return fd
|
||||
|
||||
|
||||
@hook.singlethread
|
||||
@hook.event('*')
|
||||
def log(paraml, input=None, bot=None):
|
||||
timestamp = gmtime(timestamp_format)
|
||||
|
||||
fd = get_log_fd(bot.persist_dir, input.server, 'raw')
|
||||
fd.write(timestamp + ' ' + input.raw + '\n')
|
||||
|
||||
if input.command == 'QUIT': # these are temporary fixes until proper
|
||||
input.chan = 'quit' # presence tracking is implemented
|
||||
if input.command == 'NICK':
|
||||
input.chan = 'nick'
|
||||
|
||||
beau = beautify(input)
|
||||
|
||||
if beau == '': # don't log this
|
||||
return
|
||||
|
||||
if input.chan:
|
||||
fd = get_log_fd(bot.persist_dir, input.server, input.chan)
|
||||
fd.write(timestamp + ' ' + beau + '\n')
|
||||
|
||||
print timestamp, input.chan, beau.encode('utf8', 'ignore')
|
|
@ -0,0 +1,36 @@
|
|||
from util import hook
|
||||
import urllib
|
||||
|
||||
@hook.command(autohelp=False, input=None, notice=None)
|
||||
def mccheck(inp):
|
||||
".mccheck - Attempts to log in to minecraft"
|
||||
password = input.bot.config["api_keys"]["mc"][0]
|
||||
password = input.bot.config["api_keys"]["mc"][1]
|
||||
notice(username + " " + password)
|
||||
login = urllib.urlopen("https://login.minecraft.net/?user="+username+"&password="+password+"&&version=13").read()
|
||||
if username in login:
|
||||
return "Attempting to connect to Minecraft login servers... Login servers appear to be online!"
|
||||
else:
|
||||
return "Attempting to connect to Minecraft login servers... Login servers appear to be offline :("
|
||||
|
||||
@hook.command
|
||||
def haspaid(inp):
|
||||
".haspaid <username> - Checks if a user has a premium Minecraft account"
|
||||
login = urllib.urlopen("http://www.minecraft.net/haspaid.jsp?user=" + inp).read()
|
||||
if "true" in login:
|
||||
return "The user " + inp + " has a premium Minecraft account."
|
||||
else:
|
||||
return "The user " + inp + " either has not paid or is an unused nickname."
|
||||
|
||||
@hook.command
|
||||
def mclogin(inp, say=None):
|
||||
".mclogin <username> <password> - Attempts to log in to minecraft using the provided username and password, this is NOT logged."
|
||||
inp = inp.split(" ")
|
||||
username = inp[0]
|
||||
password = inp[1]
|
||||
say("Attempting to log in using " + username)
|
||||
login = urllib.urlopen("https://login.minecraft.net/?user=" + username + "&password=" + password + "&&version=13").read()
|
||||
if username in login:
|
||||
return "I logged in with " + username
|
||||
else:
|
||||
return "I couldn't log in using " + username + ", either the password changed or minecraft auth is down :O"
|
|
@ -0,0 +1,37 @@
|
|||
|
||||
import socket
|
||||
import struct
|
||||
|
||||
|
||||
from util import hook
|
||||
|
||||
def get_info(host, port):
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.connect((host, port))
|
||||
sock.send('\xfe')
|
||||
response = sock.recv(1)
|
||||
if response != '\xff':
|
||||
return "Server gave invalid response: "+repr(response)
|
||||
length = struct.unpack('!h', sock.recv(2))[0]
|
||||
values = sock.recv(length*2).decode('utf-16be').split(u'\xa7')
|
||||
sock.close()
|
||||
return "%s - %d/%d players" % (values[0], int(values[1]), int(values[2]))
|
||||
except:
|
||||
return "Error pinging "+host+":"+str(port)+", is it up? double-check your address!"
|
||||
|
||||
@hook.command
|
||||
def mcping(inp):
|
||||
".mcping server[:port] - ping a minecraft server and show response."
|
||||
inp = inp.strip().split(" ")[0]
|
||||
|
||||
if ":" in inp:
|
||||
host, port = inp.split(":", 1)
|
||||
try:
|
||||
port = int(port)
|
||||
except:
|
||||
return "Invalid port!"
|
||||
else:
|
||||
host = inp
|
||||
port = 25565
|
||||
return get_info(host, port)
|
|
@ -0,0 +1,28 @@
|
|||
import os
|
||||
import re
|
||||
|
||||
from util import hook
|
||||
|
||||
|
||||
@hook.command(autohelp=False)
|
||||
def mem(inp):
|
||||
".mem -- returns bot's current memory usage -- linux/windows only"
|
||||
|
||||
if os.name == 'posix':
|
||||
status_file = open("/proc/%d/status" % os.getpid()).read()
|
||||
line_pairs = re.findall(r"^(\w+):\s*(.*)\s*$", status_file, re.M)
|
||||
status = dict(line_pairs)
|
||||
keys = 'VmSize VmLib VmData VmExe VmRSS VmStk'.split()
|
||||
return ', '.join(key + ':' + status[key] for key in keys)
|
||||
|
||||
elif os.name == 'nt':
|
||||
cmd = "tasklist /FI \"PID eq %s\" /FO CSV /NH" % os.getpid()
|
||||
out = os.popen(cmd).read()
|
||||
|
||||
total = 0
|
||||
for amount in re.findall(r'([,0-9]+) K', out):
|
||||
total += int(amount.replace(',', ''))
|
||||
|
||||
return 'memory usage: %d kB' % total
|
||||
|
||||
return mem.__doc__
|
|
@ -0,0 +1,135 @@
|
|||
# metacritic.com scraper
|
||||
|
||||
import re
|
||||
from urllib2 import HTTPError
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
@hook.command('mc')
|
||||
def metacritic(inp):
|
||||
'.mc [all|movie|tv|album|x360|ps3|pc|ds|wii] <title> -- gets rating for'\
|
||||
' <title> from metacritic on the specified medium'
|
||||
|
||||
# if the results suck, it's metacritic's fault
|
||||
|
||||
args = inp.strip()
|
||||
|
||||
game_platforms = ('x360', 'ps3', 'pc', 'ds', 'wii', '3ds', 'gba')
|
||||
all_platforms = game_platforms + ('all', 'movie', 'tv', 'album')
|
||||
|
||||
try:
|
||||
plat, title = args.split(' ', 1)
|
||||
if plat not in all_platforms:
|
||||
# raise the ValueError so that the except block catches it
|
||||
# in this case, or in the case of the .split above raising the
|
||||
# ValueError, we want the same thing to happen
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
plat = 'all'
|
||||
title = args
|
||||
|
||||
cat = 'game' if plat in game_platforms else plat
|
||||
|
||||
title_safe = http.quote_plus(title)
|
||||
|
||||
url = 'http://www.metacritic.com/search/%s/%s/results' % (cat, title_safe)
|
||||
|
||||
try:
|
||||
doc = http.get_html(url)
|
||||
except HTTPError:
|
||||
return 'error fetching results'
|
||||
|
||||
''' result format:
|
||||
-- game result, with score
|
||||
-- subsequent results are the same structure, without first_result class
|
||||
<li class="result first_result">
|
||||
<div class="result_type">
|
||||
<strong>Game</strong>
|
||||
<span class="platform">WII</span>
|
||||
</div>
|
||||
<div class="result_wrap">
|
||||
<div class="basic_stats has_score">
|
||||
<div class="main_stats">
|
||||
<h3 class="product_title basic_stat">...</h3>
|
||||
<div class="std_score">
|
||||
<div class="score_wrap">
|
||||
<span class="label">Metascore: </span>
|
||||
<span class="data metascore score_favorable">87</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="more_stats extended_stats">...</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
-- other platforms are the same basic layout
|
||||
-- if it doesn't have a score, there is no div.basic_score
|
||||
-- the <div class="result_type"> changes content for non-games:
|
||||
<div class="result_type"><strong>Movie</strong></div>
|
||||
'''
|
||||
|
||||
# get the proper result element we want to pull data from
|
||||
|
||||
result = None
|
||||
|
||||
if not doc.find_class('query_results'):
|
||||
return 'no results found'
|
||||
|
||||
# if they specified an invalid search term, the input box will be empty
|
||||
if doc.get_element_by_id('search_term').value == '':
|
||||
return 'invalid search term'
|
||||
|
||||
if plat not in game_platforms:
|
||||
# for [all] results, or non-game platforms, get the first result
|
||||
result = doc.find_class('result first_result')[0]
|
||||
|
||||
# find the platform, if it exists
|
||||
result_type = result.find_class('result_type')
|
||||
if result_type:
|
||||
|
||||
# if the result_type div has a platform div, get that one
|
||||
platform_div = result_type[0].find_class('platform')
|
||||
if platform_div:
|
||||
plat = platform_div[0].text_content().strip()
|
||||
else:
|
||||
# otherwise, use the result_type text_content
|
||||
plat = result_type[0].text_content().strip()
|
||||
|
||||
else:
|
||||
# for games, we want to pull the first result with the correct
|
||||
# platform
|
||||
results = doc.find_class('result')
|
||||
for res in results:
|
||||
result_plat = res.find_class('platform')[0].text_content().strip()
|
||||
if result_plat == plat.upper():
|
||||
result = res
|
||||
break
|
||||
|
||||
if not result:
|
||||
return 'no results found'
|
||||
|
||||
# get the name, release date, and score from the result
|
||||
product_title = result.find_class('product_title')[0]
|
||||
name = product_title.text_content()
|
||||
link = 'http://metacritic.com' + product_title.find('a').attrib['href']
|
||||
|
||||
try:
|
||||
release = result.find_class('release_date')[0].\
|
||||
find_class('data')[0].text_content()
|
||||
|
||||
# strip extra spaces out of the release date
|
||||
release = re.sub(r'\s{2,}', ' ', release)
|
||||
except IndexError:
|
||||
release = None
|
||||
|
||||
try:
|
||||
score = result.find_class('metascore')[0].text_content()
|
||||
except IndexError:
|
||||
score = None
|
||||
|
||||
return '[%s] %s - %s, %s -- %s' % (plat.upper(), name,
|
||||
score or 'no score',
|
||||
'release: %s' % release if release else 'unreleased',
|
||||
link)
|
|
@ -0,0 +1,56 @@
|
|||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from util import hook, http
|
||||
|
||||
socket.setdefaulttimeout(10) # global setting
|
||||
|
||||
|
||||
#autorejoin channels
|
||||
#@hook.event('KICK')
|
||||
#def rejoin(paraml, conn=None):
|
||||
# if paraml[1] == conn.nick:
|
||||
# if paraml[0].lower() in conn.channels:
|
||||
# conn.join(paraml[0])
|
||||
|
||||
|
||||
#join channels when invited
|
||||
@hook.event('INVITE')
|
||||
def invite(paraml, conn=None):
|
||||
conn.join(paraml[-1])
|
||||
|
||||
|
||||
@hook.event('004')
|
||||
def onjoin(paraml, conn=None, bot=None):
|
||||
# identify to services
|
||||
nickserv_password = conn.conf.get('nickserv_password', '')
|
||||
nickserv_name = conn.conf.get('nickserv_name', 'nickserv')
|
||||
nickserv_command = conn.conf.get('nickserv_command', 'IDENTIFY %s')
|
||||
if nickserv_password:
|
||||
if nickserv_password in bot.config['censored_strings']:
|
||||
bot.config['censored_strings'].remove(nickserv_password)
|
||||
conn.msg(nickserv_name, nickserv_command % nickserv_password)
|
||||
bot.config['censored_strings'].append(nickserv_password)
|
||||
time.sleep(1)
|
||||
|
||||
# set mode on self
|
||||
mode = conn.conf.get('mode')
|
||||
if mode:
|
||||
conn.cmd('MODE', [conn.nick, mode])
|
||||
|
||||
# join channels
|
||||
for channel in conn.channels:
|
||||
conn.join(channel)
|
||||
time.sleep(1) # don't flood JOINs
|
||||
|
||||
# set user-agent
|
||||
|
||||
http.ua_skybot = 'CloudBot'
|
||||
|
||||
|
||||
@hook.regex(r'^\x01VERSION\x01$')
|
||||
def version(inp, notice=None):
|
||||
notice('\x01VERSION CloudBot')
|
||||
http.ua_skybot = 'CloudBot'
|
|
@ -0,0 +1,183 @@
|
|||
import re
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
@hook.command
|
||||
def mtg(inp):
|
||||
".mtg <name> -- gets information about Magic the Gathering card <name>"
|
||||
|
||||
url = 'http://magiccards.info/query?v=card&s=cname'
|
||||
h = http.get_html(url, q=inp)
|
||||
|
||||
name = h.find('body/table/tr/td/span/a')
|
||||
if name is None:
|
||||
return "no cards found"
|
||||
card = name.getparent().getparent().getparent()
|
||||
|
||||
type = card.find('td/p').text.replace('\n', '')
|
||||
|
||||
# this is ugly
|
||||
text = http.html.tostring(card.xpath("//p[@class='ctext']/b")[0])
|
||||
text = text.replace('<br>', '$')
|
||||
text = http.html.fromstring(text).text_content()
|
||||
text = re.sub(r'(\w+\s*)\$+(\s*\w+)', r'\1. \2', text)
|
||||
text = text.replace('$', ' ')
|
||||
text = re.sub(r'\(.*?\)', '', text) # strip parenthetical explanations
|
||||
text = re.sub(r'\.(\S)', r'. \1', text) # fix spacing
|
||||
|
||||
printings = card.find('td/small').text_content()
|
||||
printings = re.search(r'Editions:(.*)Languages:', printings).group(1)
|
||||
printings = re.findall(r'\s*(.+?(?: \([^)]+\))*) \((.*?)\)',
|
||||
' '.join(printings.split()))
|
||||
|
||||
printing_out = ', '.join('%s (%s)' % (set_abbrevs.get(x[0], x[0]),
|
||||
rarity_abbrevs.get(x[1], x[1]))
|
||||
for x in printings)
|
||||
|
||||
name.make_links_absolute(base_url=url)
|
||||
link = name.attrib['href']
|
||||
name = name.text_content().strip()
|
||||
type = type.strip()
|
||||
text = ' '.join(text.split())
|
||||
|
||||
return ' | '.join((name, type, text, printing_out, link))
|
||||
|
||||
|
||||
set_abbrevs = {
|
||||
'15th Anniversary': '15ANN',
|
||||
'APAC Junior Series': 'AJS',
|
||||
'Alara Reborn': 'ARB',
|
||||
'Alliances': 'AI',
|
||||
'Anthologies': 'AT',
|
||||
'Antiquities': 'AQ',
|
||||
'Apocalypse': 'AP',
|
||||
'Arabian Nights': 'AN',
|
||||
'Arena League': 'ARENA',
|
||||
'Asia Pacific Land Program': 'APAC',
|
||||
'Battle Royale': 'BR',
|
||||
'Battle Royale Box Set': 'BRB',
|
||||
'Beatdown': 'BTD',
|
||||
'Beatdown Box Set': 'BTD',
|
||||
'Betrayers of Kamigawa': 'BOK',
|
||||
'Celebration Cards': 'UQC',
|
||||
'Champions of Kamigawa': 'CHK',
|
||||
'Champs': 'CP',
|
||||
'Chronicles': 'CH',
|
||||
'Classic Sixth Edition': '6E',
|
||||
'Coldsnap': 'CS',
|
||||
'Coldsnap Theme Decks': 'CSTD',
|
||||
'Conflux': 'CFX',
|
||||
'Core Set - Eighth Edition': '8E',
|
||||
'Core Set - Ninth Edition': '9E',
|
||||
'Darksteel': 'DS',
|
||||
'Deckmasters': 'DM',
|
||||
'Dissension': 'DI',
|
||||
'Dragon Con': 'DRC',
|
||||
'Duel Decks: Divine vs. Demonic': 'DVD',
|
||||
'Duel Decks: Elves vs. Goblins': 'EVG',
|
||||
'Duel Decks: Garruk vs. Liliana': 'GVL',
|
||||
'Duel Decks: Jace vs. Chandra': 'JVC',
|
||||
'Eighth Edition': '8ED',
|
||||
'Eighth Edition Box Set': '8EB',
|
||||
'European Land Program': 'EURO',
|
||||
'Eventide': 'EVE',
|
||||
'Exodus': 'EX',
|
||||
'Fallen Empires': 'FE',
|
||||
'Fifth Dawn': '5DN',
|
||||
'Fifth Edition': '5E',
|
||||
'Fourth Edition': '4E',
|
||||
'Friday Night Magic': 'FNMP',
|
||||
'From the Vault: Dragons': 'FVD',
|
||||
'From the Vault: Exiled': 'FVE',
|
||||
'Future Sight': 'FUT',
|
||||
'Gateway': 'GRC',
|
||||
'Grand Prix': 'GPX',
|
||||
'Guildpact': 'GP',
|
||||
'Guru': 'GURU',
|
||||
'Happy Holidays': 'HHO',
|
||||
'Homelands': 'HL',
|
||||
'Ice Age': 'IA',
|
||||
'Introductory Two-Player Set': 'ITP',
|
||||
'Invasion': 'IN',
|
||||
'Judge Gift Program': 'JR',
|
||||
'Judgment': 'JU',
|
||||
'Junior Series': 'JSR',
|
||||
'Legend Membership': 'DCILM',
|
||||
'Legends': 'LG',
|
||||
'Legions': 'LE',
|
||||
'Limited Edition (Alpha)': 'LEA',
|
||||
'Limited Edition (Beta)': 'LEB',
|
||||
'Limited Edition Alpha': 'LEA',
|
||||
'Limited Edition Beta': 'LEB',
|
||||
'Lorwyn': 'LW',
|
||||
'MTGO Masters Edition': 'MED',
|
||||
'MTGO Masters Edition II': 'ME2',
|
||||
'MTGO Masters Edition III': 'ME3',
|
||||
'Magic 2010': 'M10',
|
||||
'Magic Game Day Cards': 'MGDC',
|
||||
'Magic Player Rewards': 'MPRP',
|
||||
'Magic Scholarship Series': 'MSS',
|
||||
'Magic: The Gathering Launch Parties': 'MLP',
|
||||
'Media Inserts': 'MBP',
|
||||
'Mercadian Masques': 'MM',
|
||||
'Mirage': 'MR',
|
||||
'Mirrodin': 'MI',
|
||||
'Morningtide': 'MT',
|
||||
'Multiverse Gift Box Cards': 'MGBC',
|
||||
'Nemesis': 'NE',
|
||||
'Ninth Edition Box Set': '9EB',
|
||||
'Odyssey': 'OD',
|
||||
'Onslaught': 'ON',
|
||||
'Planar Chaos': 'PC',
|
||||
'Planechase': 'PCH',
|
||||
'Planeshift': 'PS',
|
||||
'Portal': 'PO',
|
||||
'Portal Demogame': 'POT',
|
||||
'Portal Second Age': 'PO2',
|
||||
'Portal Three Kingdoms': 'P3K',
|
||||
'Premium Deck Series: Slivers': 'PDS',
|
||||
'Prerelease Events': 'PTC',
|
||||
'Pro Tour': 'PRO',
|
||||
'Prophecy': 'PR',
|
||||
'Ravnica: City of Guilds': 'RAV',
|
||||
'Release Events': 'REP',
|
||||
'Revised Edition': 'RV',
|
||||
'Saviors of Kamigawa': 'SOK',
|
||||
'Scourge': 'SC',
|
||||
'Seventh Edition': '7E',
|
||||
'Shadowmoor': 'SHM',
|
||||
'Shards of Alara': 'ALA',
|
||||
'Starter': 'ST',
|
||||
'Starter 1999': 'S99',
|
||||
'Starter 2000 Box Set': 'ST2K',
|
||||
'Stronghold': 'SH',
|
||||
'Summer of Magic': 'SOM',
|
||||
'Super Series': 'SUS',
|
||||
'Tempest': 'TP',
|
||||
'Tenth Edition': '10E',
|
||||
'The Dark': 'DK',
|
||||
'Time Spiral': 'TS',
|
||||
'Time Spiral Timeshifted': 'TSTS',
|
||||
'Torment': 'TR',
|
||||
'Two-Headed Giant Tournament': 'THGT',
|
||||
'Unglued': 'UG',
|
||||
'Unhinged': 'UH',
|
||||
'Unhinged Alternate Foils': 'UHAA',
|
||||
'Unlimited Edition': 'UN',
|
||||
"Urza's Destiny": 'UD',
|
||||
"Urza's Legacy": 'UL',
|
||||
"Urza's Saga": 'US',
|
||||
'Visions': 'VI',
|
||||
'Weatherlight': 'WL',
|
||||
'Worlds': 'WRL',
|
||||
'WotC Online Store': 'WOTC',
|
||||
'Zendikar': 'ZEN'}
|
||||
|
||||
rarity_abbrevs = {
|
||||
'Land': 'L',
|
||||
'Common': 'C',
|
||||
'Uncommon': 'UC',
|
||||
'Rare': 'R',
|
||||
'Special': 'S',
|
||||
'Mythic Rare': 'MR'}
|
|
@ -0,0 +1,73 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
|
||||
from util import hook
|
||||
|
||||
|
||||
@hook.command
|
||||
def munge(inp, munge_count=0):
|
||||
".munge <text> -- munges up the given text"
|
||||
reps = 0
|
||||
for n in xrange(len(inp)):
|
||||
rep = character_replacements.get(inp[n])
|
||||
if rep:
|
||||
inp = inp[:n] + rep.decode('utf8') + inp[n + 1:]
|
||||
reps += 1
|
||||
if reps == munge_count:
|
||||
break
|
||||
return inp
|
||||
|
||||
|
||||
character_replacements = {
|
||||
'a': 'ä',
|
||||
# 'b': 'Б',
|
||||
'c': 'ċ',
|
||||
'd': 'đ',
|
||||
'e': 'ë',
|
||||
'f': 'ƒ',
|
||||
'g': 'ġ',
|
||||
'h': 'ħ',
|
||||
'i': 'í',
|
||||
'j': 'ĵ',
|
||||
'k': 'ķ',
|
||||
'l': 'ĺ',
|
||||
# 'm': 'ṁ',
|
||||
'n': 'ñ',
|
||||
'o': 'ö',
|
||||
'p': 'ρ',
|
||||
# 'q': 'ʠ',
|
||||
'r': 'ŗ',
|
||||
's': 'š',
|
||||
't': 'ţ',
|
||||
'u': 'ü',
|
||||
# 'v': '',
|
||||
'w': 'ω',
|
||||
'x': 'χ',
|
||||
'y': 'ÿ',
|
||||
'z': 'ź',
|
||||
'A': 'Å',
|
||||
'B': 'Β',
|
||||
'C': 'Ç',
|
||||
'D': 'Ď',
|
||||
'E': 'Ē',
|
||||
# 'F': 'Ḟ',
|
||||
'G': 'Ġ',
|
||||
'H': 'Ħ',
|
||||
'I': 'Í',
|
||||
'J': 'Ĵ',
|
||||
'K': 'Ķ',
|
||||
'L': 'Ĺ',
|
||||
'M': 'Μ',
|
||||
'N': 'Ν',
|
||||
'O': 'Ö',
|
||||
'P': 'Р',
|
||||
# 'Q': 'Q',
|
||||
'R': 'Ŗ',
|
||||
'S': 'Š',
|
||||
'T': 'Ţ',
|
||||
'U': 'Ů',
|
||||
# 'V': 'Ṿ',
|
||||
'W': 'Ŵ',
|
||||
'X': 'Χ',
|
||||
'Y': 'Ỳ',
|
||||
'Z': 'Ż'}
|
|
@ -0,0 +1,58 @@
|
|||
# Password generation code by <TheNoodle>
|
||||
|
||||
from util import hook
|
||||
import string
|
||||
import random
|
||||
|
||||
def gen_password(types):
|
||||
#Password Generator - The Noodle http://bowlofnoodles.net
|
||||
|
||||
okay = []
|
||||
#find the length needed for the password
|
||||
numb = types.split(" ")
|
||||
|
||||
for x in numb[0]:
|
||||
#if any errors are found defualt to 10
|
||||
if x not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
|
||||
numb[0] = 10
|
||||
length = int(numb[0])
|
||||
needs_def = 0
|
||||
#alpha characters
|
||||
if "alpha" in types or "letter" in types:
|
||||
for x in string.ascii_lowercase:
|
||||
okay.append(x)
|
||||
#adds capital characters if not told not to
|
||||
if "no caps" not in types:
|
||||
for x in string.ascii_uppercase:
|
||||
okay.append(x)
|
||||
else:
|
||||
needs_def = 1
|
||||
#adds numbers
|
||||
if "numeric" in types or "numbers" in types:
|
||||
for x in range(0,10):
|
||||
okay.append(str(x))
|
||||
else:
|
||||
needs_def = 1
|
||||
#adds symbols
|
||||
if "symbols" in types:
|
||||
sym = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_', '+', '[', ']', '{', '}', '\\', '|', ';', ':', "'", '.', '>', ',', '<', '/', '?', '`', '~','"']
|
||||
for x in sym:
|
||||
okay.append(x)
|
||||
else:
|
||||
needs_def = 1
|
||||
#defualts to lowercase alpha password if no arguments are found
|
||||
if needs_def == 1:
|
||||
for x in string.ascii_lowercase:
|
||||
okay.append(x)
|
||||
password = ""
|
||||
#generates password
|
||||
for x in range(length):
|
||||
password = password + random.choice(okay)
|
||||
return password
|
||||
|
||||
@hook.command
|
||||
def password(inp, notice=None):
|
||||
".password <length> [types] -- generates a password. types can include 'alpha', 'no caps', 'numeric', 'symbols' or any combination of the types, eg. 'numbers symbols'"
|
||||
if inp == "penis":
|
||||
return "Unable to process request, input too short"
|
||||
notice(gen_password(inp))
|
|
@ -0,0 +1,26 @@
|
|||
from util import hook
|
||||
import re
|
||||
import random
|
||||
|
||||
potatoeslist = ['AC Belmont', 'AC Blue Pride', 'AC Brador', 'AC Chaleur', 'AC Domino', 'AC Dubuc', 'AC Glacier Chip', 'AC Maple Gold', 'AC Novachip', 'AC Peregrine Red', 'AC Ptarmigan', 'AC Red Island', 'AC Saguenor', 'AC Stampede Russet', 'AC Sunbury', 'Abeille', 'Abnaki', 'Acadia', 'Acadia Russet', 'Accent', 'Adirondack Blue', 'Adirondack Red', 'Adora', 'Agria', 'All Blue', 'All Red', 'Alpha', 'Alta Russet', 'Alturas Russet', 'Amandine', 'Amisk', 'Andover', 'Anoka', 'Anson', 'Aquilon', 'Arran Consul', 'Asterix', 'Atlantic', 'Austrian Crescent', 'Avalanche', 'Banana', 'Bannock Russet', 'Batoche', 'BeRus', 'Belle De Fonteney', 'Belleisle', 'Bintje', 'Blossom', 'Blue Christie', 'Blue Mac', 'Brigus', 'Brise du Nord', 'Butte', 'Butterfinger', 'Caesar', 'CalWhite', 'CalRed', 'Caribe', 'Carlingford', 'Carlton', 'Carola', 'Cascade', 'Castile', 'Centennial Russet', 'Century Russet', 'Charlotte', 'Cherie', 'Cherokee', 'Cherry Red', 'Chieftain', 'Chipeta', 'Coastal Russet', 'Colorado Rose', 'Concurrent', 'Conestoga', 'Cowhorn', 'Crestone Russet', 'Crispin', 'Cupids', 'Daisy Gold', 'Dakota Pearl', 'Defender', 'Delikat', 'Denali', 'Desiree', 'Divina', 'Dundrod', 'Durango Red', 'Early Rose', 'Elba', 'Envol', 'Epicure', 'Eramosa', 'Estima', 'Eva', 'Fabula', 'Fambo', 'Fremont Russet', 'French Fingerling', 'Frontier Russet', 'Fundy', 'Garnet Chile', 'Gem Russet', 'GemStar Russet', 'Gemchip', 'German Butterball', 'Gigant', 'Goldrush', 'Granola', 'Green Mountain', 'Haida', 'Hertha', 'Hilite Russet', 'Huckleberry', 'Hunter', 'Huron', 'IdaRose', 'Innovator', 'Irish Cobbler', 'Island Sunshine', 'Ivory Crisp', 'Jacqueline Lee', 'Jemseg', 'Kanona', 'Katahdin', 'Kennebec', "Kerr's Pink", 'Keswick', 'Keuka Gold', 'Keystone Russet', 'King Edward VII', 'Kipfel', 'Klamath Russet', 'Krantz', 'LaRatte', 'Lady Rosetta', 'Latona', 'Lemhi Russet', 'Liberator', 'Lili', 'MaineChip', 'Marfona', 'Maris Bard', 'Maris Piper', 'Matilda', 'Mazama', 'McIntyre', 'Michigan Purple', 'Millenium Russet', 'Mirton Pearl', 'Modoc', 'Mondial', 'Monona', 'Morene', 'Morning Gold', 'Mouraska', 'Navan', 'Nicola', 'Nipigon', 'Niska', 'Nooksack', 'NorValley', 'Norchip', 'Nordonna', 'Norgold Russet', 'Norking Russet', 'Norland', 'Norwis', 'Obelix', 'Ozette', 'Peanut', 'Penta', 'Peribonka', 'Peruvian Purple', 'Pike', 'Pink Pearl', 'Prospect', 'Pungo', 'Purple Majesty', 'Purple Viking', 'Ranger Russet', 'Reba', 'Red Cloud', 'Red Gold', 'Red La Soda', 'Red Pontiac', 'Red Ruby', 'Red Thumb', 'Redsen', 'Rocket', 'Rose Finn Apple', 'Rose Gold', 'Roselys', 'Rote Erstling', 'Ruby Crescent', 'Russet Burbank', 'Russet Legend', 'Russet Norkotah', 'Russet Nugget', 'Russian Banana', 'Saginaw Gold', 'Sangre', 'Santé', 'Satina', 'Saxon', 'Sebago', 'Shepody', 'Sierra', 'Silverton Russet', 'Simcoe', 'Snowden', 'Spunta', "St. John's", 'Summit Russet', 'Sunrise', 'Superior', 'Symfonia', 'Tolaas', 'Trent', 'True Blue', 'Ulla', 'Umatilla Russet', 'Valisa', 'Van Gogh', 'Viking', 'Wallowa Russet', 'Warba', 'Western Russet', 'White Rose', 'Willamette', 'Winema', 'Yellow Finn', 'Yukon Gold']
|
||||
|
||||
@hook.command
|
||||
def potato(inp, me = None, input=None):
|
||||
".potato <user> - makes the user a tasty little potato"
|
||||
inp = inp.strip()
|
||||
|
||||
if not re.match("^[A-Za-z0-9_|.-\]\[]*$", inp.lower()):
|
||||
return "I cant make a tasty potato for that user!"
|
||||
|
||||
potatoa = random.choice(potatoeslist)
|
||||
size = random.choice(['small', 'little', 'mid-sized', 'medium-sized', 'large', 'gigantic'])
|
||||
flavor = random.choice(['tasty', 'delectable', 'delicious', 'yummy', 'toothsome', 'scrumptious', 'luscious'])
|
||||
cook = random.choice(['bakes', 'fries', 'boils', 'microwaves'])
|
||||
|
||||
me(cook + " a " + flavor + " " + size + " " + potatoa + " potato for " + inp + "!")
|
||||
|
||||
@hook.command(autohelp=False)
|
||||
def potatoes(inp, me = None, input=None):
|
||||
potatoa = random.choice(potatoeslist)
|
||||
count = str(len(potatoeslist))
|
||||
me("contemplates eating a "+potatoa+" potato, one of the "+count+" types of potatoes that I know about.")
|
|
@ -0,0 +1,98 @@
|
|||
#-----------------------------------------------------------------
|
||||
# pycparser: cdecl.py
|
||||
#
|
||||
# Example of the CDECL tool using pycparser. CDECL "explains"
|
||||
# C type declarations in plain English.
|
||||
#
|
||||
# The AST generated by pycparser from the given declaration is
|
||||
# traversed recursively to build the explanation.
|
||||
# Note that the declaration must be a valid external declaration
|
||||
# in C. All the types used in it must be defined with typedef,
|
||||
# or parsing will fail. The definition can be arbitrary, it isn't
|
||||
# really used - by pycparser must know which tokens are types.
|
||||
#
|
||||
# For example:
|
||||
#
|
||||
# 'typedef int Node; const Node* (*ar)[10];'
|
||||
# =>
|
||||
# ar is a pointer to array[10] of pointer to const Node
|
||||
#
|
||||
# Copyright (C) 2008, Eli Bendersky
|
||||
# License: LGPL
|
||||
#-----------------------------------------------------------------
|
||||
import sys
|
||||
|
||||
from pycparser import c_parser, c_ast
|
||||
|
||||
|
||||
def explain_c_declaration(c_decl):
|
||||
""" Parses the declaration in c_decl and returns a text
|
||||
explanation as a string.
|
||||
|
||||
The last external node of the string is used, to allow
|
||||
earlier typedefs for used types.
|
||||
"""
|
||||
parser = c_parser.CParser()
|
||||
|
||||
node = parser.parse(c_decl, filename='<stdin>')
|
||||
|
||||
if ( not isinstance(node, c_ast.FileAST) or
|
||||
not isinstance(node.ext[-1], c_ast.Decl)):
|
||||
return "Last external node is invalid type"
|
||||
|
||||
return _explain_decl_node(node.ext[-1])
|
||||
|
||||
|
||||
def _explain_decl_node(decl_node):
|
||||
""" Receives a c_ast.Decl note and returns its explanation in
|
||||
English.
|
||||
"""
|
||||
#~ print decl_node.show()
|
||||
storage = ' '.join(decl_node.storage) + ' ' if decl_node.storage else ''
|
||||
|
||||
return (decl_node.name +
|
||||
" is a " +
|
||||
storage +
|
||||
_explain_type(decl_node.type))
|
||||
|
||||
|
||||
def _explain_type(decl):
|
||||
""" Recursively explains a type decl node
|
||||
"""
|
||||
typ = type(decl)
|
||||
|
||||
if typ == c_ast.TypeDecl:
|
||||
quals = ' '.join(decl.quals) + ' ' if decl.quals else ''
|
||||
return quals + _explain_type(decl.type)
|
||||
elif typ == c_ast.Typename or typ == c_ast.Decl:
|
||||
return _explain_type(decl.type)
|
||||
elif typ == c_ast.IdentifierType:
|
||||
return ' '.join(decl.names)
|
||||
elif typ == c_ast.PtrDecl:
|
||||
quals = ' '.join(decl.quals) + ' ' if decl.quals else ''
|
||||
return quals + 'pointer to ' + _explain_type(decl.type)
|
||||
elif typ == c_ast.ArrayDecl:
|
||||
arr = 'array'
|
||||
if decl.dim: arr += '[%s]' % decl.dim.value
|
||||
|
||||
return arr + " of " + _explain_type(decl.type)
|
||||
|
||||
elif typ == c_ast.FuncDecl:
|
||||
if decl.args:
|
||||
params = [_explain_type(param) for param in decl.args.params]
|
||||
args = ', '.join(params)
|
||||
else:
|
||||
args = ''
|
||||
|
||||
return ('function(%s) returning ' % (args) +
|
||||
_explain_type(decl.type))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 1:
|
||||
c_decl = sys.argv[1]
|
||||
else:
|
||||
c_decl = "char *(*(**foo[][8])())[];"
|
||||
|
||||
print "Explaining the declaration:", c_decl
|
||||
print "\n", explain_c_declaration(c_decl)
|
|
@ -0,0 +1,9 @@
|
|||
# pycparser.lextab.py. This file automatically created by PLY (version 3.3). Don't edit!
|
||||
_tabversion = '3.3'
|
||||
_lextokens = {'VOID': 1, 'LBRACKET': 1, 'WCHAR_CONST': 1, 'FLOAT_CONST': 1, 'MINUS': 1, 'RPAREN': 1, 'LONG': 1, 'PLUS': 1, 'ELLIPSIS': 1, 'GT': 1, 'GOTO': 1, 'ENUM': 1, 'PERIOD': 1, 'GE': 1, 'INT_CONST_DEC': 1, 'ARROW': 1, 'DOUBLE': 1, 'MINUSEQUAL': 1, 'INT_CONST_OCT': 1, 'TIMESEQUAL': 1, 'OR': 1, 'SHORT': 1, 'RETURN': 1, 'RSHIFTEQUAL': 1, 'STATIC': 1, 'SIZEOF': 1, 'UNSIGNED': 1, 'UNION': 1, 'COLON': 1, 'WSTRING_LITERAL': 1, 'DIVIDE': 1, 'FOR': 1, 'PLUSPLUS': 1, 'EQUALS': 1, 'ELSE': 1, 'EQ': 1, 'AND': 1, 'TYPEID': 1, 'LBRACE': 1, 'PPHASH': 1, 'INT': 1, 'SIGNED': 1, 'CONTINUE': 1, 'NOT': 1, 'OREQUAL': 1, 'MOD': 1, 'RSHIFT': 1, 'DEFAULT': 1, 'CHAR': 1, 'WHILE': 1, 'DIVEQUAL': 1, 'EXTERN': 1, 'CASE': 1, 'LAND': 1, 'REGISTER': 1, 'MODEQUAL': 1, 'NE': 1, 'SWITCH': 1, 'INT_CONST_HEX': 1, 'PLUSEQUAL': 1, 'STRUCT': 1, 'CONDOP': 1, 'BREAK': 1, 'VOLATILE': 1, 'ANDEQUAL': 1, 'DO': 1, 'LNOT': 1, 'CONST': 1, 'LOR': 1, 'CHAR_CONST': 1, 'LSHIFT': 1, 'RBRACE': 1, 'LE': 1, 'SEMI': 1, 'LT': 1, 'COMMA': 1, 'TYPEDEF': 1, 'XOR': 1, 'AUTO': 1, 'TIMES': 1, 'LPAREN': 1, 'MINUSMINUS': 1, 'ID': 1, 'IF': 1, 'STRING_LITERAL': 1, 'FLOAT': 1, 'XOREQUAL': 1, 'LSHIFTEQUAL': 1, 'RBRACKET': 1}
|
||||
_lexreflags = 0
|
||||
_lexliterals = ''
|
||||
_lexstateinfo = {'ppline': 'exclusive', 'INITIAL': 'inclusive'}
|
||||
_lexstatere = {'ppline': [('(?P<t_ppline_FILENAME>"([^"\\\\\\n]|(\\\\(([a-zA-Z\\\\?\'"])|([0-7]{1,3})|(x[0-9a-fA-F]+))))*")|(?P<t_ppline_LINE_NUMBER>(0(([uU][lL])|([lL][uU])|[uU]|[lL])?)|([1-9][0-9]*(([uU][lL])|([lL][uU])|[uU]|[lL])?))|(?P<t_ppline_NEWLINE>\\n)|(?P<t_ppline_PPLINE>line)', [None, ('t_ppline_FILENAME', 'FILENAME'), None, None, None, None, None, None, ('t_ppline_LINE_NUMBER', 'LINE_NUMBER'), None, None, None, None, None, None, None, None, ('t_ppline_NEWLINE', 'NEWLINE'), ('t_ppline_PPLINE', 'PPLINE')])], 'INITIAL': [('(?P<t_PPHASH>[ \\t]*\\#)|(?P<t_NEWLINE>\\n+)|(?P<t_FLOAT_CONST>((((([0-9]*\\.[0-9]+)|([0-9]+\\.))([eE][-+]?[0-9]+)?)|([0-9]+([eE][-+]?[0-9]+)))[FfLl]?))|(?P<t_INT_CONST_HEX>0[xX][0-9a-fA-F]+(([uU][lL])|([lL][uU])|[uU]|[lL])?)|(?P<t_BAD_CONST_OCT>0[0-7]*[89])|(?P<t_INT_CONST_OCT>0[0-7]*(([uU][lL])|([lL][uU])|[uU]|[lL])?)|(?P<t_INT_CONST_DEC>(0(([uU][lL])|([lL][uU])|[uU]|[lL])?)|([1-9][0-9]*(([uU][lL])|([lL][uU])|[uU]|[lL])?))|(?P<t_CHAR_CONST>\'([^\'\\\\\\n]|(\\\\(([a-zA-Z\\\\?\'"])|([0-7]{1,3})|(x[0-9a-fA-F]+))))\')|(?P<t_WCHAR_CONST>L\'([^\'\\\\\\n]|(\\\\(([a-zA-Z\\\\?\'"])|([0-7]{1,3})|(x[0-9a-fA-F]+))))\')|(?P<t_UNMATCHED_QUOTE>(\'([^\'\\\\\\n]|(\\\\(([a-zA-Z\\\\?\'"])|([0-7]{1,3})|(x[0-9a-fA-F]+))))*\\n)|(\'([^\'\\\\\\n]|(\\\\(([a-zA-Z\\\\?\'"])|([0-7]{1,3})|(x[0-9a-fA-F]+))))*$))|(?P<t_BAD_CHAR_CONST>(\'([^\'\\\\\\n]|(\\\\(([a-zA-Z\\\\?\'"])|([0-7]{1,3})|(x[0-9a-fA-F]+))))[^\'\n]+\')|(\'\')|(\'([\\\\][^a-zA-Z\\\\?\'"x0-7])[^\'\\n]*\'))|(?P<t_WSTRING_LITERAL>L"([^"\\\\\\n]|(\\\\(([a-zA-Z\\\\?\'"])|([0-7]{1,3})|(x[0-9a-fA-F]+))))*")|(?P<t_BAD_STRING_LITERAL>"([^"\\\\\\n]|(\\\\(([a-zA-Z\\\\?\'"])|([0-7]{1,3})|(x[0-9a-fA-F]+))))*([\\\\][^a-zA-Z\\\\?\'"x0-7])([^"\\\\\\n]|(\\\\(([a-zA-Z\\\\?\'"])|([0-7]{1,3})|(x[0-9a-fA-F]+))))*")|(?P<t_ID>[a-zA-Z_][0-9a-zA-Z_]*)|(?P<t_STRING_LITERAL>"([^"\\\\\\n]|(\\\\(([a-zA-Z\\\\?\'"])|([0-7]{1,3})|(x[0-9a-fA-F]+))))*")', [None, ('t_PPHASH', 'PPHASH'), ('t_NEWLINE', 'NEWLINE'), ('t_FLOAT_CONST', 'FLOAT_CONST'), None, None, None, None, None, None, None, None, None, ('t_INT_CONST_HEX', 'INT_CONST_HEX'), None, None, None, ('t_BAD_CONST_OCT', 'BAD_CONST_OCT'), ('t_INT_CONST_OCT', 'INT_CONST_OCT'), None, None, None, ('t_INT_CONST_DEC', 'INT_CONST_DEC'), None, None, None, None, None, None, None, None, ('t_CHAR_CONST', 'CHAR_CONST'), None, None, None, None, None, None, ('t_WCHAR_CONST', 'WCHAR_CONST'), None, None, None, None, None, None, ('t_UNMATCHED_QUOTE', 'UNMATCHED_QUOTE'), None, None, None, None, None, None, None, None, None, None, None, None, None, None, ('t_BAD_CHAR_CONST', 'BAD_CHAR_CONST'), None, None, None, None, None, None, None, None, None, None, ('t_WSTRING_LITERAL', 'WSTRING_LITERAL'), None, None, None, None, None, None, ('t_BAD_STRING_LITERAL', 'BAD_STRING_LITERAL'), None, None, None, None, None, None, None, None, None, None, None, None, None, ('t_ID', 'ID'), (None, 'STRING_LITERAL')]), ('(?P<t_ELLIPSIS>\\.\\.\\.)|(?P<t_PLUSPLUS>\\+\\+)|(?P<t_LOR>\\|\\|)|(?P<t_OREQUAL>\\|=)|(?P<t_LSHIFTEQUAL><<=)|(?P<t_RSHIFTEQUAL>>>=)|(?P<t_TIMESEQUAL>\\*=)|(?P<t_PLUSEQUAL>\\+=)|(?P<t_XOREQUAL>^=)|(?P<t_PLUS>\\+)|(?P<t_MODEQUAL>%=)|(?P<t_LBRACE>\\{)|(?P<t_DIVEQUAL>/=)|(?P<t_RBRACKET>\\])|(?P<t_CONDOP>\\?)', [None, (None, 'ELLIPSIS'), (None, 'PLUSPLUS'), (None, 'LOR'), (None, 'OREQUAL'), (None, 'LSHIFTEQUAL'), (None, 'RSHIFTEQUAL'), (None, 'TIMESEQUAL'), (None, 'PLUSEQUAL'), (None, 'XOREQUAL'), (None, 'PLUS'), (None, 'MODEQUAL'), (None, 'LBRACE'), (None, 'DIVEQUAL'), (None, 'RBRACKET'), (None, 'CONDOP')]), ('(?P<t_XOR>\\^)|(?P<t_LSHIFT><<)|(?P<t_LE><=)|(?P<t_LPAREN>\\()|(?P<t_ARROW>->)|(?P<t_EQ>==)|(?P<t_RBRACE>\\})|(?P<t_NE>!=)|(?P<t_MINUSMINUS>--)|(?P<t_OR>\\|)|(?P<t_TIMES>\\*)|(?P<t_LBRACKET>\\[)|(?P<t_GE>>=)|(?P<t_RPAREN>\\))|(?P<t_LAND>&&)|(?P<t_RSHIFT>>>)|(?P<t_ANDEQUAL>&=)|(?P<t_MINUSEQUAL>-=)|(?P<t_PERIOD>\\.)|(?P<t_EQUALS>=)|(?P<t_LT><)|(?P<t_COMMA>,)|(?P<t_DIVIDE>/)|(?P<t_AND>&)|(?P<t_MOD>%)|(?P<t_SEMI>;)|(?P<t_MINUS>-)|(?P<t_GT>>)|(?P<t_COLON>:)|(?P<t_NOT>~)|(?P<t_LNOT>!)', [None, (None, 'XOR'), (None, 'LSHIFT'), (None, 'LE'), (None, 'LPAREN'), (None, 'ARROW'), (None, 'EQ'), (None, 'RBRACE'), (None, 'NE'), (None, 'MINUSMINUS'), (None, 'OR'), (None, 'TIMES'), (None, 'LBRACKET'), (None, 'GE'), (None, 'RPAREN'), (None, 'LAND'), (None, 'RSHIFT'), (None, 'ANDEQUAL'), (None, 'MINUSEQUAL'), (None, 'PERIOD'), (None, 'EQUALS'), (None, 'LT'), (None, 'COMMA'), (None, 'DIVIDE'), (None, 'AND'), (None, 'MOD'), (None, 'SEMI'), (None, 'MINUS'), (None, 'GT'), (None, 'COLON'), (None, 'NOT'), (None, 'LNOT')])]}
|
||||
_lexstateignore = {'ppline': ' \t', 'INITIAL': ' \t'}
|
||||
_lexstateerrorf = {'ppline': 't_ppline_error', 'INITIAL': 't_error'}
|
|
@ -0,0 +1,75 @@
|
|||
#-----------------------------------------------------------------
|
||||
# pycparser: __init__.py
|
||||
#
|
||||
# This package file exports some convenience functions for
|
||||
# interacting with pycparser
|
||||
#
|
||||
# Copyright (C) 2008-2009, Eli Bendersky
|
||||
# License: LGPL
|
||||
#-----------------------------------------------------------------
|
||||
|
||||
__all__ = ['c_lexer', 'c_parser', 'c_ast']
|
||||
__version__ = '1.05'
|
||||
|
||||
from subprocess import Popen, PIPE
|
||||
from types import ListType
|
||||
|
||||
from c_parser import CParser
|
||||
|
||||
|
||||
def parse_file( filename, use_cpp=False,
|
||||
cpp_path='cpp', cpp_args=''):
|
||||
""" Parse a C file using pycparser.
|
||||
|
||||
filename:
|
||||
Name of the file you want to parse.
|
||||
|
||||
use_cpp:
|
||||
Set to True if you want to execute the C pre-processor
|
||||
on the file prior to parsing it.
|
||||
|
||||
cpp_path:
|
||||
If use_cpp is True, this is the path to 'cpp' on your
|
||||
system. If no path is provided, it attempts to just
|
||||
execute 'cpp', so it must be in your PATH.
|
||||
|
||||
cpp_args:
|
||||
If use_cpp is True, set this to the command line
|
||||
arguments strings to cpp. Be careful with quotes -
|
||||
it's best to pass a raw string (r'') here.
|
||||
For example:
|
||||
r'-I../utils/fake_libc_include'
|
||||
If several arguments are required, pass a list of
|
||||
strings.
|
||||
|
||||
When successful, an AST is returned. ParseError can be
|
||||
thrown if the file doesn't parse successfully.
|
||||
|
||||
Errors from cpp will be printed out.
|
||||
"""
|
||||
if use_cpp:
|
||||
path_list = [cpp_path]
|
||||
if isinstance(cpp_args, ListType):
|
||||
path_list += cpp_args
|
||||
elif cpp_args != '':
|
||||
path_list += [cpp_args]
|
||||
path_list += [filename]
|
||||
|
||||
# Note the use of universal_newlines to treat all newlines
|
||||
# as \n for Python's purpose
|
||||
#
|
||||
pipe = Popen( path_list,
|
||||
stdout=PIPE,
|
||||
universal_newlines=True)
|
||||
text = pipe.communicate()[0]
|
||||
else:
|
||||
text = open(filename).read()
|
||||
|
||||
parser = CParser()
|
||||
return parser.parse(text, filename)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pass
|
||||
|
||||
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,443 @@
|
|||
#-----------------------------------------------------------------
|
||||
# pycparser: clex.py
|
||||
#
|
||||
# CLexer class: lexer for the C language
|
||||
#
|
||||
# Copyright (C) 2008, Eli Bendersky
|
||||
# License: LGPL
|
||||
#-----------------------------------------------------------------
|
||||
|
||||
import re
|
||||
import sys
|
||||
|
||||
import ply.lex
|
||||
from ply.lex import TOKEN
|
||||
|
||||
|
||||
class CLexer(object):
|
||||
""" A lexer for the C language. After building it, set the
|
||||
input text with input(), and call token() to get new
|
||||
tokens.
|
||||
|
||||
The public attribute filename can be set to an initial
|
||||
filaneme, but the lexer will update it upon #line
|
||||
directives.
|
||||
"""
|
||||
def __init__(self, error_func, type_lookup_func):
|
||||
""" Create a new Lexer.
|
||||
|
||||
error_func:
|
||||
An error function. Will be called with an error
|
||||
message, line and column as arguments, in case of
|
||||
an error during lexing.
|
||||
|
||||
type_lookup_func:
|
||||
A type lookup function. Given a string, it must
|
||||
return True IFF this string is a name of a type
|
||||
that was defined with a typedef earlier.
|
||||
"""
|
||||
self.error_func = error_func
|
||||
self.type_lookup_func = type_lookup_func
|
||||
self.filename = ''
|
||||
|
||||
# Allow either "# line" or "# <num>" to support GCC's
|
||||
# cpp output
|
||||
#
|
||||
self.line_pattern = re.compile('([ \t]*line\W)|([ \t]*\d+)')
|
||||
|
||||
def build(self, **kwargs):
|
||||
""" Builds the lexer from the specification. Must be
|
||||
called after the lexer object is created.
|
||||
|
||||
This method exists separately, because the PLY
|
||||
manual warns against calling lex.lex inside
|
||||
__init__
|
||||
"""
|
||||
self.lexer = ply.lex.lex(object=self, **kwargs)
|
||||
|
||||
def reset_lineno(self):
|
||||
""" Resets the internal line number counter of the lexer.
|
||||
"""
|
||||
self.lexer.lineno = 1
|
||||
|
||||
def input(self, text):
|
||||
self.lexer.input(text)
|
||||
|
||||
def token(self):
|
||||
g = self.lexer.token()
|
||||
return g
|
||||
|
||||
######################-- PRIVATE --######################
|
||||
|
||||
##
|
||||
## Internal auxiliary methods
|
||||
##
|
||||
def _error(self, msg, token):
|
||||
location = self._make_tok_location(token)
|
||||
self.error_func(msg, location[0], location[1])
|
||||
self.lexer.skip(1)
|
||||
|
||||
def _find_tok_column(self, token):
|
||||
i = token.lexpos
|
||||
while i > 0:
|
||||
if self.lexer.lexdata[i] == '\n': break
|
||||
i -= 1
|
||||
return (token.lexpos - i) + 1
|
||||
|
||||
def _make_tok_location(self, token):
|
||||
return (token.lineno, self._find_tok_column(token))
|
||||
|
||||
##
|
||||
## Reserved keywords
|
||||
##
|
||||
keywords = (
|
||||
'AUTO', 'BREAK', 'CASE', 'CHAR', 'CONST', 'CONTINUE',
|
||||
'DEFAULT', 'DO', 'DOUBLE', 'ELSE', 'ENUM', 'EXTERN',
|
||||
'FLOAT', 'FOR', 'GOTO', 'IF', 'INT', 'LONG', 'REGISTER',
|
||||
'RETURN', 'SHORT', 'SIGNED', 'SIZEOF', 'STATIC', 'STRUCT',
|
||||
'SWITCH', 'TYPEDEF', 'UNION', 'UNSIGNED', 'VOID',
|
||||
'VOLATILE', 'WHILE',
|
||||
)
|
||||
|
||||
keyword_map = {}
|
||||
for r in keywords:
|
||||
keyword_map[r.lower()] = r
|
||||
|
||||
##
|
||||
## All the tokens recognized by the lexer
|
||||
##
|
||||
tokens = keywords + (
|
||||
# Identifiers
|
||||
'ID',
|
||||
|
||||
# Type identifiers (identifiers previously defined as
|
||||
# types with typedef)
|
||||
'TYPEID',
|
||||
|
||||
# constants
|
||||
'INT_CONST_DEC', 'INT_CONST_OCT', 'INT_CONST_HEX',
|
||||
'FLOAT_CONST',
|
||||
'CHAR_CONST',
|
||||
'WCHAR_CONST',
|
||||
|
||||
# String literals
|
||||
'STRING_LITERAL',
|
||||
'WSTRING_LITERAL',
|
||||
|
||||
# Operators
|
||||
'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MOD',
|
||||
'OR', 'AND', 'NOT', 'XOR', 'LSHIFT', 'RSHIFT',
|
||||
'LOR', 'LAND', 'LNOT',
|
||||
'LT', 'LE', 'GT', 'GE', 'EQ', 'NE',
|
||||
|
||||
# Assignment
|
||||
'EQUALS', 'TIMESEQUAL', 'DIVEQUAL', 'MODEQUAL',
|
||||
'PLUSEQUAL', 'MINUSEQUAL',
|
||||
'LSHIFTEQUAL','RSHIFTEQUAL', 'ANDEQUAL', 'XOREQUAL',
|
||||
'OREQUAL',
|
||||
|
||||
# Increment/decrement
|
||||
'PLUSPLUS', 'MINUSMINUS',
|
||||
|
||||
# Structure dereference (->)
|
||||
'ARROW',
|
||||
|
||||
# Conditional operator (?)
|
||||
'CONDOP',
|
||||
|
||||
# Delimeters
|
||||
'LPAREN', 'RPAREN', # ( )
|
||||
'LBRACKET', 'RBRACKET', # [ ]
|
||||
'LBRACE', 'RBRACE', # { }
|
||||
'COMMA', 'PERIOD', # . ,
|
||||
'SEMI', 'COLON', # ; :
|
||||
|
||||
# Ellipsis (...)
|
||||
'ELLIPSIS',
|
||||
|
||||
# pre-processor
|
||||
'PPHASH', # '#'
|
||||
)
|
||||
|
||||
##
|
||||
## Regexes for use in tokens
|
||||
##
|
||||
##
|
||||
|
||||
# valid C identifiers (K&R2: A.2.3)
|
||||
identifier = r'[a-zA-Z_][0-9a-zA-Z_]*'
|
||||
|
||||
# integer constants (K&R2: A.2.5.1)
|
||||
integer_suffix_opt = r'(([uU][lL])|([lL][uU])|[uU]|[lL])?'
|
||||
decimal_constant = '(0'+integer_suffix_opt+')|([1-9][0-9]*'+integer_suffix_opt+')'
|
||||
octal_constant = '0[0-7]*'+integer_suffix_opt
|
||||
hex_constant = '0[xX][0-9a-fA-F]+'+integer_suffix_opt
|
||||
|
||||
bad_octal_constant = '0[0-7]*[89]'
|
||||
|
||||
# character constants (K&R2: A.2.5.2)
|
||||
# Note: a-zA-Z are allowed as escape chars to support #line
|
||||
# directives with Windows paths as filenames (\dir\file...)
|
||||
#
|
||||
simple_escape = r"""([a-zA-Z\\?'"])"""
|
||||
octal_escape = r"""([0-7]{1,3})"""
|
||||
hex_escape = r"""(x[0-9a-fA-F]+)"""
|
||||
bad_escape = r"""([\\][^a-zA-Z\\?'"x0-7])"""
|
||||
|
||||
escape_sequence = r"""(\\("""+simple_escape+'|'+octal_escape+'|'+hex_escape+'))'
|
||||
cconst_char = r"""([^'\\\n]|"""+escape_sequence+')'
|
||||
char_const = "'"+cconst_char+"'"
|
||||
wchar_const = 'L'+char_const
|
||||
unmatched_quote = "('"+cconst_char+"*\\n)|('"+cconst_char+"*$)"
|
||||
bad_char_const = r"""('"""+cconst_char+"""[^'\n]+')|('')|('"""+bad_escape+r"""[^'\n]*')"""
|
||||
|
||||
# string literals (K&R2: A.2.6)
|
||||
string_char = r"""([^"\\\n]|"""+escape_sequence+')'
|
||||
string_literal = '"'+string_char+'*"'
|
||||
wstring_literal = 'L'+string_literal
|
||||
bad_string_literal = '"'+string_char+'*'+bad_escape+string_char+'*"'
|
||||
|
||||
# floating constants (K&R2: A.2.5.3)
|
||||
exponent_part = r"""([eE][-+]?[0-9]+)"""
|
||||
fractional_constant = r"""([0-9]*\.[0-9]+)|([0-9]+\.)"""
|
||||
floating_constant = '(((('+fractional_constant+')'+exponent_part+'?)|([0-9]+'+exponent_part+'))[FfLl]?)'
|
||||
|
||||
##
|
||||
## Lexer states
|
||||
##
|
||||
states = (
|
||||
# ppline: preprocessor line directives
|
||||
#
|
||||
('ppline', 'exclusive'),
|
||||
)
|
||||
|
||||
def t_PPHASH(self, t):
|
||||
r'[ \t]*\#'
|
||||
m = self.line_pattern.match(
|
||||
t.lexer.lexdata, pos=t.lexer.lexpos)
|
||||
|
||||
if m:
|
||||
t.lexer.begin('ppline')
|
||||
self.pp_line = self.pp_filename = None
|
||||
#~ print "ppline starts on line %s" % t.lexer.lineno
|
||||
else:
|
||||
t.type = 'PPHASH'
|
||||
return t
|
||||
|
||||
##
|
||||
## Rules for the ppline state
|
||||
##
|
||||
@TOKEN(string_literal)
|
||||
def t_ppline_FILENAME(self, t):
|
||||
if self.pp_line is None:
|
||||
self._error('filename before line number in #line', t)
|
||||
else:
|
||||
self.pp_filename = t.value.lstrip('"').rstrip('"')
|
||||
#~ print "PP got filename: ", self.pp_filename
|
||||
|
||||
@TOKEN(decimal_constant)
|
||||
def t_ppline_LINE_NUMBER(self, t):
|
||||
if self.pp_line is None:
|
||||
self.pp_line = t.value
|
||||
else:
|
||||
# Ignore: GCC's cpp sometimes inserts a numeric flag
|
||||
# after the file name
|
||||
pass
|
||||
|
||||
def t_ppline_NEWLINE(self, t):
|
||||
r'\n'
|
||||
|
||||
if self.pp_line is None:
|
||||
self._error('line number missing in #line', t)
|
||||
else:
|
||||
self.lexer.lineno = int(self.pp_line)
|
||||
|
||||
if self.pp_filename is not None:
|
||||
self.filename = self.pp_filename
|
||||
|
||||
t.lexer.begin('INITIAL')
|
||||
|
||||
def t_ppline_PPLINE(self, t):
|
||||
r'line'
|
||||
pass
|
||||
|
||||
t_ppline_ignore = ' \t'
|
||||
|
||||
def t_ppline_error(self, t):
|
||||
msg = 'invalid #line directive'
|
||||
self._error(msg, t)
|
||||
|
||||
##
|
||||
## Rules for the normal state
|
||||
##
|
||||
t_ignore = ' \t'
|
||||
|
||||
# Newlines
|
||||
def t_NEWLINE(self, t):
|
||||
r'\n+'
|
||||
t.lexer.lineno += t.value.count("\n")
|
||||
|
||||
# Operators
|
||||
t_PLUS = r'\+'
|
||||
t_MINUS = r'-'
|
||||
t_TIMES = r'\*'
|
||||
t_DIVIDE = r'/'
|
||||
t_MOD = r'%'
|
||||
t_OR = r'\|'
|
||||
t_AND = r'&'
|
||||
t_NOT = r'~'
|
||||
t_XOR = r'\^'
|
||||
t_LSHIFT = r'<<'
|
||||
t_RSHIFT = r'>>'
|
||||
t_LOR = r'\|\|'
|
||||
t_LAND = r'&&'
|
||||
t_LNOT = r'!'
|
||||
t_LT = r'<'
|
||||
t_GT = r'>'
|
||||
t_LE = r'<='
|
||||
t_GE = r'>='
|
||||
t_EQ = r'=='
|
||||
t_NE = r'!='
|
||||
|
||||
# Assignment operators
|
||||
t_EQUALS = r'='
|
||||
t_TIMESEQUAL = r'\*='
|
||||
t_DIVEQUAL = r'/='
|
||||
t_MODEQUAL = r'%='
|
||||
t_PLUSEQUAL = r'\+='
|
||||
t_MINUSEQUAL = r'-='
|
||||
t_LSHIFTEQUAL = r'<<='
|
||||
t_RSHIFTEQUAL = r'>>='
|
||||
t_ANDEQUAL = r'&='
|
||||
t_OREQUAL = r'\|='
|
||||
t_XOREQUAL = r'^='
|
||||
|
||||
# Increment/decrement
|
||||
t_PLUSPLUS = r'\+\+'
|
||||
t_MINUSMINUS = r'--'
|
||||
|
||||
# ->
|
||||
t_ARROW = r'->'
|
||||
|
||||
# ?
|
||||
t_CONDOP = r'\?'
|
||||
|
||||
# Delimeters
|
||||
t_LPAREN = r'\('
|
||||
t_RPAREN = r'\)'
|
||||
t_LBRACKET = r'\['
|
||||
t_RBRACKET = r'\]'
|
||||
t_LBRACE = r'\{'
|
||||
t_RBRACE = r'\}'
|
||||
t_COMMA = r','
|
||||
t_PERIOD = r'\.'
|
||||
t_SEMI = r';'
|
||||
t_COLON = r':'
|
||||
t_ELLIPSIS = r'\.\.\.'
|
||||
|
||||
t_STRING_LITERAL = string_literal
|
||||
|
||||
# The following floating and integer constants are defined as
|
||||
# functions to impose a strict order (otherwise, decimal
|
||||
# is placed before the others because its regex is longer,
|
||||
# and this is bad)
|
||||
#
|
||||
@TOKEN(floating_constant)
|
||||
def t_FLOAT_CONST(self, t):
|
||||
return t
|
||||
|
||||
@TOKEN(hex_constant)
|
||||
def t_INT_CONST_HEX(self, t):
|
||||
return t
|
||||
|
||||
@TOKEN(bad_octal_constant)
|
||||
def t_BAD_CONST_OCT(self, t):
|
||||
msg = "Invalid octal constant"
|
||||
self._error(msg, t)
|
||||
|
||||
@TOKEN(octal_constant)
|
||||
def t_INT_CONST_OCT(self, t):
|
||||
return t
|
||||
|
||||
@TOKEN(decimal_constant)
|
||||
def t_INT_CONST_DEC(self, t):
|
||||
return t
|
||||
|
||||
# Must come before bad_char_const, to prevent it from
|
||||
# catching valid char constants as invalid
|
||||
#
|
||||
@TOKEN(char_const)
|
||||
def t_CHAR_CONST(self, t):
|
||||
return t
|
||||
|
||||
@TOKEN(wchar_const)
|
||||
def t_WCHAR_CONST(self, t):
|
||||
return t
|
||||
|
||||
@TOKEN(unmatched_quote)
|
||||
def t_UNMATCHED_QUOTE(self, t):
|
||||
msg = "Unmatched '"
|
||||
self._error(msg, t)
|
||||
|
||||
@TOKEN(bad_char_const)
|
||||
def t_BAD_CHAR_CONST(self, t):
|
||||
msg = "Invalid char constant %s" % t.value
|
||||
self._error(msg, t)
|
||||
|
||||
@TOKEN(wstring_literal)
|
||||
def t_WSTRING_LITERAL(self, t):
|
||||
return t
|
||||
|
||||
# unmatched string literals are caught by the preprocessor
|
||||
|
||||
@TOKEN(bad_string_literal)
|
||||
def t_BAD_STRING_LITERAL(self, t):
|
||||
msg = "String contains invalid escape code"
|
||||
self._error(msg, t)
|
||||
|
||||
@TOKEN(identifier)
|
||||
def t_ID(self, t):
|
||||
t.type = self.keyword_map.get(t.value, "ID")
|
||||
|
||||
if t.type == 'ID' and self.type_lookup_func(t.value):
|
||||
t.type = "TYPEID"
|
||||
|
||||
return t
|
||||
|
||||
def t_error(self, t):
|
||||
msg = 'Illegal character %s' % repr(t.value[0])
|
||||
self._error(msg, t)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
filename = '../zp.c'
|
||||
text = open(filename).read()
|
||||
|
||||
#~ text = '"'+r"""ka \p ka"""+'"'
|
||||
text = r"""
|
||||
546
|
||||
#line 66 "kwas\df.h"
|
||||
id 4
|
||||
# 5
|
||||
dsf
|
||||
"""
|
||||
|
||||
def errfoo(msg, a, b):
|
||||
print msg
|
||||
sys.exit()
|
||||
|
||||
def typelookup(namd):
|
||||
return False
|
||||
|
||||
clex = CLexer(errfoo, typelookup)
|
||||
clex.build()
|
||||
clex.input(text)
|
||||
|
||||
while 1:
|
||||
tok = clex.token()
|
||||
if not tok: break
|
||||
|
||||
#~ print type(tok)
|
||||
print "-", tok.value, tok.type, tok.lineno, clex.filename, tok.lexpos
|
||||
|
||||
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,4 @@
|
|||
# PLY package
|
||||
# Author: David Beazley (dave@dabeaz.com)
|
||||
|
||||
__all__ = ['lex','yacc']
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,67 @@
|
|||
#-----------------------------------------------------------------
|
||||
# plyparser.py
|
||||
#
|
||||
# PLYParser class and other utilites for simplifying programming
|
||||
# parsers with PLY
|
||||
#
|
||||
# Copyright (C) 2008-2009, Eli Bendersky
|
||||
# License: LGPL
|
||||
#-----------------------------------------------------------------
|
||||
|
||||
|
||||
class Coord(object):
|
||||
""" Coordinates of a syntactic element. Consists of:
|
||||
- File name
|
||||
- Line number
|
||||
- (optional) column number, for the Lexer
|
||||
"""
|
||||
def __init__(self, file, line, column=None):
|
||||
self.file = file
|
||||
self.line = line
|
||||
self.column = column
|
||||
|
||||
def __str__(self):
|
||||
str = "%s:%s" % (self.file, self.line)
|
||||
if self.column: str += ":%s" % self.column
|
||||
return str
|
||||
|
||||
|
||||
class ParseError(Exception): pass
|
||||
|
||||
|
||||
class PLYParser(object):
|
||||
def _create_opt_rule(self, rulename):
|
||||
""" Given a rule name, creates an optional ply.yacc rule
|
||||
for it. The name of the optional rule is
|
||||
<rulename>_opt
|
||||
"""
|
||||
optname = rulename + '_opt'
|
||||
|
||||
def optrule(self, p):
|
||||
p[0] = p[1]
|
||||
|
||||
optrule.__doc__ = '%s : empty\n| %s' % (optname, rulename)
|
||||
optrule.__name__ = 'p_%s' % optname
|
||||
setattr(self.__class__, optrule.__name__, optrule)
|
||||
|
||||
def _coord(self, lineno, column=None):
|
||||
return Coord(
|
||||
file=self.clex.filename,
|
||||
line=lineno,
|
||||
column=column)
|
||||
|
||||
def _parse_error(self, msg, coord):
|
||||
raise ParseError("%s: %s" % (coord, msg))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
pp = PLYParser()
|
||||
pp._create_opt_rule('java')
|
||||
|
||||
ar = [4, 6]
|
||||
pp.p_java_opt(ar)
|
||||
|
||||
print ar
|
||||
print pp.p_java_opt.__doc__
|
||||
|
||||
print dir(pp)
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,24 @@
|
|||
import re
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
re_lineends = re.compile(r'[\r\n]*')
|
||||
|
||||
|
||||
@hook.command
|
||||
def python(inp):
|
||||
".python <prog> -- executes python code <prog>"
|
||||
|
||||
inp = inp.replace("~n", "\n")
|
||||
|
||||
res = http.get("http://eval.appspot.com/eval", statement=inp).splitlines()
|
||||
|
||||
|
||||
if len(res) == 0:
|
||||
return
|
||||
res[0] = re_lineends.split(res[0])[0]
|
||||
if not res[0] == 'Traceback (most recent call last):':
|
||||
return res[0].decode('utf8', 'ignore')
|
||||
else:
|
||||
return res[-1].decode('utf8', 'ignore')
|
|
@ -0,0 +1,98 @@
|
|||
import random
|
||||
import re
|
||||
import time
|
||||
|
||||
from util import hook
|
||||
|
||||
|
||||
def add_quote(db, chan, nick, add_nick, msg):
|
||||
db.execute('''insert or fail into quote (chan, nick, add_nick,
|
||||
msg, time) values(?,?,?,?,?)''',
|
||||
(chan, nick, add_nick, msg, time.time()))
|
||||
db.commit()
|
||||
|
||||
|
||||
def del_quote(db, chan, nick, add_nick, msg):
|
||||
db.execute('''update quote set deleted = 1 where
|
||||
chan=? and lower(nick)=lower(?) and msg=msg''')
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_quotes_by_nick(db, chan, nick):
|
||||
return db.execute("select time, nick, msg from quote where deleted!=1 "
|
||||
"and chan=? and lower(nick)=lower(?) order by time",
|
||||
(chan, nick)).fetchall()
|
||||
|
||||
|
||||
def get_quotes_by_chan(db, chan):
|
||||
return db.execute("select time, nick, msg from quote where deleted!=1 "
|
||||
"and chan=? order by time", (chan,)).fetchall()
|
||||
|
||||
|
||||
def format_quote(q, num, n_quotes):
|
||||
ctime, nick, msg = q
|
||||
return "[%d/%d] %s <%s> %s" % (num, n_quotes,
|
||||
time.strftime("%Y-%m-%d", time.gmtime(ctime)), nick, msg)
|
||||
|
||||
|
||||
@hook.command('q')
|
||||
@hook.command
|
||||
def quote(inp, nick='', chan='', db=None):
|
||||
".q/.quote [#chan] [nick] [#n]/.quote add <nick> <msg> -- gets " \
|
||||
"random or [#n]th quote by <nick> or from <#chan>/adds quote"
|
||||
|
||||
db.execute("create table if not exists quote"
|
||||
"(chan, nick, add_nick, msg, time real, deleted default 0, "
|
||||
"primary key (chan, nick, msg))")
|
||||
db.commit()
|
||||
|
||||
add = re.match(r"add[^\w@]+(\S+?)>?\s+(.*)", inp, re.I)
|
||||
retrieve = re.match(r"(\S+)(?:\s+#?(-?\d+))?$", inp)
|
||||
retrieve_chan = re.match(r"(#\S+)\s+(\S+)(?:\s+#?(-?\d+))?$", inp)
|
||||
|
||||
if add:
|
||||
quoted_nick, msg = add.groups()
|
||||
try:
|
||||
add_quote(db, chan, quoted_nick, nick, msg)
|
||||
db.commit()
|
||||
except db.IntegrityError:
|
||||
return "message already stored, doing nothing."
|
||||
return "quote added."
|
||||
elif retrieve:
|
||||
select, num = retrieve.groups()
|
||||
|
||||
by_chan = False
|
||||
if select.startswith('#'):
|
||||
by_chan = True
|
||||
quotes = get_quotes_by_chan(db, select)
|
||||
else:
|
||||
quotes = get_quotes_by_nick(db, chan, select)
|
||||
elif retrieve_chan:
|
||||
chan, nick, num = retrieve_chan.groups()
|
||||
|
||||
quotes = get_quotes_by_nick(db, chan, nick)
|
||||
else:
|
||||
return quote.__doc__
|
||||
|
||||
n_quotes = len(quotes)
|
||||
|
||||
if not n_quotes:
|
||||
return "no quotes found"
|
||||
|
||||
if num:
|
||||
num = int(num)
|
||||
|
||||
if num:
|
||||
if num > n_quotes or (num < 0 and num < -n_quotes):
|
||||
return "I only have %d quote%s for %s" % (n_quotes,
|
||||
('s', '')[n_quotes == 1], select)
|
||||
elif num < 0:
|
||||
selected_quote = quotes[num]
|
||||
num = n_quotes + num + 1
|
||||
else:
|
||||
selected_quote = quotes[num - 1]
|
||||
else:
|
||||
num = random.randint(1, n_quotes)
|
||||
selected_quote = quotes[num - 1]
|
||||
|
||||
return format_quote(selected_quote, num, n_quotes)
|
|
@ -0,0 +1,26 @@
|
|||
from util import hook
|
||||
import re
|
||||
|
||||
@hook.regex(r'^(H|h)ello mau5bot')
|
||||
def response_hello(inp, say=None, nick=None):
|
||||
say("Hello " + nick + "!")
|
||||
|
||||
@hook.regex(r'^(H|h)i mau5bot')
|
||||
def response_hi(inp, say=None, nick=None):
|
||||
say("Hi " + nick + "!")
|
||||
|
||||
@hook.regex(r'^(H|h)eya mau5bot')
|
||||
def response_heya(inp, say=None, nick=None):
|
||||
say("Heya " + nick + "!")
|
||||
|
||||
@hook.regex(r'^(S|s)up mau5bot')
|
||||
def response_sup(inp, say=None, nick=None):
|
||||
say("Sup " + nick + "!")
|
||||
|
||||
@hook.regex(r'^((I|i) love( you,?)?|ilu) mau5bot')
|
||||
def response_love(inp, say=None, nick=None):
|
||||
say("I love you too, " + nick)
|
||||
|
||||
@hook.regex(r'^((I|i) hate( you,?)?|ihu) mau5bot')
|
||||
def response_hate(inp, say=None):
|
||||
say(";(")
|
|
@ -0,0 +1,181 @@
|
|||
from util import hook, http
|
||||
|
||||
import urllib
|
||||
import random
|
||||
import urllib2
|
||||
import htmlentitydefs
|
||||
import re
|
||||
|
||||
re_htmlent = re.compile("&(" + "|".join(htmlentitydefs.name2codepoint.keys()) + ");")
|
||||
re_numeric = re.compile(r'&#(x?)([a-fA-F0-9]+);')
|
||||
|
||||
|
||||
def db_init(db):
|
||||
db.execute("create table if not exists repaste(chan, manual, primary key(chan))")
|
||||
db.commit()
|
||||
|
||||
|
||||
def decode_html(text):
|
||||
text = re.sub(re_htmlent,
|
||||
lambda m: unichr(htmlentitydefs.name2codepoint[m.group(1)]),
|
||||
text)
|
||||
|
||||
text = re.sub(re_numeric,
|
||||
lambda m: unichr(int(m.group(2), 16 if m.group(1) else 10)),
|
||||
text)
|
||||
return text
|
||||
|
||||
|
||||
def scrape_mibpaste(url):
|
||||
if not url.startswith("http"):
|
||||
url = "http://" + url
|
||||
pagesource = http.get(url)
|
||||
rawpaste = re.search(r'(?s)(?<=<body>\n).+(?=<hr>)', pagesource).group(0)
|
||||
filterbr = rawpaste.replace("<br />", "")
|
||||
unescaped = decode_html(filterbr)
|
||||
stripped = unescaped.strip()
|
||||
|
||||
return stripped
|
||||
|
||||
|
||||
def scrape_pastebin(url):
|
||||
id = re.search(r'(?:www\.)?pastebin.com/([a-zA-Z0-9]+)$', url).group(1)
|
||||
rawurl = "http://pastebin.com/raw.php?i=" + id
|
||||
text = http.get(rawurl)
|
||||
|
||||
return text
|
||||
|
||||
|
||||
autorepastes = {}
|
||||
|
||||
|
||||
#@hook.regex('(pastebin\.com)(/[^ ]+)')
|
||||
@hook.regex('(mibpaste\.com)(/[^ ]+)')
|
||||
def autorepaste(inp, input=None, db=None, chan=None):
|
||||
db_init(db)
|
||||
manual = input.db.execute("select manual from repaste where chan=?", (chan, )).fetchone()
|
||||
if manual and len(manual) and manual[0]:
|
||||
return
|
||||
url = inp.group(1) + inp.group(2)
|
||||
urllib.unquote(url)
|
||||
if url in autorepastes:
|
||||
out = autorepastes[url]
|
||||
input.notice("In the future, please use a less awful pastebin (e.g. pastebin.com)")
|
||||
else:
|
||||
out = repaste("http://" + url, input, db, False)
|
||||
autorepastes[url] = out
|
||||
input.notice("In the future, please use a less awful pastebin (e.g. pastebin.com) instead of %s." % inp.group(1))
|
||||
input.say("%s (repasted for %s)" % (out, input.nick))
|
||||
|
||||
|
||||
scrapers = {
|
||||
r'mibpaste\.com': scrape_mibpaste,
|
||||
r'pastebin\.com': scrape_pastebin
|
||||
}
|
||||
|
||||
|
||||
def scrape(url):
|
||||
for pat, scraper in scrapers.iteritems():
|
||||
print "matching " + repr(pat) + " " + url
|
||||
if re.search(pat, url):
|
||||
break
|
||||
else:
|
||||
return None
|
||||
|
||||
return scraper(url)
|
||||
|
||||
|
||||
def paste_sprunge(text, syntax=None, user=None):
|
||||
data = urllib.urlencode({"sprunge": text})
|
||||
url = urllib2.urlopen("http://sprunge.us/", data).read().strip()
|
||||
|
||||
if syntax:
|
||||
url += "?" + syntax
|
||||
|
||||
return url
|
||||
|
||||
|
||||
def paste_ubuntu(text, user=None, syntax='text'):
|
||||
data = urllib.urlencode({"poster": user,
|
||||
"syntax": syntax,
|
||||
"content": text})
|
||||
|
||||
return urllib2.urlopen("http://paste.ubuntu.com/", data).url
|
||||
|
||||
|
||||
def paste_gist(text, user=None, syntax=None, description=None):
|
||||
data = {
|
||||
'file_contents[gistfile1]': text,
|
||||
'action_button': "private"
|
||||
}
|
||||
|
||||
if description:
|
||||
data['description'] = description
|
||||
|
||||
if syntax:
|
||||
data['file_ext[gistfile1]'] = "." + syntax
|
||||
|
||||
req = urllib2.urlopen('https://gist.github.com/gists', urllib.urlencode(data).encode('utf8'))
|
||||
return req.url
|
||||
|
||||
|
||||
def paste_strictfp(text, user=None, syntax="plain"):
|
||||
data = urllib.urlencode(dict(
|
||||
language=syntax,
|
||||
paste=text,
|
||||
private="private",
|
||||
submit="Paste"))
|
||||
req = urllib2.urlopen("http://paste.strictfp.com/", data)
|
||||
return req.url
|
||||
|
||||
|
||||
pasters = dict(
|
||||
ubuntu=paste_ubuntu,
|
||||
sprunge=paste_sprunge,
|
||||
gist=paste_gist,
|
||||
strictfp=paste_strictfp
|
||||
)
|
||||
|
||||
|
||||
@hook.command
|
||||
def repaste(inp, input=None, db=None, isManual=True):
|
||||
".repaste mode|list|[provider] [syntax] <pastebinurl> -- scrape mibpaste, reupload on given pastebin"
|
||||
|
||||
parts = inp.split()
|
||||
db_init(db)
|
||||
if parts[0] == 'list':
|
||||
return " ".join(pasters.keys())
|
||||
|
||||
|
||||
paster = paste_gist
|
||||
args = {}
|
||||
|
||||
if not parts[0].startswith("http"):
|
||||
p = parts[0].lower()
|
||||
|
||||
if p in pasters:
|
||||
paster = pasters[p]
|
||||
parts = parts[1:]
|
||||
|
||||
if not parts[0].startswith("http"):
|
||||
p = parts[0].lower()
|
||||
parts = parts[1:]
|
||||
|
||||
args["syntax"] = p
|
||||
|
||||
if len(parts) > 1:
|
||||
return "PEBKAC"
|
||||
|
||||
args["user"] = input.user
|
||||
|
||||
url = parts[0]
|
||||
|
||||
scraped = scrape(url)
|
||||
|
||||
if not scraped:
|
||||
return "No scraper for given url"
|
||||
|
||||
args["text"] = scraped
|
||||
pasted = paster(**args)
|
||||
|
||||
return pasted
|
|
@ -0,0 +1,37 @@
|
|||
from util import http, hook
|
||||
|
||||
api_root = 'http://api.rottentomatoes.com/api/public/v1.0/'
|
||||
movie_search_url = api_root+'movies.json?q=%s&apikey=%s'
|
||||
movie_info_url = api_root+'movies/%s.json?apikey=%s'
|
||||
movie_reviews_url = api_root+'movies/%s/reviews.json?apikey=%s&review_type=all'
|
||||
|
||||
response = u"%s - critics: \x02%d%%\x02 (%d\u2191%d\u2193) audience: \x02%d%%\x02 - %s"
|
||||
|
||||
|
||||
@hook.command('rt')
|
||||
def rottentomatoes(inp, bot=None):
|
||||
'.rt <title> -- gets ratings for <title> from Rotten Tomatoes'
|
||||
|
||||
api_key = bot.config.get("api_keys", {}).get("rottentomatoes", None)
|
||||
if not api_key:
|
||||
return None
|
||||
|
||||
title = inp.strip()
|
||||
|
||||
results = http.get_json(movie_search_url % (http.quote_plus(title), api_key))
|
||||
if results['total'] > 0:
|
||||
movie = results['movies'][0]
|
||||
title = movie['title']
|
||||
id = movie['id']
|
||||
critics_score = movie['ratings']['critics_score']
|
||||
audience_score = movie['ratings']['audience_score']
|
||||
url = movie['links']['alternate']
|
||||
|
||||
if critics_score != -1:
|
||||
reviews = http.get_json(movie_reviews_url%(id, api_key))
|
||||
review_count = reviews['total']
|
||||
|
||||
fresh = critics_score * review_count / 100
|
||||
rotten = review_count - fresh
|
||||
|
||||
return response % (title, critics_score, fresh, rotten, audience_score, url)
|
|
@ -0,0 +1,52 @@
|
|||
" seen.py: written by sklnd in about two beers July 2009"
|
||||
|
||||
import time
|
||||
import re
|
||||
|
||||
from util import hook, timesince
|
||||
|
||||
|
||||
def db_init(db):
|
||||
"check to see that our db has the the seen table and return a connection."
|
||||
db.execute("create table if not exists seen(name, time, quote, chan, "
|
||||
"primary key(name, chan))")
|
||||
db.commit()
|
||||
|
||||
|
||||
@hook.singlethread
|
||||
@hook.event('PRIVMSG', ignorebots=False)
|
||||
def seeninput(paraml, input=None, db=None, bot=None):
|
||||
db_init(db)
|
||||
db.execute("insert or replace into seen(name, time, quote, chan)"
|
||||
"values(?,?,?,?)", (input.nick.lower(), time.time(), input.msg,
|
||||
input.chan))
|
||||
db.commit()
|
||||
|
||||
|
||||
@hook.command
|
||||
def seen(inp, nick='', chan='', db=None, input=None):
|
||||
".seen <nick> -- Tell when a nickname was last in active in irc"
|
||||
|
||||
if input.conn.nick.lower() == inp.lower():
|
||||
# user is looking for us, being a smartass
|
||||
return "You need to get your eyes checked."
|
||||
|
||||
if inp.lower() == nick.lower():
|
||||
return "Have you looked in a mirror lately?"
|
||||
|
||||
if not re.match("^[A-Za-z0-9_|.-\]\[]*$", inp.lower()):
|
||||
return "I cant look up that name, its impossible to use!"
|
||||
|
||||
db_init(db)
|
||||
|
||||
last_seen = db.execute("select name, time, quote from seen where name"
|
||||
" like ? and chan = ?", (inp, chan)).fetchone()
|
||||
|
||||
if last_seen:
|
||||
reltime = timesince.timesince(last_seen[1])
|
||||
if last_seen[0] != inp.lower(): # for glob matching
|
||||
inp = last_seen[0]
|
||||
return '%s was last seen %s ago saying: %s' % \
|
||||
(inp, reltime, last_seen[2])
|
||||
else:
|
||||
return "I've never seen %s" % inp
|
|
@ -0,0 +1,42 @@
|
|||
# # Lukeroge
|
||||
from util import hook
|
||||
|
||||
try:
|
||||
from re import match
|
||||
from urllib2 import urlopen, Request, HTTPError
|
||||
from urllib import urlencode
|
||||
from simplejson import loads
|
||||
except ImportError, e:
|
||||
raise Exception('Required module missing: %s' % e.args[0])
|
||||
|
||||
user = "o_750ro241n9"
|
||||
apikey = "R_f3d0a9b478c53d247a134d0791f898fe"
|
||||
|
||||
def expand(url):
|
||||
try:
|
||||
params = urlencode({'shortUrl': url, 'login': user, 'apiKey': apikey, 'format': 'json'})
|
||||
req = Request("http://api.bit.ly/v3/expand?%s" % params)
|
||||
response = urlopen(req)
|
||||
j = loads(response.read())
|
||||
if j['status_code'] == 200:
|
||||
return j['data']['expand'][0]['long_url']
|
||||
raise Exception('%s'%j['status_txt'])
|
||||
except HTTPError, e:
|
||||
raise('HTTP Error%s'%e.read())
|
||||
|
||||
def tiny(url):
|
||||
try:
|
||||
params = urlencode({'longUrl': url, 'login': user, 'apiKey': apikey, 'format': 'json'})
|
||||
req = Request("http://api.bit.ly/v3/shorten?%s" % params)
|
||||
response = urlopen(req)
|
||||
j = loads(response.read())
|
||||
if j['status_code'] == 200:
|
||||
return j['data']['url']
|
||||
raise Exception('%s'%j['status_txt'])
|
||||
except HTTPError, e:
|
||||
raise('HTTP error%s'%e.read())
|
||||
|
||||
@hook.command
|
||||
def shorten(inp):
|
||||
".shorten <url> - Makes an j.mp shortlink to the url provided"
|
||||
return tiny(inp)
|
|
@ -0,0 +1,42 @@
|
|||
import re
|
||||
|
||||
from util import hook
|
||||
|
||||
|
||||
@hook.sieve
|
||||
def sieve_suite(bot, input, func, kind, args):
|
||||
if input.command == 'PRIVMSG' and \
|
||||
input.nick.lower()[-3:] == 'bot' and args.get('ignorebots', True):
|
||||
return None
|
||||
|
||||
if kind == "command":
|
||||
if input.trigger in bot.config.get('disabled_commands', []):
|
||||
return None
|
||||
|
||||
ignored = bot.config.get('ignored', [])
|
||||
if input.host in ignored or input.nick in ignored:
|
||||
return None
|
||||
|
||||
fn = re.match(r'^plugins.(.+).py$', func._filename)
|
||||
disabled = bot.config.get('disabled_plugins', [])
|
||||
if fn and fn.group(1).lower() in disabled:
|
||||
return None
|
||||
|
||||
acl = bot.config.get('acls', {}).get(func.__name__)
|
||||
if acl:
|
||||
if 'deny-except' in acl:
|
||||
allowed_channels = map(unicode.lower, acl['deny-except'])
|
||||
if input.chan.lower() not in allowed_channels:
|
||||
return None
|
||||
if 'allow-except' in acl:
|
||||
denied_channels = map(unicode.lower, acl['allow-except'])
|
||||
if input.chan.lower() in denied_channels:
|
||||
return None
|
||||
|
||||
if args.get('adminonly', False):
|
||||
admins = bot.config.get('admins', [])
|
||||
|
||||
if input.host not in admins and input.nick not in admins:
|
||||
return None
|
||||
|
||||
return input
|
|
@ -0,0 +1,186 @@
|
|||
from util import hook
|
||||
import re
|
||||
import random
|
||||
|
||||
larts = ["swaps <who>'s shampoo with glue",
|
||||
"installs windows on <who>'s machine",
|
||||
"forces <who> to use perl for 3 weeks",
|
||||
"registers <who>'s name with 50 known spammers",
|
||||
"resizes <who>'s to 40x24",
|
||||
"takes <who>'s drink",
|
||||
"dispenses <who>'s email address to a few hundred 'bulk mailing services'",
|
||||
"pokes <who> in the eye",
|
||||
"beats <who> senseless with a 50lb Linux manual",
|
||||
"cats /dev/random into <who>'s ear",
|
||||
"signs <who> up for AOL",
|
||||
"enrolls <who> in Visual Basic 101",
|
||||
"sporks <who>",
|
||||
"drops a truckload of support tickets on <who>",
|
||||
"judo chops <who>",
|
||||
"sets <who>'s resolution to 800x600",
|
||||
"formats <who>'s harddrive to fat12",
|
||||
"rm -rf's <who>",
|
||||
"stabs <who>",
|
||||
"steals <who>'s mojo",
|
||||
"strangles <who> with a doohicky mouse cord",
|
||||
"whacks <who> with the cluebat",
|
||||
"sells <who> on EBay",
|
||||
"uses <who> as a biological warfare study",
|
||||
"uses the 'Customer Appreciation Bat' on <who>",
|
||||
"puts <who> in the Total Perspective Vortex",
|
||||
"casts <who> into the fires of Mt. Doom",
|
||||
"gives <who> a melvin",
|
||||
"turns over <who> to Agent Smith to be 'bugged'",
|
||||
"takes away <who>'s internet connection",
|
||||
"pushes <who> past the Shoe Event Horizon",
|
||||
"counts '1, 2, 5... er... 3!' and hurls the Holy Handgrenade Of Antioch at <who>",
|
||||
"puts <who> in a nest of camel spiders",
|
||||
"makes <who> read slashdot at -1",
|
||||
"puts 'alias vim=emacs' in <who>'s /etc/profile",
|
||||
"uninstalls every web browser from <who>'s system",
|
||||
"locks <who> in the Chateau d'If",
|
||||
"signs <who> up for getting hit on the head lessons",
|
||||
"makes <who> try to set up a Lexmark printer",
|
||||
"fills <who>'s eyedrop bottle with lime juice",
|
||||
"casts <who> into the fires of Mt. Doom.",
|
||||
"gives <who> a Flying Dutchman",
|
||||
"rips off <who>'s arm, and uses it to beat them to death",
|
||||
"pierces <who>'s nose with a rusty paper hole puncher",
|
||||
"pokes <who> with a rusty nail",
|
||||
"puts sugar between <who>'s bedsheets",
|
||||
"pours sand into <who>'s breakfast",
|
||||
"mixes epoxy into <who>'s toothpaste",
|
||||
"puts Icy-Hot in <who>'s lube container",
|
||||
"straps <who> to a chair, and plays a endless low bitrate MP3 loop of \"the world's most annoying sound\" from \"Dumb and Dumber\"",
|
||||
"tells Dr. Dre that <who> was talking smack",
|
||||
"forces <who> to use a Commodore 64 for all their word processing",
|
||||
"smacks <who> in the face with a burlap sack full of broken glass",
|
||||
"puts <who> in a room with several heavily armed manic depressives",
|
||||
"makes <who> watch reruns of \"Blue's Clues\"",
|
||||
"puts lye in <who>'s coffee",
|
||||
"tattoos the Windows symbol on <who>'s ass",
|
||||
"lets Borg have his way with <who>",
|
||||
"signs <who> up for line dancing classes at the local senior center",
|
||||
"wakes <who> out of a sound sleep with some brand new nipple piercings",
|
||||
"gives <who> a 2 guage Prince Albert",
|
||||
"forces <who> to eat all their veggies",
|
||||
"covers <who>'s toilet paper with lemon-pepper",
|
||||
"fills <who>'s ketchup bottle with Dave's Insanity sauce",
|
||||
"forces <who> to stare at an incredibly frustrating and seemingly neverending IRC political debate",
|
||||
"knocks two of <who>'s teeth out with a 2x4",
|
||||
"removes debian from <who>'s system",
|
||||
"uses <who>'s iPod for skeet shooting practice",
|
||||
"gives <who>'s phone number to Borg",
|
||||
"posts <who>'s IP, username, and password on 4chan",
|
||||
"forces <who> to use words like 'irregardless' and 'administrate' (thereby sounding like a real dumbass)",
|
||||
"tickles <who> until they wet their pants and pass out",
|
||||
"replaces <who>'s KY with elmer's clear wood glue",
|
||||
"replaces <who>'s TUMS with alka-seltzer tablets",
|
||||
"squeezes habanero pepper juice into <who>'s tub of vaseline",
|
||||
"Forces <who> to learn the Win32 API",
|
||||
"gives <who> an atomic wedgie",
|
||||
"ties <who> to a chair and forces them to listen to 'N Sync at full blast",
|
||||
"forces <who> to use notepad for text editing",
|
||||
"frowns at <who> really really hard",
|
||||
"jabs a hot lighter into <who>'s eye sockets",
|
||||
"forces <who> to browse the web with IE6",
|
||||
"takes <who> out at the knees with a broken pool cue",
|
||||
"forces <who> to listen to emo music",
|
||||
"lets a few creepers into <who>'s house",
|
||||
"signs <who> up for the Iowa State Ferret Legging Championship",
|
||||
"attempts to hotswap <who>'s RAM",
|
||||
"dragon punches <who>",
|
||||
"puts track spikes into <who>'s side",
|
||||
"replaces <who>'s Astroglide with JB Weld",
|
||||
"replaces <who>'s stress pills with rat poison pellets",
|
||||
"replaces <who>s crotch itch cream with Nair",
|
||||
"does the Australian Death Grip on <who>",
|
||||
"dances upon the grave of <who>'s ancestors.",
|
||||
"farts in <who>'s general direction",
|
||||
"flogs <who> with stinging neddle",
|
||||
"assigns all of the permissions tickets on the BeastNode support system to <who>",
|
||||
"hands <who> a poison ivy joint"]
|
||||
|
||||
loves = ["hugs <who>",
|
||||
"gives <who> some love",
|
||||
"gives <who> a cookie",
|
||||
"makes a balloon animal for <who>",
|
||||
"shares a slice of cake with <who>",
|
||||
"slaps <who> heartily on the back",
|
||||
"tickles <who>"]
|
||||
|
||||
slaps = ["slaps <who> with a <item>",
|
||||
"slaps <who> around a bit with a <item>",
|
||||
"throws a <item> at <who>",
|
||||
"grabs a <item> and throws it in <who>'s face",
|
||||
"holds <who> down and repeatedly whacks them with a <item>",
|
||||
"prods <who> with a flaming <item>",
|
||||
"picks up a <item>, and whacks <who> with it",
|
||||
"ties <who> to a chair and throws a <item> at them",
|
||||
"hits <who> on the head with a <item>"]
|
||||
|
||||
items = ["cast iron skillet",
|
||||
"large trout",
|
||||
"baseball bat",
|
||||
"wooden cane",
|
||||
"CRT monitor",
|
||||
"physics textbook",
|
||||
"television",
|
||||
"five tonne truck",
|
||||
"roll of duct tape",
|
||||
"book",
|
||||
"rubber chicken",
|
||||
"fire extinguisher",
|
||||
"heavy rock",
|
||||
"chunk of dirt"]
|
||||
|
||||
@hook.command
|
||||
def lart(inp, me = None, nick = None, input=None, notice=None):
|
||||
".lart <user> - LARTs a user of your choice"
|
||||
inp = inp.strip()
|
||||
|
||||
if not re.match("^[A-Za-z0-9_|.-\]\[]*$", inp.lower()):
|
||||
notice("Invalid username!")
|
||||
return
|
||||
|
||||
if inp == input.conn.nick.lower() or inp == "itself":
|
||||
msg = 'slaps ' + nick + ' in the face!'
|
||||
else:
|
||||
msg = re.sub ('<who>', inp, random.choice(larts))
|
||||
|
||||
me(msg)
|
||||
|
||||
@hook.command
|
||||
def love(inp, me = None, input=None, notice=None):
|
||||
".love <user> - gives a user a nice comment"
|
||||
inp = inp.strip()
|
||||
|
||||
if not re.match("^[A-Za-z0-9_|.-\]\[]*$", inp.lower()):
|
||||
notice("Invalid username!")
|
||||
return
|
||||
|
||||
if inp == input.conn.nick.lower() or inp == "itself":
|
||||
msg = 'hugs themself!'
|
||||
else:
|
||||
msg = re.sub ('<who>', inp, random.choice(loves))
|
||||
|
||||
me(msg)
|
||||
|
||||
@hook.command
|
||||
def slap(inp, me = None, nick = None, input=None, notice=None):
|
||||
".slap <user> - slap a user"
|
||||
inp = inp.strip()
|
||||
|
||||
if not re.match("^[A-Za-z0-9_|.-\]\[]*$", inp.lower()):
|
||||
notice("Invalid username!")
|
||||
return
|
||||
|
||||
if inp == input.conn.nick.lower() or inp == "itself":
|
||||
msg = 'slaps ' + nick + ' in the face!'
|
||||
else:
|
||||
slap = random.choice(slaps)
|
||||
slap = re.sub ('<who>', inp, slap)
|
||||
msg = re.sub ('<item>', random.choice(items), slap)
|
||||
|
||||
me(msg)
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
import re
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
search_url = "http://search.atomz.com/search/?sp_a=00062d45-sp00000000"
|
||||
|
||||
|
||||
@hook.command
|
||||
def snopes(inp):
|
||||
".snopes <topic> -- searches snopes for an urban legend about <topic>"
|
||||
|
||||
search_page = http.get_html(search_url, sp_q=inp, sp_c="1")
|
||||
result_urls = search_page.xpath("//a[@target='_self']/@href")
|
||||
|
||||
if not result_urls:
|
||||
return "no matching pages found"
|
||||
|
||||
snopes_page = http.get_html(result_urls[0])
|
||||
snopes_text = snopes_page.text_content()
|
||||
|
||||
claim = re.search(r"Claim: .*", snopes_text).group(0).strip()
|
||||
status = re.search(r"Status: .*", snopes_text)
|
||||
|
||||
if status is not None:
|
||||
status = status.group(0).strip()
|
||||
else: # new-style statuses
|
||||
status = "Status: %s." % re.search(r"FALSE|TRUE|MIXTURE|UNDETERMINED",
|
||||
snopes_text).group(0).title()
|
||||
|
||||
claim = re.sub(r"[\s\xa0]+", " ", claim) # compress whitespace
|
||||
status = re.sub(r"[\s\xa0]+", " ", status)
|
||||
|
||||
return "%s %s %s" % (claim, status, result_urls[0])
|
|
@ -0,0 +1,37 @@
|
|||
import random
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
@hook.command
|
||||
def stock(inp):
|
||||
'''.stock <symbol> -- gets information about a stock symbol'''
|
||||
|
||||
url = 'http://www.google.com/ig/api?stock=%s'
|
||||
|
||||
parsed = http.get_xml(url, stock=inp)
|
||||
|
||||
if len(parsed) != 1:
|
||||
return "error getting stock info"
|
||||
|
||||
# Stuff the results in a dict for easy string formatting
|
||||
results = dict((el.tag, el.attrib['data'])
|
||||
for el in parsed.xpath('//finance/*'))
|
||||
|
||||
# if we dont get a company name back, the symbol doesn't match a company
|
||||
if results['company'] == '':
|
||||
return "unknown ticker symbol %s" % inp
|
||||
|
||||
if results['change'][0] == '-':
|
||||
results['color'] = "5"
|
||||
else:
|
||||
results['color'] = "3"
|
||||
|
||||
ret = "%(company)s - %(last)s %(currency)s " \
|
||||
"\x03%(color)s%(change)s (%(perc_change)s)\x03 " \
|
||||
"as of %(trade_timestamp)s" % results
|
||||
|
||||
if results['delay'] != '0':
|
||||
ret += " (delayed %s minutes)" % results['delay']
|
||||
|
||||
return ret
|
|
@ -0,0 +1,33 @@
|
|||
import json
|
||||
import random
|
||||
import re
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
@hook.command
|
||||
def suggest(inp, inp_unstripped=''):
|
||||
".suggest [#n] <phrase> -- gets a random/the nth suggested google search"
|
||||
|
||||
inp = inp_unstripped
|
||||
m = re.match('^#(\d+) (.+)$', inp)
|
||||
if m:
|
||||
num, inp = m.groups()
|
||||
num = int(num)
|
||||
if num > 10:
|
||||
return 'can only get first ten suggestions'
|
||||
else:
|
||||
num = 0
|
||||
|
||||
page = http.get('http://google.com/complete/search', q=inp)
|
||||
page_json = page.split('(', 1)[1][:-1]
|
||||
suggestions = json.loads(page_json)[1]
|
||||
if not suggestions:
|
||||
return 'no suggestions found'
|
||||
if num:
|
||||
if len(suggestions) + 1 <= num:
|
||||
return 'only got %d suggestions' % len(suggestions)
|
||||
out = suggestions[num - 1]
|
||||
else:
|
||||
out = random.choice(suggestions)
|
||||
return '#%d: %s' % (int(out[2][0]) + 1, out[0])
|
|
@ -0,0 +1,118 @@
|
|||
" tell.py: written by sklnd in July 2009"
|
||||
" 2010.01.25 - modified by Scaevolus"
|
||||
|
||||
import time
|
||||
import re
|
||||
|
||||
from util import hook, timesince
|
||||
|
||||
|
||||
def db_init(db):
|
||||
"check to see that our db has the tell table and return a dbection."
|
||||
db.execute("create table if not exists tell"
|
||||
"(user_to, user_from, message, chan, time,"
|
||||
"primary key(user_to, message))")
|
||||
db.commit()
|
||||
|
||||
return db
|
||||
|
||||
|
||||
def get_tells(db, user_to):
|
||||
return db.execute("select user_from, message, time, chan from tell where"
|
||||
" user_to=lower(?) order by time",
|
||||
(user_to.lower(),)).fetchall()
|
||||
|
||||
|
||||
@hook.singlethread
|
||||
@hook.event('PRIVMSG')
|
||||
def tellinput(paraml, input=None, db=None, bot=None):
|
||||
if 'showtells' in input.msg.lower():
|
||||
return
|
||||
|
||||
db_init(db)
|
||||
|
||||
tells = get_tells(db, input.nick)
|
||||
|
||||
if tells:
|
||||
user_from, message, time, chan = tells[0]
|
||||
reltime = timesince.timesince(time)
|
||||
|
||||
reply = "%s said %s ago in %s: %s" % (user_from, reltime, chan,
|
||||
message)
|
||||
if len(tells) > 1:
|
||||
reply += " (+%d more, .showtells to view)" % (len(tells) - 1)
|
||||
|
||||
db.execute("delete from tell where user_to=lower(?) and message=?",
|
||||
(input.nick, message))
|
||||
db.commit()
|
||||
input.notice(reply)
|
||||
|
||||
|
||||
@hook.command(autohelp=False)
|
||||
def showtells(inp, nick='', chan='', notice=None, db=None):
|
||||
".showtells -- view all pending tell messages (sent in PM)."
|
||||
|
||||
db_init(db)
|
||||
|
||||
tells = get_tells(db, nick)
|
||||
|
||||
if not tells:
|
||||
notice("You have no pending tells.")
|
||||
return
|
||||
|
||||
for tell in tells:
|
||||
user_from, message, time, chan = tell
|
||||
past = timesince.timesince(time)
|
||||
notice("%s said %s ago in %s: %s" % (user_from, past, chan, message))
|
||||
|
||||
db.execute("delete from tell where user_to=lower(?)",
|
||||
(nick,))
|
||||
db.commit()
|
||||
|
||||
|
||||
@hook.command
|
||||
def tell(inp, nick='', chan='', db=None, input=None, notice=None):
|
||||
".tell <nick> <message> -- relay <message> to <nick> when <nick> is around"
|
||||
|
||||
query = inp.split(' ', 1)
|
||||
|
||||
if len(query) != 2:
|
||||
return tell.__doc__
|
||||
|
||||
user_to = query[0].lower()
|
||||
message = query[1].strip()
|
||||
user_from = nick
|
||||
|
||||
if chan.lower() == user_from.lower():
|
||||
chan = 'a pm'
|
||||
|
||||
if user_to == user_from.lower():
|
||||
notice("No.")
|
||||
return
|
||||
|
||||
if user_to.lower() == "mau5bot":
|
||||
# user is looking for us, being a smartass
|
||||
notice("Thanks for the message, " + user_from + "!")
|
||||
return
|
||||
|
||||
if not re.match("^[A-Za-z0-9_|.-\]\[]*$", user_to.lower()):
|
||||
notice("I cant send a message to that user!")
|
||||
return
|
||||
|
||||
db_init(db)
|
||||
|
||||
if db.execute("select count() from tell where user_to=?",
|
||||
(user_to,)).fetchone()[0] >= 10:
|
||||
notice("That person has too many things queued.")
|
||||
return
|
||||
|
||||
try:
|
||||
db.execute("insert into tell(user_to, user_from, message, chan,"
|
||||
"time) values(?,?,?,?,?)", (user_to, user_from, message,
|
||||
chan, time.time()))
|
||||
db.commit()
|
||||
except db.IntegrityError:
|
||||
notice("Message has already been queued.")
|
||||
return
|
||||
|
||||
notice("I'll pass that along.")
|
|
@ -0,0 +1,186 @@
|
|||
from util import hook
|
||||
import re
|
||||
|
||||
db_inited = False
|
||||
|
||||
|
||||
def cleanSQL(sql):
|
||||
return re.sub(r'\s+', " ", sql).strip()
|
||||
|
||||
|
||||
def db_init(db):
|
||||
global db_inited
|
||||
if db_inited:
|
||||
return
|
||||
|
||||
exists = db.execute("""
|
||||
select exists (
|
||||
select * from sqlite_master where type = "table" and name = "todos"
|
||||
)
|
||||
""").fetchone()[0] == 1
|
||||
|
||||
if not exists:
|
||||
db.execute(cleanSQL("""
|
||||
create virtual table todos using fts4(
|
||||
user,
|
||||
text,
|
||||
added,
|
||||
tokenize=porter
|
||||
)"""))
|
||||
|
||||
db.commit()
|
||||
|
||||
db_inited = True
|
||||
|
||||
|
||||
def db_getall(db, nick, limit=-1):
|
||||
return db.execute("""
|
||||
select added, text
|
||||
from todos
|
||||
where lower(user) = lower(?)
|
||||
order by added desc
|
||||
limit ?
|
||||
|
||||
""", (nick, limit))
|
||||
|
||||
|
||||
def db_get(db, nick, id):
|
||||
return db.execute("""
|
||||
select added, text from todos
|
||||
where lower(user) = lower(?)
|
||||
order by added desc
|
||||
limit 1
|
||||
offset ?
|
||||
""", (nick, id)).fetchone()
|
||||
|
||||
|
||||
def db_del(db, nick, limit='all'):
|
||||
row = db.execute("""
|
||||
delete from todos
|
||||
where rowid in (
|
||||
select rowid from todos
|
||||
where lower(user) = lower(?)
|
||||
order by added desc
|
||||
limit ?
|
||||
offset ?)
|
||||
""", (nick,
|
||||
-1 if limit == 'all' else 1,
|
||||
0 if limit == 'all' else limit))
|
||||
db.commit()
|
||||
return row
|
||||
|
||||
|
||||
def db_add(db, nick, text):
|
||||
db.execute("""
|
||||
insert into todos (user, text, added)
|
||||
values (?, ?, CURRENT_TIMESTAMP)
|
||||
""", (nick, text))
|
||||
db.commit()
|
||||
|
||||
|
||||
def db_search(db, nick, query):
|
||||
return db.execute("""
|
||||
select added, text
|
||||
from todos
|
||||
where todos match ?
|
||||
and lower(user) = lower(?)
|
||||
order by added desc
|
||||
""", (query, nick))
|
||||
|
||||
|
||||
@hook.command
|
||||
def todo(inp, nick='', chan='', db=None, notice=None, bot=None):
|
||||
"todo (add|del|list|search) [@user] args -- manipulates your todos"
|
||||
|
||||
db_init(db)
|
||||
|
||||
parts = inp.split()
|
||||
cmd = parts[0].lower()
|
||||
|
||||
args = parts[1:]
|
||||
|
||||
if len(args) and args[0].startswith("@"):
|
||||
nick = args[0][1:]
|
||||
args = args[1:]
|
||||
|
||||
if cmd == 'add':
|
||||
if not len(args):
|
||||
return "no text"
|
||||
|
||||
text = " ".join(args)
|
||||
|
||||
db_add(db, nick, text)
|
||||
|
||||
notice("Task added!")
|
||||
return
|
||||
elif cmd == 'get':
|
||||
if len(args):
|
||||
try:
|
||||
index = int(args[0])
|
||||
except ValueError:
|
||||
notice("Invalid number format.")
|
||||
return
|
||||
else:
|
||||
index = 0
|
||||
|
||||
row = db_get(db, nick, index)
|
||||
|
||||
if not row:
|
||||
notice("No such entry.")
|
||||
return
|
||||
notice("[%d]: %s: %s" % (index, row[0], row[1]))
|
||||
elif cmd == 'del' or cmd == 'delete' or cmd == 'remove':
|
||||
if not len(args):
|
||||
return "error"
|
||||
|
||||
if args[0] == 'all':
|
||||
index = 'all'
|
||||
else:
|
||||
try:
|
||||
index = int(args[0])
|
||||
except ValueError:
|
||||
notice("Invalid number.")
|
||||
return
|
||||
|
||||
rows = db_del(db, nick, index)
|
||||
|
||||
notice("Deleted %d entries" % rows.rowcount)
|
||||
elif cmd == 'list':
|
||||
limit = -1
|
||||
|
||||
if len(args):
|
||||
try:
|
||||
limit = int(args[0])
|
||||
limit = max(-1, limit)
|
||||
except ValueError:
|
||||
notice("Invalid number.")
|
||||
return
|
||||
|
||||
rows = db_getall(db, nick, limit)
|
||||
|
||||
found = False
|
||||
|
||||
for (index, row) in enumerate(rows):
|
||||
notice("[%d]: %s: %s" % (index, row[0], row[1]))
|
||||
found = True
|
||||
|
||||
if not found:
|
||||
notice("%s has no entries." % nick)
|
||||
elif cmd == 'search':
|
||||
if not len(args):
|
||||
notice("No search query given!")
|
||||
return
|
||||
query = " ".join(args)
|
||||
rows = db_search(db, nick, query)
|
||||
|
||||
found = False
|
||||
|
||||
for (index, row) in enumerate(rows):
|
||||
notice("[%d]: %s: %s" % (index, row[0], row[1]))
|
||||
found = True
|
||||
|
||||
if not found:
|
||||
notice("%s has no matching entries for: %s" % (nick, query))
|
||||
|
||||
else:
|
||||
notice("Unknown command: %s" % cmd)
|
|
@ -0,0 +1,188 @@
|
|||
import htmlentitydefs
|
||||
import re
|
||||
|
||||
from util import hook, http
|
||||
|
||||
########### from http://effbot.org/zone/re-sub.htm#unescape-html #############
|
||||
|
||||
|
||||
def unescape(text):
|
||||
def fixup(m):
|
||||
text = m.group(0)
|
||||
if text[:2] == "&#":
|
||||
# character reference
|
||||
try:
|
||||
if text[:3] == "&#x":
|
||||
return unichr(int(text[3:-1], 16))
|
||||
else:
|
||||
return unichr(int(text[2:-1]))
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
# named entity
|
||||
try:
|
||||
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
|
||||
except KeyError:
|
||||
pass
|
||||
return text # leave as is
|
||||
|
||||
return re.sub("&#?\w+;", fixup, text)
|
||||
|
||||
##############################################################################
|
||||
|
||||
|
||||
def goog_trans(text, slang, tlang):
|
||||
url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&key=ABQIAAAAGjLiqTxkFw7F24ITXc4bNRS04yDz5pgaUTdxja2Sk3UoWlae7xTXom3fBzER6Upo8jfzcTtvz-8ebQ'
|
||||
parsed = http.get_json(url, q=text, langpair=(slang + '|' + tlang))
|
||||
if not 200 <= parsed['responseStatus'] < 300:
|
||||
raise IOError('error with the translation server: %d: %s' % (
|
||||
parsed['responseStatus'], parsed['responseDetails']))
|
||||
if not slang:
|
||||
return unescape('(%(detectedSourceLanguage)s) %(translatedText)s' %
|
||||
(parsed['responseData']))
|
||||
return unescape(parsed['responseData']['translatedText'])
|
||||
|
||||
|
||||
def match_language(fragment):
|
||||
fragment = fragment.lower()
|
||||
for short, _ in lang_pairs:
|
||||
if fragment in short.lower().split():
|
||||
return short.split()[0]
|
||||
|
||||
for short, full in lang_pairs:
|
||||
if fragment in full.lower():
|
||||
return short.split()[0]
|
||||
|
||||
return None
|
||||
|
||||
|
||||
@hook.command
|
||||
def translate(inp):
|
||||
'.translate [source language [target language]] <sentence> -- translates' \
|
||||
' <sentence> from source language (default autodetect) to target' \
|
||||
' language (default English) using Google Translate'
|
||||
|
||||
args = inp.split(' ', 2)
|
||||
|
||||
try:
|
||||
if len(args) >= 2:
|
||||
sl = match_language(args[0])
|
||||
if not sl:
|
||||
return goog_trans(inp, '', 'en')
|
||||
if len(args) >= 3:
|
||||
tl = match_language(args[1])
|
||||
if not tl:
|
||||
if sl == 'en':
|
||||
return 'unable to determine desired target language'
|
||||
return goog_trans(args[1] + ' ' + args[2], sl, 'en')
|
||||
return goog_trans(args[2], sl, tl)
|
||||
return goog_trans(inp, '', 'en')
|
||||
except IOError, e:
|
||||
return e
|
||||
|
||||
|
||||
languages = 'ja fr de ko ru zh'.split()
|
||||
language_pairs = zip(languages[:-1], languages[1:])
|
||||
|
||||
|
||||
def babel_gen(inp):
|
||||
for language in languages:
|
||||
inp = inp.encode('utf8')
|
||||
trans = goog_trans(inp, 'en', language).encode('utf8')
|
||||
inp = goog_trans(trans, language, 'en')
|
||||
yield language, trans, inp
|
||||
|
||||
|
||||
@hook.command
|
||||
def babel(inp):
|
||||
".babel <sentence> -- translates <sentence> through multiple languages"
|
||||
|
||||
try:
|
||||
return list(babel_gen(inp))[-1][2]
|
||||
except IOError, e:
|
||||
return e
|
||||
|
||||
|
||||
@hook.command
|
||||
def babelext(inp):
|
||||
".babelext <sentence> -- like .babel, but with more detailed output"
|
||||
|
||||
try:
|
||||
babels = list(babel_gen(inp))
|
||||
except IOError, e:
|
||||
return e
|
||||
|
||||
out = u''
|
||||
for lang, trans, text in babels:
|
||||
out += '%s:"%s", ' % (lang, text.decode('utf8'))
|
||||
|
||||
out += 'en:"' + babels[-1][2].decode('utf8') + '"'
|
||||
|
||||
if len(out) > 300:
|
||||
out = out[:150] + ' ... ' + out[-150:]
|
||||
|
||||
return out
|
||||
|
||||
|
||||
lang_pairs = [
|
||||
("no", "Norwegian"),
|
||||
("it", "Italian"),
|
||||
("ht", "Haitian Creole"),
|
||||
("af", "Afrikaans"),
|
||||
("sq", "Albanian"),
|
||||
("ar", "Arabic"),
|
||||
("hy", "Armenian"),
|
||||
("az", "Azerbaijani"),
|
||||
("eu", "Basque"),
|
||||
("be", "Belarusian"),
|
||||
("bg", "Bulgarian"),
|
||||
("ca", "Catalan"),
|
||||
("zh-CN zh", "Chinese"),
|
||||
("hr", "Croatian"),
|
||||
("cs", "Czech"),
|
||||
("da", "Danish"),
|
||||
("nl", "Dutch"),
|
||||
("en", "English"),
|
||||
("et", "Estonian"),
|
||||
("tl", "Filipino"),
|
||||
("fi", "Finnish"),
|
||||
("fr", "French"),
|
||||
("gl", "Galician"),
|
||||
("ka", "Georgian"),
|
||||
("de", "German"),
|
||||
("el", "Greek"),
|
||||
("ht", "Haitian Creole"),
|
||||
("iw", "Hebrew"),
|
||||
("hi", "Hindi"),
|
||||
("hu", "Hungarian"),
|
||||
("is", "Icelandic"),
|
||||
("id", "Indonesian"),
|
||||
("ga", "Irish"),
|
||||
("it", "Italian"),
|
||||
("ja jp jpn", "Japanese"),
|
||||
("ko", "Korean"),
|
||||
("lv", "Latvian"),
|
||||
("lt", "Lithuanian"),
|
||||
("mk", "Macedonian"),
|
||||
("ms", "Malay"),
|
||||
("mt", "Maltese"),
|
||||
("no", "Norwegian"),
|
||||
("fa", "Persian"),
|
||||
("pl", "Polish"),
|
||||
("pt", "Portuguese"),
|
||||
("ro", "Romanian"),
|
||||
("ru", "Russian"),
|
||||
("sr", "Serbian"),
|
||||
("sk", "Slovak"),
|
||||
("sl", "Slovenian"),
|
||||
("es", "Spanish"),
|
||||
("sw", "Swahili"),
|
||||
("sv", "Swedish"),
|
||||
("th", "Thai"),
|
||||
("tr", "Turkish"),
|
||||
("uk", "Ukrainian"),
|
||||
("ur", "Urdu"),
|
||||
("vi", "Vietnamese"),
|
||||
("cy", "Welsh"),
|
||||
("yi", "Yiddish")
|
||||
]
|
|
@ -0,0 +1,165 @@
|
|||
"""
|
||||
TV information, written by Lurchington 2010
|
||||
modified by rmmh 2010
|
||||
"""
|
||||
|
||||
import datetime
|
||||
from urllib2 import URLError
|
||||
from zipfile import ZipFile
|
||||
from cStringIO import StringIO
|
||||
|
||||
from lxml import etree
|
||||
from util import hook, http
|
||||
|
||||
|
||||
base_url = "http://thetvdb.com/api/"
|
||||
api_key = "469B73127CA0C411"
|
||||
|
||||
|
||||
def get_zipped_xml(*args, **kwargs):
|
||||
try:
|
||||
path = kwargs.pop("path")
|
||||
except KeyError:
|
||||
raise KeyError("must specify a path for the zipped file to be read")
|
||||
zip_buffer = StringIO(http.get(*args, **kwargs))
|
||||
return etree.parse(ZipFile(zip_buffer, "r").open(path))
|
||||
|
||||
|
||||
def get_episodes_for_series(seriesname):
|
||||
res = {"error": None, "ended": False, "episodes": None, "name": None}
|
||||
# http://thetvdb.com/wiki/index.php/API:GetSeries
|
||||
try:
|
||||
query = http.get_xml(base_url + 'GetSeries.php', seriesname=seriesname)
|
||||
except URLError:
|
||||
res["error"] = "error contacting thetvdb.com"
|
||||
return res
|
||||
|
||||
series_id = query.xpath('//seriesid/text()')
|
||||
|
||||
if not series_id:
|
||||
res["error"] = "unknown tv series (using www.thetvdb.com)"
|
||||
return res
|
||||
|
||||
series_id = series_id[0]
|
||||
|
||||
try:
|
||||
series = get_zipped_xml(base_url + '%s/series/%s/all/en.zip' %
|
||||
(api_key, series_id), path="en.xml")
|
||||
except URLError:
|
||||
res["error"] = "error contacting thetvdb.com"
|
||||
return res
|
||||
|
||||
series_name = series.xpath('//SeriesName/text()')[0]
|
||||
|
||||
if series.xpath('//Status/text()')[0] == 'Ended':
|
||||
res["ended"] = True
|
||||
|
||||
res["episodes"] = series.xpath('//Episode')
|
||||
res["name"] = series_name
|
||||
return res
|
||||
|
||||
|
||||
def get_episode_info(episode):
|
||||
first_aired = episode.findtext("FirstAired")
|
||||
|
||||
try:
|
||||
airdate = datetime.date(*map(int, first_aired.split('-')))
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
episode_num = "S%02dE%02d" % (int(episode.findtext("SeasonNumber")),
|
||||
int(episode.findtext("EpisodeNumber")))
|
||||
|
||||
episode_name = episode.findtext("EpisodeName")
|
||||
# in the event of an unannounced episode title, users either leave the
|
||||
# field out (None) or fill it with TBA
|
||||
if episode_name == "TBA":
|
||||
episode_name = None
|
||||
|
||||
episode_desc = '%s' % episode_num
|
||||
if episode_name:
|
||||
episode_desc += ' - %s' % episode_name
|
||||
return (first_aired, airdate, episode_desc)
|
||||
|
||||
|
||||
@hook.command
|
||||
@hook.command('tv')
|
||||
def tv_next(inp):
|
||||
".tv_next <series> -- get the next episode of <series>"
|
||||
episodes = get_episodes_for_series(inp)
|
||||
|
||||
if episodes["error"]:
|
||||
return episodes["error"]
|
||||
|
||||
series_name = episodes["name"]
|
||||
ended = episodes["ended"]
|
||||
episodes = episodes["episodes"]
|
||||
|
||||
if ended:
|
||||
return "%s has ended." % series_name
|
||||
|
||||
next_eps = []
|
||||
today = datetime.date.today()
|
||||
|
||||
for episode in reversed(episodes):
|
||||
ep_info = get_episode_info(episode)
|
||||
|
||||
if ep_info is None:
|
||||
continue
|
||||
|
||||
(first_aired, airdate, episode_desc) = ep_info
|
||||
|
||||
if airdate > today:
|
||||
next_eps = ['%s (%s)' % (first_aired, episode_desc)]
|
||||
elif airdate == today:
|
||||
next_eps = ['Today (%s)' % episode_desc] + next_eps
|
||||
else:
|
||||
#we're iterating in reverse order with newest episodes last
|
||||
#so, as soon as we're past today, break out of loop
|
||||
break
|
||||
|
||||
if not next_eps:
|
||||
return "there are no new episodes scheduled for %s" % series_name
|
||||
|
||||
if len(next_eps) == 1:
|
||||
return "the next episode of %s airs %s" % (series_name, next_eps[0])
|
||||
else:
|
||||
next_eps = ', '.join(next_eps)
|
||||
return "the next episodes of %s: %s" % (series_name, next_eps)
|
||||
|
||||
|
||||
@hook.command
|
||||
@hook.command('tv_prev')
|
||||
def tv_last(inp):
|
||||
".tv_last <series> -- gets the most recently aired episode of <series>"
|
||||
episodes = get_episodes_for_series(inp)
|
||||
|
||||
if episodes["error"]:
|
||||
return episodes["error"]
|
||||
|
||||
series_name = episodes["name"]
|
||||
ended = episodes["ended"]
|
||||
episodes = episodes["episodes"]
|
||||
|
||||
prev_ep = None
|
||||
today = datetime.date.today()
|
||||
|
||||
for episode in reversed(episodes):
|
||||
ep_info = get_episode_info(episode)
|
||||
|
||||
if ep_info is None:
|
||||
continue
|
||||
|
||||
(first_aired, airdate, episode_desc) = ep_info
|
||||
|
||||
if airdate < today:
|
||||
#iterating in reverse order, so the first episode encountered
|
||||
#before today was the most recently aired
|
||||
prev_ep = '%s (%s)' % (first_aired, episode_desc)
|
||||
break
|
||||
|
||||
if not prev_ep:
|
||||
return "there are no previously aired episodes for %s" % series_name
|
||||
if ended:
|
||||
return '%s ended. The last episode aired %s' % (series_name, prev_ep)
|
||||
return "the last episode of %s aired %s" % (series_name, prev_ep)
|
|
@ -0,0 +1,134 @@
|
|||
"""
|
||||
twitter.py: written by Scaevolus 2009
|
||||
retrieves most recent tweets
|
||||
"""
|
||||
|
||||
import random
|
||||
import re
|
||||
from time import strptime, strftime
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
def unescape_xml(string):
|
||||
# unescape the 5 chars that might be escaped in xml
|
||||
|
||||
# gratuitously functional
|
||||
# return reduce(lambda x, y: x.replace(*y), (string,
|
||||
# zip('> < ' "e; &'.split(), '> < \' " &'.split()))
|
||||
|
||||
# boring, normal
|
||||
return string.replace('>', '>').replace('<', '<').replace(''',
|
||||
"'").replace('"e;', '"').replace('&', '&')
|
||||
|
||||
history = []
|
||||
history_max_size = 250
|
||||
|
||||
|
||||
@hook.command
|
||||
def twitter(inp):
|
||||
".twitter <user>/<user> <n>/<id>/#<hashtag>/@<user> -- gets last/<n>th "\
|
||||
"tweet from <user>/gets tweet <id>/gets random tweet with #<hashtag>/"\
|
||||
"gets replied tweet from @<user>"
|
||||
|
||||
def add_reply(reply_name, reply_id):
|
||||
if len(history) == history_max_size:
|
||||
history.pop()
|
||||
history.insert(0, (reply_name, reply_id))
|
||||
|
||||
def find_reply(reply_name):
|
||||
for name, id in history:
|
||||
if name == reply_name:
|
||||
return id if id != -1 else name
|
||||
|
||||
if inp[0] == '@':
|
||||
reply_inp = find_reply(inp[1:])
|
||||
if reply_inp == None:
|
||||
return 'error: no replies to %s found' % inp
|
||||
inp = reply_inp
|
||||
|
||||
url = 'http://twitter.com'
|
||||
getting_nth = False
|
||||
getting_id = False
|
||||
searching_hashtag = False
|
||||
|
||||
time = 'status/created_at'
|
||||
text = 'status/text'
|
||||
reply_name = 'status/in_reply_to_screen_name'
|
||||
reply_id = 'status/in_reply_to_status_id'
|
||||
reply_user = 'status/in_reply_to_user_id'
|
||||
|
||||
if re.match(r'^\d+$', inp):
|
||||
getting_id = True
|
||||
url += '/statuses/show/%s.xml' % inp
|
||||
screen_name = 'user/screen_name'
|
||||
time = 'created_at'
|
||||
text = 'text'
|
||||
reply_name = 'in_reply_to_screen_name'
|
||||
reply_id = 'in_reply_to_status_id'
|
||||
reply_user = 'in_reply_to_user_id'
|
||||
elif re.match(r'^\w{1,15}$', inp):
|
||||
url += '/users/show/%s.xml' % inp
|
||||
screen_name = 'screen_name'
|
||||
elif re.match(r'^\w{1,15}\s+\d+$', inp):
|
||||
getting_nth = True
|
||||
name, num = inp.split()
|
||||
if int(num) > 3200:
|
||||
return 'error: only supports up to the 3200th tweet'
|
||||
url += '/statuses/user_timeline/%s.xml?count=1&page=%s' % (name, num)
|
||||
screen_name = 'status/user/screen_name'
|
||||
elif re.match(r'^#\w+$', inp):
|
||||
url = 'http://search.twitter.com/search.atom?q=%23' + inp[1:]
|
||||
searching_hashtag = True
|
||||
else:
|
||||
return 'error: invalid request'
|
||||
|
||||
try:
|
||||
tweet = http.get_xml(url)
|
||||
except http.HTTPError, e:
|
||||
errors = {400: 'bad request (ratelimited?)',
|
||||
401: 'tweet is private',
|
||||
403: 'tweet is private',
|
||||
404: 'invalid user/id',
|
||||
500: 'twitter is broken',
|
||||
502: 'twitter is down ("getting upgraded")',
|
||||
503: 'twitter is overloaded (lol, RoR)'}
|
||||
if e.code == 404:
|
||||
return 'error: invalid ' + ['username', 'tweet id'][getting_id]
|
||||
if e.code in errors:
|
||||
return 'error: ' + errors[e.code]
|
||||
return 'error: unknown %s' % e.code
|
||||
except http.URLerror, e:
|
||||
return 'error: timeout'
|
||||
|
||||
if searching_hashtag:
|
||||
ns = '{http://www.w3.org/2005/Atom}'
|
||||
tweets = tweet.findall(ns + 'entry/' + ns + 'id')
|
||||
if not tweets:
|
||||
return 'error: hashtag not found'
|
||||
id = random.choice(tweets).text
|
||||
id = id[id.rfind(':') + 1:]
|
||||
return twitter(id)
|
||||
|
||||
if getting_nth:
|
||||
if tweet.find('status') is None:
|
||||
return 'error: user does not have that many tweets'
|
||||
|
||||
time = tweet.find(time)
|
||||
if time is None:
|
||||
return 'error: user has no tweets'
|
||||
|
||||
reply_name = tweet.find(reply_name).text
|
||||
reply_id = tweet.find(reply_id).text
|
||||
reply_user = tweet.find(reply_user).text
|
||||
if reply_name is not None and (reply_id is not None or
|
||||
reply_user is not None):
|
||||
add_reply(reply_name, reply_id or -1)
|
||||
|
||||
time = strftime('%Y-%m-%d %H:%M:%S',
|
||||
strptime(time.text,
|
||||
'%a %b %d %H:%M:%S +0000 %Y'))
|
||||
text = unescape_xml(tweet.find(text).text.replace('\n', ''))
|
||||
screen_name = tweet.find(screen_name).text
|
||||
|
||||
return "%s %s: %s" % (time, screen_name, text)
|
|
@ -0,0 +1,80 @@
|
|||
import math
|
||||
import re
|
||||
import time
|
||||
|
||||
from util import hook, urlnorm, timesince
|
||||
|
||||
|
||||
expiration_period = 60 * 60 * 24 # 1 day
|
||||
|
||||
ignored_urls = [urlnorm.normalize("http://google.com"),]
|
||||
|
||||
|
||||
def db_init(db):
|
||||
db.execute("create table if not exists urlhistory"
|
||||
"(chan, url, nick, time)")
|
||||
db.commit()
|
||||
|
||||
|
||||
def insert_history(db, chan, url, nick):
|
||||
now = time.time()
|
||||
db.execute("insert into urlhistory(chan, url, nick, time) "
|
||||
"values(?,?,?,?)", (chan, url, nick, time.time()))
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_history(db, chan, url):
|
||||
db.execute("delete from urlhistory where time < ?",
|
||||
(time.time() - expiration_period,))
|
||||
return db.execute("select nick, time from urlhistory where "
|
||||
"chan=? and url=? order by time desc", (chan, url)).fetchall()
|
||||
|
||||
|
||||
def nicklist(nicks):
|
||||
nicks = sorted(dict(nicks), key=unicode.lower)
|
||||
if len(nicks) <= 2:
|
||||
return ' and '.join(nicks)
|
||||
else:
|
||||
return ', and '.join((', '.join(nicks[:-1]), nicks[-1]))
|
||||
|
||||
|
||||
def format_reply(history):
|
||||
if not history:
|
||||
return
|
||||
|
||||
last_nick, recent_time = history[0]
|
||||
last_time = timesince.timesince(recent_time)
|
||||
|
||||
if len(history) == 1:
|
||||
return #"%s linked that %s ago." % (last_nick, last_time)
|
||||
|
||||
hour_span = math.ceil((time.time() - history[-1][1]) / 3600)
|
||||
hour_span = '%.0f hours' % hour_span if hour_span > 1 else 'hour'
|
||||
|
||||
hlen = len(history)
|
||||
ordinal = ["once", "twice", "%d times" % hlen][min(hlen, 3) - 1]
|
||||
|
||||
if len(dict(history)) == 1:
|
||||
last = "last linked %s ago" % last_time
|
||||
else:
|
||||
last = "last linked by %s %s ago" % (last_nick, last_time)
|
||||
|
||||
return #"that url has been posted %s in the past %s by %s (%s)." % (ordinal,
|
||||
|
||||
@hook.regex(r'([a-zA-Z]+://|www\.)[^ ]+')
|
||||
def urlinput(match, nick='', chan='', db=None, bot=None):
|
||||
db_init(db)
|
||||
url = urlnorm.normalize(match.group().encode('utf-8'))
|
||||
if url not in ignored_urls:
|
||||
url = url.decode('utf-8')
|
||||
history = get_history(db, chan, url)
|
||||
insert_history(db, chan, url, nick)
|
||||
|
||||
inp = match.string.lower()
|
||||
|
||||
for name in dict(history):
|
||||
if name.lower() in inp: # person was probably quoting a line
|
||||
return # that had a link. don't remind them.
|
||||
|
||||
if nick not in dict(history):
|
||||
return format_reply(history)
|
|
@ -0,0 +1,31 @@
|
|||
from util import hook, http, urlnorm
|
||||
import urllib
|
||||
import re
|
||||
import BeautifulSoup
|
||||
|
||||
ignored_urls = [urlnorm.normalize("http://google.com"),urlnorm.normalize("http://youtube.com")]
|
||||
|
||||
def parse(match):
|
||||
url = urlnorm.normalize(match.encode('utf-8'))
|
||||
if url not in ignored_urls:
|
||||
url = url.decode('utf-8')
|
||||
try:
|
||||
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
|
||||
return soup.title.string
|
||||
except:
|
||||
return "Failed to parse URL"
|
||||
|
||||
|
||||
#@hook.regex(r'^(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$')
|
||||
|
||||
@hook.command
|
||||
def title(inp):
|
||||
p = re.compile(r'^(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$')
|
||||
m = p.match(inp)
|
||||
if m:
|
||||
return parse(inp)
|
||||
else:
|
||||
return 'Invalid URL!'
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
import inspect
|
||||
import re
|
||||
|
||||
|
||||
def _hook_add(func, add, name=''):
|
||||
if not hasattr(func, '_hook'):
|
||||
func._hook = []
|
||||
func._hook.append(add)
|
||||
|
||||
if not hasattr(func, '_filename'):
|
||||
func._filename = func.func_code.co_filename
|
||||
|
||||
if not hasattr(func, '_args'):
|
||||
argspec = inspect.getargspec(func)
|
||||
if name:
|
||||
n_args = len(argspec.args)
|
||||
if argspec.defaults:
|
||||
n_args -= len(argspec.defaults)
|
||||
if argspec.keywords:
|
||||
n_args -= 1
|
||||
if argspec.varargs:
|
||||
n_args -= 1
|
||||
if n_args != 1:
|
||||
err = '%ss must take 1 non-keyword argument (%s)' % (name,
|
||||
func.__name__)
|
||||
raise ValueError(err)
|
||||
|
||||
args = []
|
||||
if argspec.defaults:
|
||||
end = bool(argspec.keywords) + bool(argspec.varargs)
|
||||
args.extend(argspec.args[-len(argspec.defaults):
|
||||
end if end else None])
|
||||
if argspec.keywords:
|
||||
args.append(0) # means kwargs present
|
||||
func._args = args
|
||||
|
||||
if not hasattr(func, '_thread'): # does function run in its own thread?
|
||||
func._thread = False
|
||||
|
||||
|
||||
def sieve(func):
|
||||
if func.func_code.co_argcount != 5:
|
||||
raise ValueError(
|
||||
'sieves must take 5 arguments: (bot, input, func, type, args)')
|
||||
_hook_add(func, ['sieve', (func,)])
|
||||
return func
|
||||
|
||||
|
||||
def command(arg=None, **kwargs):
|
||||
args = {}
|
||||
|
||||
def command_wrapper(func):
|
||||
args.setdefault('name', func.func_name)
|
||||
_hook_add(func, ['command', (func, args)], 'command')
|
||||
return func
|
||||
|
||||
if kwargs or not inspect.isfunction(arg):
|
||||
if arg is not None:
|
||||
args['name'] = arg
|
||||
args.update(kwargs)
|
||||
return command_wrapper
|
||||
else:
|
||||
return command_wrapper(arg)
|
||||
|
||||
|
||||
def event(arg=None, **kwargs):
|
||||
args = kwargs
|
||||
|
||||
def event_wrapper(func):
|
||||
args['name'] = func.func_name
|
||||
args.setdefault('events', ['*'])
|
||||
_hook_add(func, ['event', (func, args)], 'event')
|
||||
return func
|
||||
|
||||
if inspect.isfunction(arg):
|
||||
return event_wrapper(arg, kwargs)
|
||||
else:
|
||||
if arg is not None:
|
||||
args['events'] = arg.split()
|
||||
return event_wrapper
|
||||
|
||||
|
||||
def singlethread(func):
|
||||
func._thread = True
|
||||
return func
|
||||
|
||||
|
||||
def regex(regex, flags=0, **kwargs):
|
||||
args = kwargs
|
||||
|
||||
def regex_wrapper(func):
|
||||
args['name'] = func.func_name
|
||||
args['regex'] = regex
|
||||
args['re'] = re.compile(regex, flags)
|
||||
_hook_add(func, ['regex', (func, args)], 'regex')
|
||||
return func
|
||||
|
||||
if inspect.isfunction(regex):
|
||||
raise ValueError("regex decorators require a regex to match against")
|
||||
else:
|
||||
return regex_wrapper
|
|
@ -0,0 +1,103 @@
|
|||
# convenience wrapper for urllib2 & friends
|
||||
|
||||
import cookielib
|
||||
import json
|
||||
import urllib
|
||||
import urllib2
|
||||
import urlparse
|
||||
|
||||
from urllib import quote, quote_plus as _quote_plus
|
||||
from urllib2 import HTTPError, URLError
|
||||
|
||||
from BeautifulSoup import BeautifulSoup
|
||||
|
||||
|
||||
from lxml import etree, html
|
||||
|
||||
|
||||
ua_skybot = 'Cloudbot/3.4 http://github.com/lukeroge/cloudbot'
|
||||
|
||||
ua_firefox = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) ' \
|
||||
'Gecko/20070725 Firefox/2.0.0.6'
|
||||
ua_internetexplorer = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
|
||||
|
||||
jar = cookielib.CookieJar()
|
||||
|
||||
|
||||
def get(*args, **kwargs):
|
||||
return open(*args, **kwargs).read()
|
||||
|
||||
|
||||
def get_html(*args, **kwargs):
|
||||
return html.fromstring(get(*args, **kwargs))
|
||||
|
||||
|
||||
def get_soup(*args, **kwargs):
|
||||
return BeautifulSoup(get(*args, **kwargs))
|
||||
|
||||
|
||||
def get_xml(*args, **kwargs):
|
||||
return etree.fromstring(get(*args, **kwargs))
|
||||
|
||||
|
||||
def get_json(*args, **kwargs):
|
||||
return json.loads(get(*args, **kwargs))
|
||||
|
||||
|
||||
def open(url, query_params=None, user_agent=None, post_data=None,
|
||||
get_method=None, cookies=False, **kwargs):
|
||||
|
||||
if query_params is None:
|
||||
query_params = {}
|
||||
|
||||
if user_agent is None:
|
||||
user_agent = ua_skybot
|
||||
|
||||
query_params.update(kwargs)
|
||||
|
||||
url = prepare_url(url, query_params)
|
||||
|
||||
request = urllib2.Request(url, post_data)
|
||||
|
||||
if get_method is not None:
|
||||
request.get_method = lambda: get_method
|
||||
|
||||
request.add_header('User-Agent', user_agent)
|
||||
|
||||
if cookies:
|
||||
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
|
||||
else:
|
||||
opener = urllib2.build_opener()
|
||||
|
||||
return opener.open(request)
|
||||
|
||||
|
||||
def prepare_url(url, queries):
|
||||
if queries:
|
||||
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
|
||||
|
||||
query = dict(urlparse.parse_qsl(query))
|
||||
query.update(queries)
|
||||
query = urllib.urlencode(dict((to_utf8(key), to_utf8(value))
|
||||
for key, value in query.iteritems()))
|
||||
|
||||
url = urlparse.urlunsplit((scheme, netloc, path, query, fragment))
|
||||
|
||||
return url
|
||||
|
||||
|
||||
def to_utf8(s):
|
||||
if isinstance(s, unicode):
|
||||
return s.encode('utf8', 'ignore')
|
||||
else:
|
||||
return str(s)
|
||||
|
||||
|
||||
def quote_plus(s):
|
||||
return _quote_plus(to_utf8(s))
|
||||
|
||||
|
||||
def unescape(s):
|
||||
if not s.strip():
|
||||
return s
|
||||
return html.fromstring(s).text_content()
|
|
@ -0,0 +1,54 @@
|
|||
from htmlentitydefs import name2codepoint
|
||||
from time import time as unix_time
|
||||
from HTMLParser import HTMLParser
|
||||
from datetime import datetime
|
||||
import tempfile
|
||||
import logging as log
|
||||
import errno
|
||||
import re
|
||||
import sys
|
||||
import os
|
||||
|
||||
class HTMLStripper(HTMLParser):
|
||||
|
||||
def __init__(self, data):
|
||||
HTMLParser.__init__(self)
|
||||
self._stripped = []
|
||||
self.feed(data)
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
if tag.lower() == 'br':
|
||||
self._stripped.append('\n')
|
||||
|
||||
def handle_charref(self, name):
|
||||
try:
|
||||
if name.lower().startswith('x'):
|
||||
char = int(name[1:], 16)
|
||||
else:
|
||||
char = int(name)
|
||||
self._stripped.append(unichr(char))
|
||||
except Exception, error:
|
||||
log.warn('invalid entity: %s' % error)
|
||||
|
||||
def handle_entityref(self, name):
|
||||
try:
|
||||
char = unichr(name2codepoint[name])
|
||||
except Exception, error:
|
||||
log.warn('unknown entity: %s' % error)
|
||||
char = u'&%s;' % name
|
||||
self._stripped.append(char)
|
||||
|
||||
def handle_data(self, data):
|
||||
self._stripped.append(data)
|
||||
|
||||
@property
|
||||
def stripped(self):
|
||||
return ''.join(self._stripped)
|
||||
|
||||
def superscript(text):
|
||||
if isinstance(text, str):
|
||||
text = decode(text, 'utf-8')
|
||||
return text.translate(SUPER_MAP)
|
||||
|
||||
def strip_html(data):
|
||||
return HTMLStripper(data).stripped
|
|
@ -0,0 +1,219 @@
|
|||
#!/usr/bin/env python
|
||||
#
|
||||
# molecular.py
|
||||
# Copyright (c) 2001, Chris Gonnerman
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions
|
||||
# are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
#
|
||||
# Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in the
|
||||
# documentation and/or other materials provided with the distribution.
|
||||
#
|
||||
# Neither the name of the author nor the names of any contributors
|
||||
# may be used to endorse or promote products derived from this software
|
||||
# without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
# AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""molecular.py -- molecular (ngenoid) name generator
|
||||
|
||||
This module knows how to generate "random" names for RPG characters.
|
||||
It uses the same method as the "ngen" name generator by Kimmo Kulovesi,
|
||||
and in fact it can use the same name files. molecular.py knows how
|
||||
to merge multiple tables also, which can be handy...
|
||||
|
||||
If run as a command-line program, use the following options:
|
||||
|
||||
-r namefile -- read the given name file and add to the
|
||||
current name table.
|
||||
nnn -- generate nnn (a number) names and print
|
||||
on standard output.
|
||||
|
||||
To generate names from a name file:
|
||||
|
||||
python molecular.py -r file 10
|
||||
|
||||
As a module (to be imported) you get the following classes and functions:
|
||||
|
||||
NameFile (class) -- a file wrapper with a disabled close() method,
|
||||
used internally and probably not useful otherwise.
|
||||
nameopen (function) -- opens a file; takes filename and mode options,
|
||||
searches the default name file directory if not
|
||||
found in current directory, handles "-" filenames,
|
||||
and uses NameFile to disable closing of sys.stdin/
|
||||
sys.stdout.
|
||||
Molecule (class) -- the meat of the matter. A Molecule instance has
|
||||
the following methods:
|
||||
|
||||
.load(file) -- loads a name file,
|
||||
which may be a file-like
|
||||
object with a .readline()
|
||||
method or a filename as a
|
||||
string.
|
||||
.name() -- generate one name and
|
||||
return it.
|
||||
"""
|
||||
|
||||
__version__ = "1.0"
|
||||
|
||||
import string, re, sys, random
|
||||
|
||||
NAMEDIR = "/home/ircbot/bot/plugins/util/names"
|
||||
NAMESECTIONS = [ "inf", "first", "mid", "final", "notes", "end" ]
|
||||
|
||||
class NameFile:
|
||||
__file_attributes = ('closed','mode','name','softspace')
|
||||
def __init__(self, file):
|
||||
self.fd = file
|
||||
def close(self):
|
||||
pass
|
||||
def flush(self):
|
||||
return self.fd.flush()
|
||||
def isatty(self):
|
||||
return self.fd.isatty()
|
||||
def fileno(self):
|
||||
return self.fd.fileno()
|
||||
def read(self, *args):
|
||||
return apply(self.fd.read, args)
|
||||
def readline(self, *args):
|
||||
return apply(self.fd.readline, args)
|
||||
def readlines(self, *args):
|
||||
return apply(self.fd.readlines, args)
|
||||
def seek(self, *args):
|
||||
return apply(self.fd.seek, args)
|
||||
def tell(self):
|
||||
return self.fd.tell()
|
||||
def write(self, str):
|
||||
return self.fd.write(str)
|
||||
def writelines(self, list):
|
||||
return self.fd.writelines(list)
|
||||
def __repr__(self):
|
||||
return repr(self.fd)
|
||||
def __getattr__(self, name):
|
||||
if name in self.__file_attributes:
|
||||
return getattr(self.fd, name)
|
||||
else:
|
||||
return self.__dict__[name]
|
||||
def __setattr__(self, name, value):
|
||||
if name in self.__file_attributes:
|
||||
setattr(self.fd, name, value)
|
||||
else:
|
||||
self.__dict__[name] = value
|
||||
def __cmp__(self, file):
|
||||
"""I'm not sure what the correct behavior is, and therefore
|
||||
this implementation is just a guess."""
|
||||
if type(file) == type(self.fd):
|
||||
return cmp(self.fd, file)
|
||||
else:
|
||||
return cmp(self.fd, file.fd)
|
||||
|
||||
|
||||
class NameReader:
|
||||
def __init__(self, file):
|
||||
self.file = file
|
||||
self.line = ""
|
||||
def next(self):
|
||||
self.line = self.file.readline()
|
||||
return self.line
|
||||
def close(self):
|
||||
return self.file.close()
|
||||
|
||||
|
||||
def safeopen(filename, mode):
|
||||
try:
|
||||
return open(filename, mode)
|
||||
except IOError:
|
||||
return None
|
||||
|
||||
def nameopen(filename, mode):
|
||||
if filename == "-":
|
||||
if "r" in mode:
|
||||
return NameFile(sys.stdin)
|
||||
else:
|
||||
return NameFile(sys.stdout)
|
||||
fp = safeopen(filename, mode)
|
||||
if fp is None:
|
||||
fp = safeopen(filename + ".nam", mode)
|
||||
if "r" in mode and fp is None:
|
||||
fp = safeopen(NAMEDIR + "/" + filename, mode)
|
||||
# last call is open() instead of safeopen() to finally raise
|
||||
# the exception if we just can't find the file.
|
||||
if fp is None:
|
||||
fp = open(NAMEDIR + "/" + filename + ".nam", mode)
|
||||
return fp
|
||||
|
||||
|
||||
class Molecule:
|
||||
|
||||
def __init__(self):
|
||||
self.nametbl = {}
|
||||
for i in NAMESECTIONS:
|
||||
self.nametbl[i] = []
|
||||
self.nametbl[""] = []
|
||||
self.cursection = self.nametbl[""]
|
||||
|
||||
def load(self, fp):
|
||||
if type(fp) is type(""):
|
||||
fp = nameopen(fp, "r")
|
||||
else:
|
||||
fp = NameFile(fp)
|
||||
rdr = NameReader(fp)
|
||||
while rdr.next():
|
||||
line = rdr.line[:-1]
|
||||
if len(line) > 0 and line[0] == '[' and line[-1] == ']':
|
||||
line = string.strip(line)[1:-1]
|
||||
if not self.nametbl.has_key(line):
|
||||
self.nametbl[line] = []
|
||||
self.cursection = self.nametbl[line]
|
||||
else:
|
||||
self.cursection.append(line)
|
||||
fp.close()
|
||||
|
||||
def name(self):
|
||||
n = []
|
||||
if len(self.nametbl["first"]) > 0:
|
||||
n.append(random.choice(self.nametbl["first"]))
|
||||
if len(self.nametbl["mid"]) > 0:
|
||||
n.append(random.choice(self.nametbl["mid"]))
|
||||
if len(self.nametbl["final"]) > 0:
|
||||
n.append(random.choice(self.nametbl["final"]))
|
||||
return string.join(n, "")
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
if len(sys.argv) <= 1:
|
||||
sys.stderr.write( \
|
||||
"Usage: molecular.py [ -r file ] [ nn ]\n")
|
||||
sys.exit(0)
|
||||
|
||||
name = Molecule()
|
||||
|
||||
i = 1
|
||||
|
||||
while i < len(sys.argv):
|
||||
arg = sys.argv[i]
|
||||
if arg == "-r":
|
||||
i += 1
|
||||
name.load(sys.argv[i])
|
||||
else:
|
||||
n = int(sys.argv[i])
|
||||
lst = []
|
||||
for i in range(n):
|
||||
print name.name()
|
||||
i += 1
|
|
@ -0,0 +1,102 @@
|
|||
# Copyright (c) Django Software Foundation and individual contributors.
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# 1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
# 2. Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in the
|
||||
# documentation and/or other materials provided with the distribution.
|
||||
#
|
||||
# 3. Neither the name of Django nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without
|
||||
# specific prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND
|
||||
#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
#DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
#ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
#(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
#LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
#ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
#(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
#SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
import datetime
|
||||
|
||||
|
||||
def timesince(d, now=None):
|
||||
"""
|
||||
Takes two datetime objects and returns the time between d and now
|
||||
as a nicely formatted string, e.g. "10 minutes". If d occurs after now,
|
||||
then "0 minutes" is returned.
|
||||
|
||||
Units used are years, months, weeks, days, hours, and minutes.
|
||||
Seconds and microseconds are ignored. Up to two adjacent units will be
|
||||
displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are
|
||||
possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.
|
||||
|
||||
Adapted from http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
|
||||
"""
|
||||
chunks = (
|
||||
(60 * 60 * 24 * 365, ('year', 'years')),
|
||||
(60 * 60 * 24 * 30, ('month', 'months')),
|
||||
(60 * 60 * 24 * 7, ('week', 'weeks')),
|
||||
(60 * 60 * 24, ('day', 'days')),
|
||||
(60 * 60, ('hour', 'hours')),
|
||||
(60, ('minute', 'minutes'))
|
||||
)
|
||||
|
||||
# Convert int or float (unix epoch) to datetime.datetime for comparison
|
||||
if isinstance(d, int) or isinstance(d, float):
|
||||
d = datetime.datetime.fromtimestamp(d)
|
||||
|
||||
# Convert datetime.date to datetime.datetime for comparison.
|
||||
if not isinstance(d, datetime.datetime):
|
||||
d = datetime.datetime(d.year, d.month, d.day)
|
||||
if now and not isinstance(now, datetime.datetime):
|
||||
now = datetime.datetime(now.year, now.month, now.day)
|
||||
|
||||
if not now:
|
||||
now = datetime.datetime.now()
|
||||
|
||||
# ignore microsecond part of 'd' since we removed it from 'now'
|
||||
delta = now - (d - datetime.timedelta(0, 0, d.microsecond))
|
||||
since = delta.days * 24 * 60 * 60 + delta.seconds
|
||||
if since <= 0:
|
||||
# d is in the future compared to now, stop processing.
|
||||
return u'0 ' + 'minutes'
|
||||
for i, (seconds, name) in enumerate(chunks):
|
||||
count = since // seconds
|
||||
if count != 0:
|
||||
break
|
||||
|
||||
if count == 1:
|
||||
s = '%(number)d %(type)s' % {'number': count, 'type': name[0]}
|
||||
else:
|
||||
s = '%(number)d %(type)s' % {'number': count, 'type': name[1]}
|
||||
|
||||
if i + 1 < len(chunks):
|
||||
# Now get the second item
|
||||
seconds2, name2 = chunks[i + 1]
|
||||
count2 = (since - (seconds * count)) // seconds2
|
||||
if count2 != 0:
|
||||
if count2 == 1:
|
||||
s += ', %d %s' % (count2, name2[0])
|
||||
else:
|
||||
s += ', %d %s' % (count2, name2[1])
|
||||
return s
|
||||
|
||||
|
||||
def timeuntil(d, now=None):
|
||||
"""
|
||||
Like timesince, but returns a string measuring the time until
|
||||
the given time.
|
||||
"""
|
||||
if not now:
|
||||
now = datetime.datetime.now()
|
||||
return timesince(now, d)
|
|
@ -0,0 +1,133 @@
|
|||
"""
|
||||
URI Normalization function:
|
||||
* Always provide the URI scheme in lowercase characters.
|
||||
* Always provide the host, if any, in lowercase characters.
|
||||
* Only perform percent-encoding where it is essential.
|
||||
* Always use uppercase A-through-F characters when percent-encoding.
|
||||
* Prevent dot-segments appearing in non-relative URI paths.
|
||||
* For schemes that define a default authority, use an empty authority if the
|
||||
default is desired.
|
||||
* For schemes that define an empty path to be equivalent to a path of "/",
|
||||
use "/".
|
||||
* For schemes that define a port, use an empty port if the default is desired
|
||||
* All portions of the URI must be utf-8 encoded NFC from Unicode strings
|
||||
|
||||
implements:
|
||||
http://gbiv.com/protocols/uri/rev-2002/rfc2396bis.html#canonical-form
|
||||
http://www.intertwingly.net/wiki/pie/PaceCanonicalIds
|
||||
|
||||
inspired by:
|
||||
Tony J. Ibbs, http://starship.python.net/crew/tibs/python/tji_url.py
|
||||
Mark Nottingham, http://www.mnot.net/python/urlnorm.py
|
||||
"""
|
||||
|
||||
__license__ = "Python"
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
import urlparse
|
||||
from urllib import quote, unquote
|
||||
|
||||
default_port = {
|
||||
'http': 80,
|
||||
}
|
||||
|
||||
|
||||
class Normalizer(object):
|
||||
def __init__(self, regex, normalize_func):
|
||||
self.regex = regex
|
||||
self.normalize = normalize_func
|
||||
|
||||
normalizers = ( Normalizer( re.compile(r'(?:https?://)?(?:[a-zA-Z0-9\-]+\.)?(?:amazon|amzn){1}\.(?P<tld>[a-zA-Z\.]{2,})\/(gp/(?:product|offer-listing|customer-media/product-gallery)/|exec/obidos/tg/detail/-/|o/ASIN/|dp/|(?:[A-Za-z0-9\-]+)/dp/)?(?P<ASIN>[0-9A-Za-z]{10})'),
|
||||
lambda m: r'http://amazon.%s/dp/%s' % (m.group('tld'), m.group('ASIN'))),
|
||||
Normalizer( re.compile(r'.*waffleimages\.com.*/([0-9a-fA-F]{40})'),
|
||||
lambda m: r'http://img.waffleimages.com/%s' % m.group(1) ),
|
||||
Normalizer( re.compile(r'(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)([-_a-z0-9]+)'),
|
||||
lambda m: r'http://youtube.com/watch?v=%s' % m.group(1) ),
|
||||
)
|
||||
|
||||
|
||||
def normalize(url):
|
||||
"""Normalize a URL."""
|
||||
|
||||
scheme, auth, path, query, fragment = urlparse.urlsplit(url.strip())
|
||||
userinfo, host, port = re.search('([^@]*@)?([^:]*):?(.*)', auth).groups()
|
||||
|
||||
# Always provide the URI scheme in lowercase characters.
|
||||
scheme = scheme.lower()
|
||||
|
||||
# Always provide the host, if any, in lowercase characters.
|
||||
host = host.lower()
|
||||
if host and host[-1] == '.':
|
||||
host = host[:-1]
|
||||
if host and host.startswith("www."):
|
||||
if not scheme:
|
||||
scheme = "http"
|
||||
host = host[4:]
|
||||
elif path and path.startswith("www."):
|
||||
if not scheme:
|
||||
scheme = "http"
|
||||
path = path[4:]
|
||||
|
||||
# Only perform percent-encoding where it is essential.
|
||||
# Always use uppercase A-through-F characters when percent-encoding.
|
||||
# All portions of the URI must be utf-8 encoded NFC from Unicode strings
|
||||
def clean(string):
|
||||
string = unicode(unquote(string), 'utf-8', 'replace')
|
||||
return unicodedata.normalize('NFC', string).encode('utf-8')
|
||||
path = quote(clean(path), "~:/?#[]@!$&'()*+,;=")
|
||||
fragment = quote(clean(fragment), "~")
|
||||
|
||||
# note care must be taken to only encode & and = characters as values
|
||||
query = "&".join(["=".join([quote(clean(t), "~:/?#[]@!$'()*+,;=")
|
||||
for t in q.split("=", 1)]) for q in query.split("&")])
|
||||
|
||||
# Prevent dot-segments appearing in non-relative URI paths.
|
||||
if scheme in ["", "http", "https", "ftp", "file"]:
|
||||
output = []
|
||||
for input in path.split('/'):
|
||||
if input == "":
|
||||
if not output:
|
||||
output.append(input)
|
||||
elif input == ".":
|
||||
pass
|
||||
elif input == "..":
|
||||
if len(output) > 1:
|
||||
output.pop()
|
||||
else:
|
||||
output.append(input)
|
||||
if input in ["", ".", ".."]:
|
||||
output.append("")
|
||||
path = '/'.join(output)
|
||||
|
||||
# For schemes that define a default authority, use an empty authority if
|
||||
# the default is desired.
|
||||
if userinfo in ["@", ":@"]:
|
||||
userinfo = ""
|
||||
|
||||
# For schemes that define an empty path to be equivalent to a path of "/",
|
||||
# use "/".
|
||||
if path == "" and scheme in ["http", "https", "ftp", "file"]:
|
||||
path = "/"
|
||||
|
||||
# For schemes that define a port, use an empty port if the default is
|
||||
# desired
|
||||
if port and scheme in default_port.keys():
|
||||
if port.isdigit():
|
||||
port = str(int(port))
|
||||
if int(port) == default_port[scheme]:
|
||||
port = ''
|
||||
|
||||
# Put it all back together again
|
||||
auth = (userinfo or "") + host
|
||||
if port:
|
||||
auth += ":" + port
|
||||
if url.endswith("#") and query == "" and fragment == "":
|
||||
path += "#"
|
||||
normal_url = urlparse.urlunsplit((scheme, auth, path, query,
|
||||
fragment)).replace("http:///", "http://")
|
||||
for norm in normalizers:
|
||||
m = norm.regex.match(normal_url)
|
||||
if m:
|
||||
return norm.normalize(m)
|
||||
return normal_url
|
|
@ -0,0 +1,25 @@
|
|||
'''
|
||||
Runs a given url through the w3c validator
|
||||
|
||||
by Vladi
|
||||
'''
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
@hook.command
|
||||
def validate(inp):
|
||||
".validate <url> -- runs url through w3c markup validator"
|
||||
|
||||
if not inp.startswith('http://'):
|
||||
inp = 'http://' + inp
|
||||
|
||||
url = 'http://validator.w3.org/check?uri=' + http.quote_plus(inp)
|
||||
info = dict(http.open(url).info())
|
||||
|
||||
status = info['x-w3c-validator-status'].lower()
|
||||
if status in ("valid", "invalid"):
|
||||
errorcount = info['x-w3c-validator-errors']
|
||||
warningcount = info['x-w3c-validator-warnings']
|
||||
return "%s was found to be %s with %s errors and %s warnings." \
|
||||
" see: %s" % (inp, status, errorcount, warningcount, url)
|
|
@ -0,0 +1,14 @@
|
|||
from util import hook, http
|
||||
|
||||
|
||||
@hook.regex(r'vimeo.com/([0-9]+)')
|
||||
def vimeo_url(match):
|
||||
info = http.get_json('http://vimeo.com/api/v2/video/%s.json'
|
||||
% match.group(1))
|
||||
|
||||
if info:
|
||||
return ("\x02%(title)s\x02 - length \x02%(duration)ss\x02 - "
|
||||
"\x02%(stats_number_of_likes)s\x02 likes - "
|
||||
"\x02%(stats_number_of_plays)s\x02 plays - "
|
||||
"\x02%(user_name)s\x02 on \x02%(upload_date)s\x02"
|
||||
% info[0])
|
|
@ -0,0 +1,45 @@
|
|||
"weather, thanks to google"
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
@hook.command(autohelp=False)
|
||||
def weather(inp, nick='', server='', reply=None, db=None, notice=None):
|
||||
".weather <location> [dontsave] -- gets weather data from Google"
|
||||
|
||||
loc = inp
|
||||
|
||||
dontsave = loc.endswith(" dontsave")
|
||||
if dontsave:
|
||||
loc = loc[:-9].strip().lower()
|
||||
|
||||
db.execute("create table if not exists weather(nick primary key, loc)")
|
||||
|
||||
if not loc: # blank line
|
||||
loc = db.execute("select loc from weather where nick=lower(?)",
|
||||
(nick,)).fetchone()
|
||||
if not loc:
|
||||
notice(weather.__doc__)
|
||||
return
|
||||
loc = loc[0]
|
||||
|
||||
w = http.get_xml('http://www.google.com/ig/api', weather=loc)
|
||||
w = w.find('weather')
|
||||
|
||||
if w.find('problem_cause') is not None:
|
||||
notice("Couldn't fetch weather data for '%s', try using a zip or " \
|
||||
"postal code." % inp)
|
||||
return
|
||||
|
||||
info = dict((e.tag, e.get('data')) for e in w.find('current_conditions'))
|
||||
info['city'] = w.find('forecast_information/city').get('data')
|
||||
info['high'] = w.find('forecast_conditions/high').get('data')
|
||||
info['low'] = w.find('forecast_conditions/low').get('data')
|
||||
|
||||
reply('%(city)s: %(condition)s, %(temp_f)sF/%(temp_c)sC (H:%(high)sF'\
|
||||
', L:%(low)sF), %(humidity)s, %(wind_condition)s.' % info)
|
||||
|
||||
if inp and not dontsave:
|
||||
db.execute("insert or replace into weather(nick, loc) values (?,?)",
|
||||
(nick.lower(), loc))
|
||||
db.commit()
|
|
@ -0,0 +1,51 @@
|
|||
'''Searches wikipedia and returns first sentence of article
|
||||
Scaevolus 2009'''
|
||||
|
||||
import re
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
api_prefix = "http://en.wikipedia.org/w/api.php"
|
||||
search_url = api_prefix + "?action=opensearch&format=xml"
|
||||
|
||||
paren_re = re.compile('\s*\(.*\)$')
|
||||
|
||||
|
||||
@hook.command('w')
|
||||
@hook.command
|
||||
def wiki(inp):
|
||||
'''.w/.wiki <phrase> -- gets first sentence of wikipedia ''' \
|
||||
'''article on <phrase>'''
|
||||
|
||||
x = http.get_xml(search_url, search=inp)
|
||||
|
||||
ns = '{http://opensearch.org/searchsuggest2}'
|
||||
items = x.findall(ns + 'Section/' + ns + 'Item')
|
||||
|
||||
if items == []:
|
||||
if x.find('error') is not None:
|
||||
return 'error: %(code)s: %(info)s' % x.find('error').attrib
|
||||
else:
|
||||
return 'no results found'
|
||||
|
||||
def extract(item):
|
||||
return [item.find(ns + x).text for x in
|
||||
('Text', 'Description', 'Url')]
|
||||
|
||||
title, desc, url = extract(items[0])
|
||||
|
||||
if 'may refer to' in desc:
|
||||
title, desc, url = extract(items[1])
|
||||
|
||||
title = paren_re.sub('', title)
|
||||
|
||||
if title.lower() not in desc.lower():
|
||||
desc = title + desc
|
||||
|
||||
desc = re.sub('\s+', ' ', desc).strip() # remove excess spaces
|
||||
|
||||
if len(desc) > 300:
|
||||
desc = desc[:300] + '...'
|
||||
|
||||
return '%s -- %s' % (desc, http.quote(url, ':/'))
|
|
@ -0,0 +1,56 @@
|
|||
import re
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
@hook.command('wa')
|
||||
@hook.command
|
||||
def wolframalpha(inp):
|
||||
".wa/.wolframalpha <query> -- scrapes Wolfram Alpha's" \
|
||||
" results for <query>"
|
||||
|
||||
url = "http://www.wolframalpha.com/input/?asynchronous=false"
|
||||
|
||||
h = http.get_html(url, i=inp)
|
||||
|
||||
pods = h.xpath("//div[@class='pod ']")
|
||||
|
||||
pod_texts = []
|
||||
for pod in pods:
|
||||
heading = pod.find('h2')
|
||||
if heading is not None:
|
||||
heading = heading.text_content().strip()
|
||||
if heading.startswith('Input'):
|
||||
continue
|
||||
else:
|
||||
continue
|
||||
|
||||
results = []
|
||||
for alt in pod.xpath('div/div[@class="output pnt"]/img/@alt'):
|
||||
alt = alt.strip().replace('\\n', '; ')
|
||||
alt = re.sub(r'\s+', ' ', alt)
|
||||
if alt:
|
||||
results.append(alt)
|
||||
if results:
|
||||
pod_texts.append(heading + ' ' + '|'.join(results))
|
||||
|
||||
ret = '. '.join(pod_texts)
|
||||
|
||||
if not pod_texts:
|
||||
return 'no results'
|
||||
|
||||
ret = re.sub(r'\\(.)', r'\1', ret)
|
||||
|
||||
def unicode_sub(match):
|
||||
return unichr(int(match.group(1), 16))
|
||||
|
||||
ret = re.sub(r'\\:([0-9a-z]{4})', unicode_sub, ret)
|
||||
|
||||
if len(ret) > 430:
|
||||
ret = ret[:ret.rfind(' ', 0, 430)]
|
||||
ret = re.sub(r'\W+$', '', ret) + '...'
|
||||
|
||||
if not ret:
|
||||
return 'no result'
|
||||
|
||||
return ret
|
|
@ -0,0 +1,19 @@
|
|||
import re
|
||||
from util import hook, http
|
||||
from BeautifulSoup import BeautifulSoup
|
||||
|
||||
@hook.command(autohelp=False)
|
||||
def wordu(inp, say=False, nick=False):
|
||||
".word -- gets the word of the day
|
||||
return "true"
|
||||
page = http.get('http://merriam-webster.com/word-of-the-day')
|
||||
|
||||
soup = BeautifulSoup(page)
|
||||
|
||||
word = soup.find('strong', {'class' : 'main_entry_word'})
|
||||
function = soup.find('p', {'class' : 'word_function'})
|
||||
|
||||
#definitions = re.findall(r'<span class="ssens"><strong>:</strong>'
|
||||
# r' *([^<]+)</span>', content)
|
||||
|
||||
say("(%s) The word of the day is: \x02%s\x02 (%s)" % (nick, word, function))
|
|
@ -0,0 +1,90 @@
|
|||
import locale
|
||||
import re
|
||||
import time
|
||||
|
||||
from util import hook, http
|
||||
|
||||
|
||||
locale.setlocale(locale.LC_ALL, '')
|
||||
|
||||
youtube_re = (r'(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)'
|
||||
'([-_a-z0-9]+)', re.I)
|
||||
|
||||
base_url = 'http://gdata.youtube.com/feeds/api/'
|
||||
url = base_url + 'videos/%s?v=2&alt=jsonc'
|
||||
search_api_url = base_url + 'videos?v=2&alt=jsonc&max-results=1'
|
||||
video_url = "http://youtube.com/watch?v=%s"
|
||||
|
||||
|
||||
def get_video_description(vid_id):
|
||||
j = http.get_json(url % vid_id)
|
||||
|
||||
if j.get('error'):
|
||||
return
|
||||
|
||||
j = j['data']
|
||||
out = {}
|
||||
out["title"] = '%s' % j['title']
|
||||
|
||||
if not j.get('duration'):
|
||||
return out
|
||||
|
||||
length = j['duration']
|
||||
ti = ""
|
||||
if length / 3600: # > 1 hour
|
||||
ti += '%dh ' % (length / 3600)
|
||||
if length / 60:
|
||||
ti += '%dm ' % (length / 60 % 60)
|
||||
out["length"] = ti
|
||||
#out += "%ds\x02" % (length % 60)
|
||||
|
||||
if 'ratingCount' in j and 'likeCount' in j:
|
||||
out["likes"] = int(j['likeCount'])
|
||||
out["dislikes"] = int(j['ratingCount']) - int(j['likeCount'])
|
||||
|
||||
if 'rating' in j:
|
||||
out["rating"] = (j['rating'])
|
||||
|
||||
if 'viewCount' in j:
|
||||
out["views"] = j['viewCount']
|
||||
|
||||
upload_time = time.strptime(j['uploaded'], "%Y-%m-%dT%H:%M:%S.000Z")
|
||||
out["uploadtime"] = (j['uploader'])
|
||||
|
||||
|
||||
# title. uploader. length. upload date.
|
||||
give = '\x02' + j[u'title'] + '\x02'
|
||||
give += " - Length: " + GetInHMS(j['duration'])
|
||||
give += " - "+ j[u'uploaded'][:10] + " by " + j[u'uploader']
|
||||
return give
|
||||
|
||||
def GetInHMS(seconds):
|
||||
hours = seconds / 3600
|
||||
seconds -= 3600*hours
|
||||
minutes = seconds / 60
|
||||
seconds -= 60*minutes
|
||||
if hours == 0:
|
||||
return "%02d:%02d" % (minutes, seconds)
|
||||
return "%02d:%02d:%02d" % (hours, minutes, seconds)
|
||||
|
||||
|
||||
@hook.regex(*youtube_re)
|
||||
def youtube_url(match):
|
||||
return get_video_description(match.group(1))
|
||||
|
||||
@hook.command('y')
|
||||
@hook.command
|
||||
def youtube(inp):
|
||||
'.youtube <query> -- returns the first YouTube search result for <query>'
|
||||
|
||||
j = http.get_json(search_api_url, q=inp)
|
||||
|
||||
if 'error' in j:
|
||||
return 'error performing search'
|
||||
|
||||
if j['data']['totalItems'] == 0:
|
||||
return 'no results found'
|
||||
|
||||
vid_id = j['data']['items'][0]['id']
|
||||
|
||||
return get_video_description(vid_id) + " - " + video_url % vid_id
|
Reference in New Issue