mirror of
http://aero2k.de/t/repos/urlbot-native.git
synced 2017-09-06 15:25:38 +02:00
replace local logger() by logging infrastructure
This commit is contained in:
15
common.py
15
common.py
@@ -5,7 +5,7 @@ if '__main__' == __name__:
|
|||||||
print('''this is a library file, which is not meant to be executed''')
|
print('''this is a library file, which is not meant to be executed''')
|
||||||
exit(-1)
|
exit(-1)
|
||||||
|
|
||||||
import sys, time, pickle, os
|
import sys, time, pickle, os, logging
|
||||||
from local_config import conf
|
from local_config import conf
|
||||||
|
|
||||||
RATE_GLOBAL = 0x01
|
RATE_GLOBAL = 0x01
|
||||||
@@ -21,16 +21,17 @@ basedir = '.'
|
|||||||
if 2 == len(sys.argv):
|
if 2 == len(sys.argv):
|
||||||
basedir = sys.argv[1]
|
basedir = sys.argv[1]
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format=sys.argv[0]+' %(asctime)s %(levelname)-8s %(message)s'
|
||||||
|
)
|
||||||
|
log = logging.getLogger()
|
||||||
|
log.plugin = log.info # ... probably fix this sometime (FIXME)
|
||||||
|
|
||||||
def debug_enabled():
|
def debug_enabled():
|
||||||
# return True
|
# return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def logger(severity, message):
|
|
||||||
# sev = ( 'err', 'warn', 'info' )
|
|
||||||
# if severity in sev:
|
|
||||||
args = (sys.argv[0], time.strftime('%Y-%m-%d.%H:%M:%S'), severity, message)
|
|
||||||
sys.stderr.write('%s %s %s: %s\n' % args)
|
|
||||||
|
|
||||||
def conf_save(obj):
|
def conf_save(obj):
|
||||||
with open(conf('persistent_storage'), 'wb') as fd:
|
with open(conf('persistent_storage'), 'wb') as fd:
|
||||||
return pickle.dump(obj, fd)
|
return pickle.dump(obj, fd)
|
||||||
|
|||||||
12
idlebot.py
12
idlebot.py
@@ -17,7 +17,6 @@ except ImportError:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
import logging
|
|
||||||
from sleekxmpp import ClientXMPP
|
from sleekxmpp import ClientXMPP
|
||||||
|
|
||||||
got_hangup = False
|
got_hangup = False
|
||||||
@@ -37,7 +36,7 @@ class bot(ClientXMPP):
|
|||||||
self.send_presence()
|
self.send_presence()
|
||||||
|
|
||||||
for room in self.rooms:
|
for room in self.rooms:
|
||||||
logger('info', 'joining %s' % room)
|
log.info('joining %s' % room)
|
||||||
self.plugin['xep_0045'].joinMUC(
|
self.plugin['xep_0045'].joinMUC(
|
||||||
room,
|
room,
|
||||||
self.nick,
|
self.nick,
|
||||||
@@ -55,7 +54,7 @@ class bot(ClientXMPP):
|
|||||||
return
|
return
|
||||||
|
|
||||||
if msg_obj['body'].startswith(conf('bot_user')) and 'hangup' in msg_obj['body']:
|
if msg_obj['body'].startswith(conf('bot_user')) and 'hangup' in msg_obj['body']:
|
||||||
logger('warn', "got 'hangup' from '%s': '%s'" % (
|
log.warn("got 'hangup' from '%s': '%s'" % (
|
||||||
msg_obj['mucnick'], msg_obj['body']
|
msg_obj['mucnick'], msg_obj['body']
|
||||||
))
|
))
|
||||||
got_hangup = True
|
got_hangup = True
|
||||||
@@ -63,12 +62,7 @@ class bot(ClientXMPP):
|
|||||||
|
|
||||||
|
|
||||||
if '__main__' == __name__:
|
if '__main__' == __name__:
|
||||||
print(sys.argv[0] + ' ' + VERSION)
|
log.info(VERSION)
|
||||||
|
|
||||||
logging.basicConfig(
|
|
||||||
level=logging.INFO,
|
|
||||||
format='%(levelname)-8s %(message)s'
|
|
||||||
)
|
|
||||||
|
|
||||||
xmpp = bot(
|
xmpp = bot(
|
||||||
jid=conf('jid'),
|
jid=conf('jid'),
|
||||||
|
|||||||
84
plugins.py
84
plugins.py
@@ -60,7 +60,7 @@ def parse_mental_ill(**args):
|
|||||||
break
|
break
|
||||||
|
|
||||||
if True == flag:
|
if True == flag:
|
||||||
logger('plugin', 'sent mental illness reply')
|
log.plugin('sent mental illness reply')
|
||||||
return {
|
return {
|
||||||
'msg': '''Multiple exclamation/question marks are a sure sign of mental disease, with %s as a living example.''' % args['reply_user']
|
'msg': '''Multiple exclamation/question marks are a sure sign of mental disease, with %s as a living example.''' % args['reply_user']
|
||||||
}
|
}
|
||||||
@@ -73,7 +73,7 @@ def parse_debbug(**args):
|
|||||||
|
|
||||||
out = []
|
out = []
|
||||||
for b in bugs:
|
for b in bugs:
|
||||||
logger('plugin', 'detected Debian bug #%s' % b)
|
log.plugin('detected Debian bug #%s' % b)
|
||||||
|
|
||||||
url = 'https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s' % b
|
url = 'https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s' % b
|
||||||
status, title = extract_title(url)
|
status, title = extract_title(url)
|
||||||
@@ -83,7 +83,7 @@ def parse_debbug(**args):
|
|||||||
elif 3 == status:
|
elif 3 == status:
|
||||||
out.append('error for #%s: %s' % (b, title))
|
out.append('error for #%s: %s' % (b, title))
|
||||||
else:
|
else:
|
||||||
logger('plugin', 'parse_debbug(): unknown status %d' % status)
|
log.plugin('parse_debbug(): unknown status %d' % status)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'msg': out
|
'msg': out
|
||||||
@@ -95,7 +95,7 @@ def parse_cve(**args):
|
|||||||
if not cves:
|
if not cves:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
logger('plugin', 'detected CVE handle')
|
log.plugin('detected CVE handle')
|
||||||
return {
|
return {
|
||||||
'msg': ['https://security-tracker.debian.org/tracker/%s' % c for c in cves]
|
'msg': ['https://security-tracker.debian.org/tracker/%s' % c for c in cves]
|
||||||
}
|
}
|
||||||
@@ -106,7 +106,7 @@ def parse_dsa(**args):
|
|||||||
if not dsas:
|
if not dsas:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
logger('plugin', 'detected DSA handle')
|
log.plugin('detected DSA handle')
|
||||||
return {
|
return {
|
||||||
'msg': ['https://security-tracker.debian.org/tracker/%s' % d for d in dsas]
|
'msg': ['https://security-tracker.debian.org/tracker/%s' % d for d in dsas]
|
||||||
}
|
}
|
||||||
@@ -114,7 +114,7 @@ def parse_dsa(**args):
|
|||||||
@pluginfunction('skynet', 'parse skynet', ptypes_PARSE)
|
@pluginfunction('skynet', 'parse skynet', ptypes_PARSE)
|
||||||
def parse_skynet(**args):
|
def parse_skynet(**args):
|
||||||
if 'skynet' in args['data'].lower():
|
if 'skynet' in args['data'].lower():
|
||||||
logger('plugin', 'sent skynet reply')
|
log.plugin('sent skynet reply')
|
||||||
return {
|
return {
|
||||||
'msg': '''I'm an independent bot and have nothing to do with other artificial intelligence systems!'''
|
'msg': '''I'm an independent bot and have nothing to do with other artificial intelligence systems!'''
|
||||||
}
|
}
|
||||||
@@ -122,7 +122,7 @@ def parse_skynet(**args):
|
|||||||
@pluginfunction('moin', 'parse moin/bye', ptypes_PARSE)
|
@pluginfunction('moin', 'parse moin/bye', ptypes_PARSE)
|
||||||
def parse_moin_bye(**args):
|
def parse_moin_bye(**args):
|
||||||
if args['reply_user'] in conf('moin-disabled-user'):
|
if args['reply_user'] in conf('moin-disabled-user'):
|
||||||
logger('plugin', 'moin blacklist match')
|
log.plugin('moin blacklist match')
|
||||||
return
|
return
|
||||||
|
|
||||||
moin = [
|
moin = [
|
||||||
@@ -149,7 +149,7 @@ def parse_moin_bye(**args):
|
|||||||
for w in words:
|
for w in words:
|
||||||
if d.lower() == w.lower():
|
if d.lower() == w.lower():
|
||||||
if args['reply_user'] in conf('moin-modified-user'):
|
if args['reply_user'] in conf('moin-modified-user'):
|
||||||
logger('plugin', 'being "quiet" for %s' % w)
|
log.plugin('being "quiet" for %s' % w)
|
||||||
return {
|
return {
|
||||||
'msg': '/me %s' % random.choice([
|
'msg': '/me %s' % random.choice([
|
||||||
"doesn't say anything at all",
|
"doesn't say anything at all",
|
||||||
@@ -158,7 +158,7 @@ def parse_moin_bye(**args):
|
|||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
logger('plugin', 'sent %s reply for %s' % (
|
log.plugin('sent %s reply for %s' % (
|
||||||
'moin' if direction is moin else 'bye', w
|
'moin' if direction is moin else 'bye', w
|
||||||
))
|
))
|
||||||
return {
|
return {
|
||||||
@@ -178,7 +178,7 @@ def parse_latex(**args):
|
|||||||
@pluginfunction('me-action', 'reacts to /me.*%{bot_user}', ptypes_PARSE)
|
@pluginfunction('me-action', 'reacts to /me.*%{bot_user}', ptypes_PARSE)
|
||||||
def parse_slash_me(**args):
|
def parse_slash_me(**args):
|
||||||
if args['data'].lower().startswith('/me') and (conf('bot_user') in args['data'].lower()):
|
if args['data'].lower().startswith('/me') and (conf('bot_user') in args['data'].lower()):
|
||||||
logger('plugin', 'sent /me reply')
|
log.plugin('sent /me reply')
|
||||||
|
|
||||||
me_replys = [
|
me_replys = [
|
||||||
'are you that rude to everybody?',
|
'are you that rude to everybody?',
|
||||||
@@ -195,7 +195,7 @@ def parse_slash_me(**args):
|
|||||||
#@pluginfunction('dummy_parser', 'dummy_parser desc', ptypes_PARSE)
|
#@pluginfunction('dummy_parser', 'dummy_parser desc', ptypes_PARSE)
|
||||||
#def parse_skynet(**args):
|
#def parse_skynet(**args):
|
||||||
# if 'dummy_parser' in args['data'].lower():
|
# if 'dummy_parser' in args['data'].lower():
|
||||||
# logger('plugin', 'dummy_parser triggered')
|
# log.plugin('dummy_parser triggered')
|
||||||
# return {
|
# return {
|
||||||
# 'msg': 'dummy_parser triggered'
|
# 'msg': 'dummy_parser triggered'
|
||||||
# }
|
# }
|
||||||
@@ -227,7 +227,7 @@ def command_help(argv, **args):
|
|||||||
return
|
return
|
||||||
|
|
||||||
if None == what:
|
if None == what:
|
||||||
logger('plugin', 'empty help request, sent all commands')
|
log.plugin('empty help request, sent all commands')
|
||||||
commands = args['cmd_list']
|
commands = args['cmd_list']
|
||||||
commands.sort()
|
commands.sort()
|
||||||
parsers = args['parser_list']
|
parsers = args['parser_list']
|
||||||
@@ -245,7 +245,7 @@ def command_help(argv, **args):
|
|||||||
for p in plugins[ptypes_COMMAND] + plugins[ptypes_PARSE]:
|
for p in plugins[ptypes_COMMAND] + plugins[ptypes_PARSE]:
|
||||||
if what == p.plugin_name:
|
if what == p.plugin_name:
|
||||||
flag = True
|
flag = True
|
||||||
logger('plugin', 'sent help for %s' % what)
|
log.plugin('sent help for %s' % what)
|
||||||
return {
|
return {
|
||||||
'msg': args['reply_user'] + ': help for %s %s: %s' % (
|
'msg': args['reply_user'] + ': help for %s %s: %s' % (
|
||||||
'parser' if p.plugin_type == ptypes_PARSE else 'command',
|
'parser' if p.plugin_type == ptypes_PARSE else 'command',
|
||||||
@@ -254,7 +254,7 @@ def command_help(argv, **args):
|
|||||||
}
|
}
|
||||||
|
|
||||||
if not flag:
|
if not flag:
|
||||||
logger('plugin', 'no help found for %s' % what)
|
log.plugin('no help found for %s' % what)
|
||||||
return {
|
return {
|
||||||
'msg': args['reply_user'] + ': no such command: %s' % what
|
'msg': args['reply_user'] + ': no such command: %s' % what
|
||||||
}
|
}
|
||||||
@@ -265,7 +265,7 @@ def command_version(argv, **args):
|
|||||||
if 'version' != argv[0]:
|
if 'version' != argv[0]:
|
||||||
return
|
return
|
||||||
|
|
||||||
logger('plugin', 'sent version string')
|
log.plugin('sent version string')
|
||||||
return {
|
return {
|
||||||
'msg': args['reply_user'] + (''': I'm running ''' + VERSION)
|
'msg': args['reply_user'] + (''': I'm running ''' + VERSION)
|
||||||
}
|
}
|
||||||
@@ -275,7 +275,7 @@ def command_klammer(argv, **args):
|
|||||||
if 'klammer' != argv[0]:
|
if 'klammer' != argv[0]:
|
||||||
return
|
return
|
||||||
|
|
||||||
logger('plugin', 'sent karl klammer')
|
log.plugin('sent karl klammer')
|
||||||
return {
|
return {
|
||||||
'msg': (
|
'msg': (
|
||||||
args['reply_user'] + ',',
|
args['reply_user'] + ',',
|
||||||
@@ -293,7 +293,7 @@ def command_unicode(argv, **args):
|
|||||||
if 'unikot' != argv[0]:
|
if 'unikot' != argv[0]:
|
||||||
return
|
return
|
||||||
|
|
||||||
logger('plugin', 'sent some unicode')
|
log.plugin('sent some unicode')
|
||||||
return {
|
return {
|
||||||
'msg': (
|
'msg': (
|
||||||
args['reply_user'] + ''', here's some''',
|
args['reply_user'] + ''', here's some''',
|
||||||
@@ -308,7 +308,7 @@ def command_source(argv, **args):
|
|||||||
if not argv[0] in ('source', 'src'):
|
if not argv[0] in ('source', 'src'):
|
||||||
return
|
return
|
||||||
|
|
||||||
logger('plugin', 'sent source URL')
|
log.plugin('sent source URL')
|
||||||
return {
|
return {
|
||||||
'msg': 'My source code can be found at %s' % conf('src-url')
|
'msg': 'My source code can be found at %s' % conf('src-url')
|
||||||
}
|
}
|
||||||
@@ -344,10 +344,10 @@ def command_dice(argv, **args):
|
|||||||
rnd = 0
|
rnd = 0
|
||||||
if args['reply_user'] in conf('enhanced-random-user'):
|
if args['reply_user'] in conf('enhanced-random-user'):
|
||||||
rnd = 0 # this might confuse users. good.
|
rnd = 0 # this might confuse users. good.
|
||||||
logger('plugin', 'sent random (enhanced)')
|
log.plugin('sent random (enhanced)')
|
||||||
else:
|
else:
|
||||||
rnd = random.randint(1, 6)
|
rnd = random.randint(1, 6)
|
||||||
logger('plugin', 'sent random')
|
log.plugin('sent random')
|
||||||
|
|
||||||
# the \u200b chars ('ZERO WIDTH SPACE') avoid interpreting stuff as smileys
|
# the \u200b chars ('ZERO WIDTH SPACE') avoid interpreting stuff as smileys
|
||||||
# by some strange clients
|
# by some strange clients
|
||||||
@@ -371,7 +371,7 @@ def command_uptime(argv, **args):
|
|||||||
if 1 == conf('request_counter'):
|
if 1 == conf('request_counter'):
|
||||||
plural_request = ''
|
plural_request = ''
|
||||||
|
|
||||||
logger('plugin', 'sent statistics')
|
log.plugin('sent statistics')
|
||||||
return {
|
return {
|
||||||
'msg': args['reply_user'] + (''': happily serving for %d second%s, %d request%s so far.''' % (u, plural_uptime, conf('request_counter'), plural_request))
|
'msg': args['reply_user'] + (''': happily serving for %d second%s, %d request%s so far.''' % (u, plural_uptime, conf('request_counter'), plural_request))
|
||||||
}
|
}
|
||||||
@@ -384,13 +384,13 @@ def command_ping(argv, **args):
|
|||||||
rnd = random.randint(0, 3) # 1:4
|
rnd = random.randint(0, 3) # 1:4
|
||||||
if 0 == rnd:
|
if 0 == rnd:
|
||||||
msg = args['reply_user'] + ''': peng (You're dead now.)'''
|
msg = args['reply_user'] + ''': peng (You're dead now.)'''
|
||||||
logger('plugin', 'sent pong (variant)')
|
log.plugin('sent pong (variant)')
|
||||||
elif 1 == rnd:
|
elif 1 == rnd:
|
||||||
msg = args['reply_user'] + ''': I don't like you, leave me alone.'''
|
msg = args['reply_user'] + ''': I don't like you, leave me alone.'''
|
||||||
logger('plugin', 'sent pong (dontlike)')
|
log.plugin('sent pong (dontlike)')
|
||||||
else:
|
else:
|
||||||
msg = args['reply_user'] + ''': pong'''
|
msg = args['reply_user'] + ''': pong'''
|
||||||
logger('plugin', 'sent pong')
|
log.plugin('sent pong')
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'msg': msg
|
'msg': msg
|
||||||
@@ -401,7 +401,7 @@ def command_info(argv, **args):
|
|||||||
if 'info' != argv[0]:
|
if 'info' != argv[0]:
|
||||||
return
|
return
|
||||||
|
|
||||||
logger('plugin', 'sent long info')
|
log.plugin('sent long info')
|
||||||
return {
|
return {
|
||||||
'msg': args['reply_user'] + (''': I'm a bot, my job is to extract <title> tags from posted URLs. In case I'm annoying or for further questions, please talk to my master %s. I'm rate limited and shouldn't post more than %d messages per %d seconds. To make me exit immediately, highlight me with 'hangup' in the message (emergency only, please). For other commands, highlight me with 'help'.''' % (conf('bot_owner'), conf('hist_max_count'), conf('hist_max_time')))
|
'msg': args['reply_user'] + (''': I'm a bot, my job is to extract <title> tags from posted URLs. In case I'm annoying or for further questions, please talk to my master %s. I'm rate limited and shouldn't post more than %d messages per %d seconds. To make me exit immediately, highlight me with 'hangup' in the message (emergency only, please). For other commands, highlight me with 'help'.''' % (conf('bot_owner'), conf('hist_max_count'), conf('hist_max_time')))
|
||||||
}
|
}
|
||||||
@@ -426,7 +426,7 @@ def command_teatimer(argv, **args):
|
|||||||
ready = time.time() + steep
|
ready = time.time() + steep
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logger('plugin', 'tea timer set to %s' % time.strftime('%F.%T', time.localtime(ready)))
|
log.plugin('tea timer set to %s' % time.strftime('%F.%T', time.localtime(ready)))
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
return {
|
return {
|
||||||
'msg': args['reply_user'] + ': time format error: ' + str(e)
|
'msg': args['reply_user'] + ': time format error: ' + str(e)
|
||||||
@@ -454,12 +454,12 @@ def command_decode(argv, **args):
|
|||||||
|
|
||||||
char = argv[1]
|
char = argv[1]
|
||||||
char_esc = str(char.encode('unicode_escape'))[3:-1]
|
char_esc = str(char.encode('unicode_escape'))[3:-1]
|
||||||
logger('plugin', 'decode called for %s' % char)
|
log.plugin('decode called for %s' % char)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
uni_name = unicodedata.name(char)
|
uni_name = unicodedata.name(char)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger('plugin', 'decode(%s) failed: %s' % (char, str(e)))
|
log.plugin('decode(%s) failed: %s' % (char, str(e)))
|
||||||
return {
|
return {
|
||||||
'msg': args['reply_user'] + ": can't decode %s (%s): %s" % (char, char_esc, str(e))
|
'msg': args['reply_user'] + ": can't decode %s (%s): %s" % (char, char_esc, str(e))
|
||||||
}
|
}
|
||||||
@@ -473,7 +473,7 @@ def command_show_blacklist(argv, **args):
|
|||||||
if 'show-blacklist' != argv[0]:
|
if 'show-blacklist' != argv[0]:
|
||||||
return
|
return
|
||||||
|
|
||||||
logger('plugin', 'sent URL blacklist')
|
log.plugin('sent URL blacklist')
|
||||||
|
|
||||||
argv1 = None if len(argv) < 2 else argv[1]
|
argv1 = None if len(argv) < 2 else argv[1]
|
||||||
|
|
||||||
@@ -581,7 +581,7 @@ def command_remember(argv, **args):
|
|||||||
if 'remember' != argv[0]:
|
if 'remember' != argv[0]:
|
||||||
return
|
return
|
||||||
|
|
||||||
logger('plugin', 'remember plugin called')
|
log.plugin('remember plugin called')
|
||||||
|
|
||||||
if not len(argv) > 1:
|
if not len(argv) > 1:
|
||||||
return {
|
return {
|
||||||
@@ -600,7 +600,7 @@ def command_recall(argv, **args):
|
|||||||
if 'recall' != argv[0]:
|
if 'recall' != argv[0]:
|
||||||
return
|
return
|
||||||
|
|
||||||
logger('plugin', 'recall plugin called')
|
log.plugin('recall plugin called')
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'msg': args['reply_user'] + ': recalling %s' % conf('data_remember')
|
'msg': args['reply_user'] + ': recalling %s' % conf('data_remember')
|
||||||
@@ -615,7 +615,7 @@ def command_plugin_activation(argv, **args):
|
|||||||
if not command in ('enable', 'disable'):
|
if not command in ('enable', 'disable'):
|
||||||
return
|
return
|
||||||
|
|
||||||
logger('plugin', 'plugin activation plugin called')
|
log.plugin('plugin activation plugin called')
|
||||||
|
|
||||||
if None == plugin:
|
if None == plugin:
|
||||||
return {
|
return {
|
||||||
@@ -655,7 +655,7 @@ def command_wp(argv, lang='de', **args):
|
|||||||
if 'wp' != argv[0]:
|
if 'wp' != argv[0]:
|
||||||
return
|
return
|
||||||
|
|
||||||
logger('plugin', 'wp plugin called')
|
log.plugin('wp plugin called')
|
||||||
|
|
||||||
query = ' '.join(argv[1:])
|
query = ' '.join(argv[1:])
|
||||||
|
|
||||||
@@ -678,7 +678,7 @@ def command_wp(argv, lang='de', **args):
|
|||||||
lang, urllib.parse.urlencode(api)
|
lang, urllib.parse.urlencode(api)
|
||||||
)
|
)
|
||||||
|
|
||||||
logger('plugin', 'wp: fetching %s' % apiurl)
|
log.plugin('wp: fetching %s' % apiurl)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = urllib.request.urlopen(apiurl)
|
response = urllib.request.urlopen(apiurl)
|
||||||
@@ -692,7 +692,7 @@ def command_wp(argv, lang='de', **args):
|
|||||||
lang, urllib.parse.quote(linktitle)
|
lang, urllib.parse.quote(linktitle)
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger('plugin', 'wp(%s) failed: %s, %s' % (query, e, traceback.format_exc()))
|
log.plugin('wp(%s) failed: %s, %s' % (query, e, traceback.format_exc()))
|
||||||
return {
|
return {
|
||||||
'msg': args['reply_user'] + ': something failed: %s' % e
|
'msg': args['reply_user'] + ': something failed: %s' % e
|
||||||
}
|
}
|
||||||
@@ -717,7 +717,7 @@ def command_dummy(argv, **args):
|
|||||||
if 'excuse' != argv[0]:
|
if 'excuse' != argv[0]:
|
||||||
return
|
return
|
||||||
|
|
||||||
logger('plugin', 'BOFH plugin called')
|
log.plugin('BOFH plugin called')
|
||||||
|
|
||||||
excuse = random.sample(excuses, 1)[0]
|
excuse = random.sample(excuses, 1)[0]
|
||||||
|
|
||||||
@@ -730,14 +730,14 @@ def command_dummy(argv, **args):
|
|||||||
# if 'dummy' != argv[0]:
|
# if 'dummy' != argv[0]:
|
||||||
# return
|
# return
|
||||||
#
|
#
|
||||||
# logger('plugin', 'dummy plugin called')
|
# log.plugin('dummy plugin called')
|
||||||
#
|
#
|
||||||
# return {
|
# return {
|
||||||
# 'msg': args['reply_user'] + ': dummy plugin called'
|
# 'msg': args['reply_user'] + ': dummy plugin called'
|
||||||
# }
|
# }
|
||||||
|
|
||||||
def else_command(args):
|
def else_command(args):
|
||||||
logger('plugin', 'sent short info')
|
log.plugin('sent short info')
|
||||||
return {
|
return {
|
||||||
'msg': args['reply_user'] + ''': I'm a bot (highlight me with 'info' for more information).'''
|
'msg': args['reply_user'] + ''': I'm a bot (highlight me with 'info' for more information).'''
|
||||||
}
|
}
|
||||||
@@ -756,7 +756,7 @@ def data_parse_commands(msg_obj):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
if 'hangup' in data:
|
if 'hangup' in data:
|
||||||
logger('warn', 'received hangup: ' + data)
|
log.warn('received hangup: ' + data)
|
||||||
got_hangup = True
|
got_hangup = True
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
return None
|
return None
|
||||||
@@ -830,7 +830,7 @@ if debug_enabled():
|
|||||||
except NameError:
|
except NameError:
|
||||||
ratelimit_touch = _ratelimit_touch
|
ratelimit_touch = _ratelimit_touch
|
||||||
|
|
||||||
logger('info', 'debugging enabled')
|
log.info('debugging enabled')
|
||||||
|
|
||||||
def register(func_type):
|
def register(func_type):
|
||||||
'''
|
'''
|
||||||
@@ -848,7 +848,7 @@ def register(func_type):
|
|||||||
and f.plugin_type == func_type
|
and f.plugin_type == func_type
|
||||||
]
|
]
|
||||||
|
|
||||||
logger('info', 'auto registering plugins: %s' % (', '.join(
|
log.info('auto registering plugins: %s' % (', '.join(
|
||||||
f.plugin_name for f in functions
|
f.plugin_name for f in functions
|
||||||
)))
|
)))
|
||||||
|
|
||||||
@@ -859,7 +859,7 @@ def register_plugin(function, func_type):
|
|||||||
try:
|
try:
|
||||||
plugins[func_type].append(function)
|
plugins[func_type].append(function)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger('warn', 'registering %s failed: %s, %s' %
|
log.warn('registering %s failed: %s, %s' %
|
||||||
(function, e, traceback.format_exc()))
|
(function, e, traceback.format_exc()))
|
||||||
|
|
||||||
def register_all():
|
def register_all():
|
||||||
|
|||||||
36
urlbot.py
36
urlbot.py
@@ -21,8 +21,6 @@ except ImportError:
|
|||||||
|
|
||||||
sys.exit(-1)
|
sys.exit(-1)
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from sleekxmpp import ClientXMPP
|
from sleekxmpp import ClientXMPP
|
||||||
|
|
||||||
# rate limiting to 5 messages per 10 minutes
|
# rate limiting to 5 messages per 10 minutes
|
||||||
@@ -32,7 +30,7 @@ hist_flag = True
|
|||||||
parser = None
|
parser = None
|
||||||
|
|
||||||
def fetch_page(url):
|
def fetch_page(url):
|
||||||
logger('info', 'fetching page ' + url)
|
log.info('fetching page ' + url)
|
||||||
try:
|
try:
|
||||||
request = urllib.request.Request(url)
|
request = urllib.request.Request(url)
|
||||||
request.add_header('User-Agent', '''Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.0''')
|
request.add_header('User-Agent', '''Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.0''')
|
||||||
@@ -41,7 +39,7 @@ def fetch_page(url):
|
|||||||
response.close()
|
response.close()
|
||||||
return (0, html_text, response.headers)
|
return (0, html_text, response.headers)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger('warn', 'failed: ' + str(e))
|
log.warn('failed: %s' % e)
|
||||||
return (1, str(e), 'dummy')
|
return (1, str(e), 'dummy')
|
||||||
|
|
||||||
return (-1, None, None)
|
return (-1, None, None)
|
||||||
@@ -50,10 +48,10 @@ def extract_title(url):
|
|||||||
global parser
|
global parser
|
||||||
|
|
||||||
if 'repo/urlbot.git' in url:
|
if 'repo/urlbot.git' in url:
|
||||||
logger('info', 'repo URL found: ' + url)
|
log.info('repo URL found: ' + url)
|
||||||
return (3, 'wee, that looks like my home repo!')
|
return (3, 'wee, that looks like my home repo!')
|
||||||
|
|
||||||
logger('info', 'extracting title from ' + url)
|
log.info('extracting title from ' + url)
|
||||||
|
|
||||||
(code, html_text, headers) = fetch_page(url)
|
(code, html_text, headers) = fetch_page(url)
|
||||||
|
|
||||||
@@ -77,7 +75,7 @@ def extract_title(url):
|
|||||||
try:
|
try:
|
||||||
html_text = html_text.decode(charset)
|
html_text = html_text.decode(charset)
|
||||||
except LookupError:
|
except LookupError:
|
||||||
logger('warn', 'invalid charset in ' + headers['content-type'])
|
log.warn('invalid charset in ' + headers['content-type'])
|
||||||
|
|
||||||
if str != type(html_text):
|
if str != type(html_text):
|
||||||
html_text = str(html_text)
|
html_text = str(html_text)
|
||||||
@@ -92,7 +90,7 @@ def extract_title(url):
|
|||||||
try:
|
try:
|
||||||
expanded_html = parser.unescape(match)
|
expanded_html = parser.unescape(match)
|
||||||
except UnicodeDecodeError as e: # idk why this can happen, but it does
|
except UnicodeDecodeError as e: # idk why this can happen, but it does
|
||||||
logger('warn', 'parser.unescape() expoded here: ' + str(e))
|
log.warn('parser.unescape() expoded here: ' + str(e))
|
||||||
expanded_html = match
|
expanded_html = match
|
||||||
return (0, expanded_html)
|
return (0, expanded_html)
|
||||||
else:
|
else:
|
||||||
@@ -129,7 +127,7 @@ def ratelimit_exceeded(ignored=None): # FIXME: separate counters
|
|||||||
# FIXME: this is very likely broken now
|
# FIXME: this is very likely broken now
|
||||||
send_reply('(rate limited to %d messages in %d seconds, try again at %s)' % (conf('hist_max_count'), conf('hist_max_time'), time.strftime('%T %Z', time.localtime(hist_ts[0] + conf('hist_max_time')))))
|
send_reply('(rate limited to %d messages in %d seconds, try again at %s)' % (conf('hist_max_count'), conf('hist_max_time'), time.strftime('%T %Z', time.localtime(hist_ts[0] + conf('hist_max_time')))))
|
||||||
|
|
||||||
logger('warn', 'rate limiting exceeded: ' + pickle.dumps(hist_ts))
|
log.warn('rate limiting exceeded: ' + pickle.dumps(hist_ts))
|
||||||
return True
|
return True
|
||||||
|
|
||||||
hist_flag = True
|
hist_flag = True
|
||||||
@@ -151,7 +149,7 @@ def extract_url(data, msg_obj):
|
|||||||
for b in conf('url_blacklist'):
|
for b in conf('url_blacklist'):
|
||||||
if not None is re.match(b, url):
|
if not None is re.match(b, url):
|
||||||
flag = True
|
flag = True
|
||||||
logger('info', 'url blacklist match for ' + url)
|
log.info('url blacklist match for ' + url)
|
||||||
break
|
break
|
||||||
|
|
||||||
if flag:
|
if flag:
|
||||||
@@ -185,7 +183,7 @@ def extract_url(data, msg_obj):
|
|||||||
title, random.choice(char), url
|
title, random.choice(char), url
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
logger('info', 'no message sent for non-text %s (%s)' % (url, title))
|
log.info('no message sent for non-text %s (%s)' % (url, title))
|
||||||
continue
|
continue
|
||||||
elif 2 == status:
|
elif 2 == status:
|
||||||
message = 'No title: %s' % url
|
message = 'No title: %s' % url
|
||||||
@@ -193,13 +191,13 @@ def extract_url(data, msg_obj):
|
|||||||
message = title
|
message = title
|
||||||
elif 4 == status:
|
elif 4 == status:
|
||||||
message = 'Bug triggered (%s), invalid URL/domain part: %s' % (title, url)
|
message = 'Bug triggered (%s), invalid URL/domain part: %s' % (title, url)
|
||||||
logger('warn', message)
|
log.warn(message)
|
||||||
else:
|
else:
|
||||||
message = 'some error occurred when fetching %s' % url
|
message = 'some error occurred when fetching %s' % url
|
||||||
|
|
||||||
message = message.replace('\n', '\\n')
|
message = message.replace('\n', '\\n')
|
||||||
|
|
||||||
logger('info', 'adding to out buf: ' + message)
|
log.info('adding to out buf: ' + message)
|
||||||
out.append(message)
|
out.append(message)
|
||||||
ret = True
|
ret = True
|
||||||
|
|
||||||
@@ -215,11 +213,11 @@ def handle_msg(msg_obj):
|
|||||||
return
|
return
|
||||||
|
|
||||||
if sys.argv[0] in content:
|
if sys.argv[0] in content:
|
||||||
logger('info', 'silenced, this is my own log')
|
log.info('silenced, this is my own log')
|
||||||
return
|
return
|
||||||
|
|
||||||
if 'nospoiler' in content:
|
if 'nospoiler' in content:
|
||||||
logger('info', 'no spoiler for: ' + content)
|
log.info('no spoiler for: ' + content)
|
||||||
return
|
return
|
||||||
|
|
||||||
# don't react to itself
|
# don't react to itself
|
||||||
@@ -233,7 +231,7 @@ def handle_msg(msg_obj):
|
|||||||
if arg_user in blob_userpref:
|
if arg_user in blob_userpref:
|
||||||
if 'spoiler' in blob_userpref[arg_user]:
|
if 'spoiler' in blob_userpref[arg_user]:
|
||||||
if not blob_userpref[arg_user]['spoiler']:
|
if not blob_userpref[arg_user]['spoiler']:
|
||||||
logger('info', 'nospoiler from conf')
|
log.info('nospoiler from conf')
|
||||||
nospoiler = True
|
nospoiler = True
|
||||||
|
|
||||||
ret = None
|
ret = None
|
||||||
@@ -263,7 +261,7 @@ class bot(ClientXMPP):
|
|||||||
self.send_presence()
|
self.send_presence()
|
||||||
|
|
||||||
for room in self.rooms:
|
for room in self.rooms:
|
||||||
logger('info', 'joining %s' % room)
|
log.info('joining %s' % room)
|
||||||
self.plugin['xep_0045'].joinMUC(
|
self.plugin['xep_0045'].joinMUC(
|
||||||
room,
|
room,
|
||||||
self.nick,
|
self.nick,
|
||||||
@@ -291,6 +289,8 @@ class bot(ClientXMPP):
|
|||||||
# self.send_presence(pto=room, pstatus=msg)
|
# self.send_presence(pto=room, pstatus=msg)
|
||||||
|
|
||||||
if '__main__' == __name__:
|
if '__main__' == __name__:
|
||||||
|
log.info(VERSION)
|
||||||
|
|
||||||
import plugins
|
import plugins
|
||||||
|
|
||||||
plugins.send_reply = send_reply
|
plugins.send_reply = send_reply
|
||||||
@@ -299,8 +299,6 @@ if '__main__' == __name__:
|
|||||||
|
|
||||||
plugins.register_all()
|
plugins.register_all()
|
||||||
|
|
||||||
print(sys.argv[0] + ' ' + VERSION)
|
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
level=logging.INFO,
|
level=logging.INFO,
|
||||||
format='%(levelname)-8s %(message)s'
|
format='%(levelname)-8s %(message)s'
|
||||||
|
|||||||
Reference in New Issue
Block a user