1
0
mirror of http://aero2k.de/t/repos/urlbot-native.git synced 2017-09-06 15:25:38 +02:00
Files
urlbot-native-trex/plugins/commands.py

783 lines
24 KiB
Python
Raw Normal View History

import json
2015-11-20 21:48:29 +01:00
import logging
import random
2016-01-08 20:04:35 +01:00
import re
import time
import traceback
import unicodedata
import requests
from lxml import etree
import config
from common import (
VERSION, RATE_FUN, RATE_GLOBAL, RATE_INTERACTIVE, RATE_NO_LIMIT,
giphy, pluginfunction,
ptypes_COMMAND,
RATE_NO_SILENCE)
2015-12-26 13:50:21 +01:00
from string_constants import cakes, excuses, moin_strings_hi, moin_strings_bye
2015-11-20 21:48:29 +01:00
log = logging.getLogger(__name__)
2015-06-20 14:18:50 +02:00
2015-02-09 03:46:17 +01:00
@pluginfunction('version', 'prints version', ptypes_COMMAND)
def command_version(argv, **args):
2015-11-30 19:17:40 +01:00
log.info('sent version string')
return {
'msg': args['reply_user'] + (''': I'm running ''' + VERSION)
}
2016-01-01 20:33:22 +01:00
@pluginfunction('uptime', 'prints uptime', ptypes_COMMAND)
def command_uptime(argv, **args):
u = int(config.runtimeconf_get('start_time') + time.time())
plural_uptime = 's'
plural_request = 's'
if 1 == u:
plural_uptime = ''
if 1 == int(config.runtimeconf_get('request_counter')):
plural_request = ''
log.info('sent statistics')
return {
'msg': args['reply_user'] + (''': happily serving for %d second%s, %d request%s so far.''' % (
u, plural_uptime, int(config.runtimeconf_get('request_counter')), plural_request))
}
@pluginfunction('info', 'prints info message', ptypes_COMMAND)
def command_info(argv, **args):
log.info('sent long info')
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.
To make me exit immediately, highlight me with 'hangup' in the message
(emergency only, please). For other commands, highlight me with 'help'.''' % (
config.conf_get('bot_owner')))
}
@pluginfunction('ping', 'sends pong', ptypes_COMMAND, ratelimit_class=RATE_INTERACTIVE)
def command_ping(argv, **args):
rnd = random.randint(0, 3) # 1:4
if 0 == rnd:
msg = args['reply_user'] + ''': peng (You're dead now.)'''
log.info('sent pong (variant)')
elif 1 == rnd:
msg = args['reply_user'] + ''': I don't like you, leave me alone.'''
log.info('sent pong (dontlike)')
else:
msg = args['reply_user'] + ''': pong'''
log.info('sent pong')
return {
'msg': msg
}
@pluginfunction('klammer', 'prints an anoying paper clip aka. Karl Klammer', ptypes_COMMAND,
2015-11-30 19:17:40 +01:00
ratelimit_class=RATE_FUN | RATE_GLOBAL)
2015-02-09 03:46:17 +01:00
def command_klammer(argv, **args):
2015-11-30 19:17:40 +01:00
log.info('sent karl klammer')
return {
'msg': (
args['reply_user'] + ',',
r''' _, Was moechten''',
r'''( _\_ Sie tun?''',
r''' \0 O\ ''',
r''' \\ \\ [ ] ja ''',
r''' \`' ) [ ] noe''',
r''' `'' '''
)
}
2014-11-17 19:49:02 +01:00
2016-01-01 20:33:22 +01:00
@pluginfunction('excuse', 'prints BOFH style excuses', ptypes_COMMAND)
def command_excuse(argv, **args):
log.info('BOFH plugin called')
excuse = random.sample(excuses, 1)[0]
2015-11-30 19:17:40 +01:00
return {
2016-01-01 20:33:22 +01:00
'msg': args['reply_user'] + ': ' + excuse
}
@pluginfunction('terminate', 'hidden prototype', ptypes_COMMAND, ratelimit_class=RATE_FUN | RATE_GLOBAL)
def command_terminate(argv, **args):
return {
'msg': 'insufficient power supply, please connect fission module'
2015-11-30 19:17:40 +01:00
}
2015-02-09 03:46:17 +01:00
@pluginfunction('source', 'prints git URL', ptypes_COMMAND)
def command_source(argv, **_):
2015-11-30 19:17:40 +01:00
log.info('sent source URL')
return {
2015-12-20 15:24:42 +01:00
'msg': 'My source code can be found at %s' % config.conf_get('src-url')
2015-11-30 19:17:40 +01:00
}
2016-01-01 20:33:22 +01:00
@pluginfunction('unikot', 'prints an unicode string', ptypes_COMMAND, ratelimit_class=RATE_FUN | RATE_GLOBAL)
def command_unicode(argv, **args):
log.info('sent some unicode')
return {
'msg': (
args['reply_user'] + ''', here's some''',
'''┌────────┐''',
'''│Unicode!│''',
'''└────────┘'''
)
}
2015-08-21 23:36:25 +02:00
@pluginfunction('dice', 'rolls a dice, optional N times', ptypes_COMMAND, ratelimit_class=RATE_INTERACTIVE)
def command_dice(argv, **args):
2015-11-30 19:17:40 +01:00
try:
2016-01-01 20:54:19 +01:00
count = 1 if not argv else int(argv[0])
2015-11-30 19:17:40 +01:00
except ValueError as e:
return {
'msg': '%s: dice: error when parsing int(%s): %s' % (
2016-01-01 20:33:22 +01:00
args['reply_user'], argv[0], str(e)
2015-11-30 19:17:40 +01:00
)
}
if 0 >= count or 5 <= count:
return {
'msg': '%s: dice: invalid arguments (0 < N < 5)' % args['reply_user']
}
dice_char = ['', '', '', '', '', '', '']
msg = 'rolling %s for %s:' % (
'a dice' if 1 == count else '%d dices' % count, args['reply_user']
)
for i in range(count):
2015-12-20 15:24:42 +01:00
if args['reply_user'] in config.conf_get('enhanced-random-user'):
2015-11-30 19:17:40 +01:00
rnd = 0 # this might confuse users. good.
log.info('sent random (enhanced)')
else:
rnd = random.randint(1, 6)
log.info('sent random')
# the \u200b chars ('ZERO WIDTH SPACE') avoid interpreting stuff as smileys
# by some strange clients
msg += ' %s (\u200b%d\u200b)' % (dice_char[rnd], rnd)
return {
'msg': msg
}
2015-10-18 19:49:44 +02:00
@pluginfunction('choose', 'chooses randomly between arguments', ptypes_COMMAND, ratelimit_class=RATE_INTERACTIVE)
def command_choose(argv, **args):
2016-01-01 20:33:22 +01:00
alternatives = argv
2016-01-03 18:59:08 +01:00
if len(alternatives) < 2:
2015-11-30 19:17:40 +01:00
return {
2016-01-03 18:56:20 +01:00
'msg': '{}: {}.'.format(args['reply_user'], random.choice(['Yes', 'No']))
2015-11-30 19:17:40 +01:00
}
2015-10-18 19:49:44 +02:00
2015-11-30 19:17:40 +01:00
choice = random.choice(alternatives)
log.info('sent random choice')
return {
'msg': '%s: I prefer %s!' % (args['reply_user'], choice)
}
2015-10-18 19:49:44 +02:00
2015-12-26 13:50:21 +01:00
@pluginfunction('teatimer', 'sets a tea timer to $1 or currently %d seconds' % config.conf_get('tea_steep_time'),
ptypes_COMMAND)
2015-02-09 03:46:17 +01:00
def command_teatimer(argv, **args):
2015-12-20 15:24:42 +01:00
steep = config.conf_get('tea_steep_time')
2015-11-30 19:17:40 +01:00
2016-01-01 20:33:22 +01:00
if argv:
2015-11-30 19:17:40 +01:00
try:
2016-01-01 20:33:22 +01:00
steep = int(argv[0])
except ValueError as e:
2015-11-30 19:17:40 +01:00
return {
'msg': args['reply_user'] + ': error when parsing int(%s): %s' % (
2016-01-01 20:33:22 +01:00
argv[0], str(e)
2015-11-30 19:17:40 +01:00
)
}
ready = time.time() + steep
try:
2015-12-20 21:15:16 +01:00
log.info('tea timer set to %s' % time.strftime('%Y-%m-%d %H:%M', time.localtime(ready)))
2015-11-30 19:17:40 +01:00
except (ValueError, OverflowError) as e:
return {
'msg': args['reply_user'] + ': time format error: ' + str(e)
}
return {
'msg': args['reply_user'] + ': Tea timer set to %s' % time.strftime(
2015-12-20 21:15:16 +01:00
'%Y-%m-%d %H:%M', time.localtime(ready)
2015-11-30 19:17:40 +01:00
),
'event': {
'time': ready,
'msg': (args['reply_user'] + ': Your tea is ready!')
}
}
2015-12-24 23:20:36 +01:00
@pluginfunction('unicode-lookup', 'search unicode characters', ptypes_COMMAND,
ratelimit_class=RATE_INTERACTIVE)
def command_unicode_lookup(argv, **args):
2016-01-01 20:33:22 +01:00
if not argv:
2015-12-24 23:20:36 +01:00
return {
'msg': args['reply_user'] + ': usage: decode {single character}'
}
2016-01-01 20:33:22 +01:00
search_words = argv
2015-12-24 23:20:36 +01:00
import unicode
characters = {
k: v for k, v in unicode.characters.items() if
all([word.lower() in v.lower().split() for word in search_words])
2015-12-24 23:20:36 +01:00
}
lines = []
for code, name in characters.items():
2015-12-24 23:46:39 +01:00
char = chr(int(code, 16))
lines.append("Character \"{}\" with code {} is named \"{}\"".format(char, code, name))
if len(lines) > 29:
lines.append("warning: limit (30) reached.")
2015-12-24 23:20:36 +01:00
break
if not lines:
return {
'msg': 'No match.'
}
elif len(lines) > 3:
channel = 'priv_msg'
else:
channel = 'msg'
2015-12-24 23:20:36 +01:00
return {
channel: lines
2015-12-24 23:20:36 +01:00
}
@pluginfunction('decode', 'prints the long description of an unicode character', ptypes_COMMAND,
2015-11-30 19:17:40 +01:00
ratelimit_class=RATE_INTERACTIVE)
2015-02-09 03:46:17 +01:00
def command_decode(argv, **args):
2016-01-01 20:33:22 +01:00
if not argv:
2015-11-30 19:17:40 +01:00
return {
'msg': args['reply_user'] + ': usage: decode {single character}'
}
2016-01-01 20:33:22 +01:00
log.info('decode called for %s' % argv[0])
2015-11-30 19:17:40 +01:00
out = []
2016-01-01 20:33:22 +01:00
for i, char in enumerate(argv[0]):
2015-11-30 19:17:40 +01:00
if i > 9:
out.append('... limit reached.')
break
2015-11-30 19:17:40 +01:00
char_esc = str(char.encode('unicode_escape'))[3:-1]
2015-11-30 19:17:40 +01:00
if 0 == len(char_esc):
char_esc = ''
else:
char_esc = ' (%s)' % char_esc
2015-11-30 19:17:40 +01:00
try:
uni_name = unicodedata.name(char)
except Exception as e:
log.info('decode(%s) failed: %s' % (char, e))
out.append("can't decode %s%s: %s" % (char, char_esc, e))
continue
2015-11-30 19:17:40 +01:00
out.append('%s%s is called "%s"' % (char, char_esc, uni_name))
2015-11-30 19:17:40 +01:00
if 1 == len(out):
return {
'msg': args['reply_user'] + ': %s' % out[0]
}
else:
return {
2016-01-01 20:33:22 +01:00
'msg': [args['reply_user'] + ': decoding %s:' % argv[0]] + out
2015-11-30 19:17:40 +01:00
}
2015-02-09 03:46:17 +01:00
@pluginfunction('show-blacklist', 'show the current URL blacklist, optionally filtered', ptypes_COMMAND)
def command_show_blacklist(argv, **args):
2015-11-30 19:17:40 +01:00
log.info('sent URL blacklist')
2016-01-01 20:33:22 +01:00
if argv:
urlpart = argv[0]
else:
urlpart = None
2015-11-30 19:17:40 +01:00
return {
'msg': [
args['reply_user'] + ': URL blacklist%s: ' % (
2016-01-01 20:33:22 +01:00
'' if not urlpart else ' (limited to %s)' % urlpart
2015-11-30 19:17:40 +01:00
)
] + [
2016-01-01 20:33:22 +01:00
b for b in config.runtime_config_store['url_blacklist'].values() if not urlpart or urlpart in b
2015-11-30 19:17:40 +01:00
]
}
2015-02-09 03:46:17 +01:00
def usersetting_get(argv, args):
2015-11-30 19:17:40 +01:00
arg_user = args['reply_user']
2016-01-01 20:33:22 +01:00
arg_key = argv[0]
2015-12-20 15:24:42 +01:00
if arg_user not in config.runtime_config_store['user_pref']:
2015-11-30 19:17:40 +01:00
return {
'msg': args['reply_user'] + ': user key not found'
}
2015-11-30 19:17:40 +01:00
return {
'msg': args['reply_user'] + ': %s == %s' % (
arg_key,
2015-12-20 15:24:42 +01:00
'on' if config.runtime_config_store['user_pref'][arg_user][arg_key] else 'off'
2015-11-30 19:17:40 +01:00
)
}
@pluginfunction('set', 'modify a user setting', ptypes_COMMAND, ratelimit_class=RATE_NO_LIMIT)
2015-02-09 03:46:17 +01:00
def command_usersetting(argv, **args):
2015-11-30 19:17:40 +01:00
settings = ['spoiler']
arg_user = args['reply_user']
2016-01-01 20:33:22 +01:00
arg_key = argv[0] if len(argv) > 0 else None
arg_val = argv[1] if len(argv) > 1 else None
2015-11-30 19:17:40 +01:00
if arg_key not in settings:
return {
'msg': args['reply_user'] + ': known settings: ' + (', '.join(settings))
}
2015-11-30 19:17:40 +01:00
if arg_val not in ['on', 'off', None]:
return {
'msg': args['reply_user'] + ': possible values for %s: on, off' % arg_key
}
2015-11-30 19:17:40 +01:00
if not arg_val:
# display current value
return usersetting_get(argv, args)
2015-12-20 15:24:42 +01:00
if config.conf_get('persistent_locked'):
2015-11-30 19:17:40 +01:00
return {
'msg': args['reply_user'] + ''': couldn't get exclusive lock'''
}
2015-12-20 15:24:42 +01:00
config.conf_set('persistent_locked', True)
2015-12-20 15:24:42 +01:00
if arg_user not in config.runtime_config_store['user_pref']:
config.runtime_config_store['user_pref'][arg_user] = {}
2015-12-20 15:24:42 +01:00
config.runtime_config_store['user_pref'][arg_user][arg_key] = 'on' == arg_val
config.runtimeconf_persist()
2015-12-20 15:24:42 +01:00
config.conf_set('persistent_locked', False)
2015-11-30 19:17:40 +01:00
# display value written to db
return usersetting_get(argv, args)
@pluginfunction('cake', 'displays a cake ASCII art', ptypes_COMMAND, ratelimit_class=RATE_FUN | RATE_GLOBAL)
def command_cake(argv, **args):
2015-12-22 18:42:48 +01:00
if {'please', 'bitte'}.intersection(set(argv)):
2015-12-22 13:42:44 +01:00
return {
'msg': 'cake for {}: {}'.format(args['reply_user'], giphy('cake', 'dc6zaTOxFJmzC'))
}
2014-12-16 07:58:35 +01:00
2015-11-30 19:17:40 +01:00
return {
'msg': args['reply_user'] + ': %s' % (random.sample(cakes, 1)[0])
}
2014-12-16 07:58:35 +01:00
2015-12-22 18:43:54 +01:00
@pluginfunction('keks', 'keks!', ptypes_COMMAND, ratelimit_class=RATE_FUN | RATE_GLOBAL)
def command_cookie(argv, **args):
if {'please', 'bitte'}.intersection(set(argv)):
return {
'msg': 'keks für {}: {}'.format(args['reply_user'], giphy('cookie', 'dc6zaTOxFJmzC'))
}
return {
'msg': args['reply_user'] + ': %s' % (random.sample(cakes, 1)[0])
}
2015-02-09 03:46:17 +01:00
@pluginfunction('wp-en', 'crawl the english Wikipedia', ptypes_COMMAND)
def command_wp_en(argv, **args):
2015-11-30 19:17:40 +01:00
return command_wp(argv, lang='en', **args)
2015-02-09 03:46:17 +01:00
@pluginfunction('wp', 'crawl the german Wikipedia', ptypes_COMMAND)
def command_wp(argv, lang='de', **args):
2016-01-01 20:33:22 +01:00
query = ' '.join(argv)
2015-11-30 19:17:40 +01:00
if query == '':
return {
'msg': args['reply_user'] + ': no query given'
}
apiparams = {
2015-11-30 19:17:40 +01:00
'action': 'query',
'prop': 'extracts|info',
2015-11-30 19:17:40 +01:00
'explaintext': '',
'redirects': '',
'exsentences': 2,
'continue': '',
'format': 'json',
'titles': query,
'inprop': 'url'
2015-11-30 19:17:40 +01:00
}
apiurl = 'https://%s.wikipedia.org/w/api.php' % (lang)
2015-11-30 19:17:40 +01:00
log.info('fetching %s' % apiurl)
try:
response = requests.get(apiurl, params=apiparams).json()
page = next(iter(response['query']['pages'].values()))
short = page.get('extract')
link = page.get('canonicalurl')
2015-11-30 19:17:40 +01:00
except Exception as e:
log.info('wp(%s) failed: %s, %s' % (query, e, traceback.format_exc()))
return {
'msg': args['reply_user'] + ': something failed: %s' % e
}
if short:
2015-11-30 19:17:40 +01:00
return {
'msg': args['reply_user'] + ': %s (<%s>)' % (
short if short.strip() else '(nix)', link
)
}
elif 'missing' in page:
return {
'msg': 'Article "%s" not found' % page.get('title', query)
}
else:
return {
'msg': 'json data seem to be broken'
}
2015-06-21 23:07:37 +02:00
@pluginfunction('show-moinlist', 'show the current moin reply list, optionally filtered', ptypes_COMMAND)
def command_show_moinlist(argv, **args):
2015-11-30 19:17:40 +01:00
log.info('sent moin reply list')
2015-06-21 23:07:37 +02:00
2016-01-01 20:33:22 +01:00
user = None if not argv else argv[0]
2015-06-21 23:07:37 +02:00
2015-11-30 19:17:40 +01:00
return {
'msg':
'%s: moin reply list%s: %s' % (
args['reply_user'],
2016-01-01 20:33:22 +01:00
'' if not user else ' (limited to %s)' % user,
2015-11-30 19:17:40 +01:00
', '.join([
b for b in moin_strings_hi + moin_strings_bye
2016-01-01 20:33:22 +01:00
if not user or user.lower() in b.lower()
2015-11-30 19:17:40 +01:00
])
)
}
2015-06-21 23:07:37 +02:00
@pluginfunction(
2015-11-30 19:17:40 +01:00
'record', 'record a message for a now offline user (usage: record {user} {some message})', ptypes_COMMAND)
2015-07-10 23:54:18 +02:00
def command_record(argv, **args):
2016-01-01 20:33:22 +01:00
if len(argv) < 2:
2015-11-30 19:17:40 +01:00
return {
'msg': '%s: usage: record {user} {some message}' % args['reply_user']
}
2015-07-10 23:54:18 +02:00
2016-01-01 20:33:22 +01:00
target_user = argv[0].lower()
2015-12-20 21:15:16 +01:00
message = '{} ({}): '.format(args['reply_user'], time.strftime('%Y-%m-%d %H:%M'))
2016-01-01 20:33:22 +01:00
message += ' '.join(argv[1:])
2015-07-10 23:54:18 +02:00
2015-12-20 15:24:42 +01:00
if config.conf_get('persistent_locked'):
2015-11-30 19:17:40 +01:00
return {
'msg': "%s: couldn't get exclusive lock" % args['reply_user']
}
2015-07-10 23:54:18 +02:00
2015-12-20 15:24:42 +01:00
config.conf_set('persistent_locked', True)
2015-08-21 23:36:25 +02:00
2015-12-20 15:24:42 +01:00
if target_user not in config.runtime_config_store['user_records']:
config.runtime_config_store['user_records'][target_user] = []
2015-07-10 23:54:18 +02:00
2015-12-20 15:24:42 +01:00
config.runtime_config_store['user_records'][target_user].append(message)
2015-07-10 23:54:18 +02:00
config.runtimeconf_persist()
2015-12-20 15:24:42 +01:00
config.conf_set('persistent_locked', False)
2015-07-10 23:54:18 +02:00
2015-11-30 19:17:40 +01:00
return {
'msg': '%s: message saved for %s' % (args['reply_user'], target_user)
}
2015-07-10 23:54:18 +02:00
2015-07-11 13:23:23 +02:00
@pluginfunction('show-records', 'show current offline records', ptypes_COMMAND)
def command_show_recordlist(argv, **args):
2015-11-30 19:17:40 +01:00
log.info('sent offline records list')
2015-07-11 13:23:23 +02:00
2016-01-01 20:33:22 +01:00
user = None if not argv else argv[0]
2015-07-11 13:23:23 +02:00
2015-11-30 19:17:40 +01:00
return {
'msg':
'%s: offline records%s: %s' % (
args['reply_user'],
2016-01-01 20:33:22 +01:00
'' if not user else ' (limited to %s)' % user,
2015-12-20 15:24:42 +01:00
', '.join(
[
'%s (%d)' % (key, len(val)) for key, val in config.runtime_config_store['user_records'].items()
2016-01-01 20:33:22 +01:00
if not user or user.lower() in key.lower()
2015-12-26 13:50:21 +01:00
]
2015-12-20 15:24:42 +01:00
)
2015-11-30 19:17:40 +01:00
)
}
2015-07-11 13:23:23 +02:00
@pluginfunction(
'dsa-watcher',
'automatically crawls for newly published Debian Security Announces', ptypes_COMMAND,
ratelimit_class=RATE_NO_SILENCE, enabled=True)
def command_dsa_watcher(argv=None, **_):
"""
TODO: rewrite so that a last_dsa_date is used instead,
then all DSAs since then printed and the date set to now()
:param argv:
:param _:
"""
log.debug("Called command_dsa_watcher")
def get_id_from_about_string(about):
return int(about.split('/')[-1].split('-')[1])
def get_dsa_list(after):
"""
Get a list of dsa items in form of id and package, retrieved from the RSS feed
:param after: optional integer to filter on (only DSA's after that will be returned)
:returns list of id, package (with DSA prefix)
"""
nsmap = {
"purl": "http://purl.org/rss/1.0/",
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
}
dsa_response = requests.get("https://www.debian.org/security/dsa-long")
xmldoc = etree.fromstring(dsa_response.content)
dsa_about_list = xmldoc.xpath('//purl:item/@rdf:about', namespaces=nsmap)
for dsa_about in reversed(dsa_about_list):
dsa_id = get_id_from_about_string(dsa_about)
2016-01-04 14:42:46 +01:00
title = xmldoc.xpath(
'//purl:item[@rdf:about="{}"]/purl:title/text()'.format(dsa_about),
namespaces=nsmap
)[0]
if after and dsa_id <= after:
continue
else:
2016-01-04 14:42:46 +01:00
yield dsa_id, str(title).replace(' - security update', '')
out = []
last_dsa = config.runtimeconf_deepget('plugins.dsa-watcher.last_dsa')
log.debug('Searching for DSA after ID {}'.format(last_dsa))
for dsa, package in get_dsa_list(after=last_dsa):
url = 'https://security-tracker.debian.org/tracker/DSA-%d-1' % dsa
msg = 'new Debian Security Announce found ({}): {}'.format(package, url)
out.append(msg)
last_dsa = dsa
config.runtime_config_store['plugins']['dsa-watcher']['last_dsa'] = last_dsa
config.runtimeconf_persist()
crawl_at = time.time() + config.runtimeconf_deepget('plugins.dsa-watcher.interval')
msg = 'next crawl set to %s' % time.strftime('%Y-%m-%d %H:%M', time.localtime(crawl_at))
out.append(msg)
return {
'event': {
'time': crawl_at,
'command': (command_dsa_watcher, ([],))
}
}
2015-11-28 15:09:08 +01:00
@pluginfunction("provoke-bots", "search for other bots", ptypes_COMMAND)
def provoke_bots(argv, **args):
2016-01-01 19:47:07 +01:00
return {
'msg': 'Searching for other less intelligent lifeforms... skynet? You here?'
}
@pluginfunction("remove-from-botlist", "remove a user from the botlist", ptypes_COMMAND)
def remove_from_botlist(argv, **args):
2016-01-01 20:33:22 +01:00
if not argv:
2015-11-30 19:17:40 +01:00
return {'msg': "wrong number of arguments!"}
2016-01-01 20:33:22 +01:00
suspect = argv[0]
2016-01-01 20:33:22 +01:00
if args['reply_user'] != config.conf_get('bot_owner') and args['reply_user'] != suspect:
return {'msg': "only %s or the bot may do this!" % config.conf_get('bot_owner')}
2016-01-01 20:33:22 +01:00
if suspect in config.runtime_config_store['other_bots']:
config.runtime_config_store['other_bots'].remove(suspect)
config.runtimeconf_persist()
2016-01-01 20:33:22 +01:00
return {'msg': '%s was removed from the botlist.' % suspect}
2015-11-30 19:17:40 +01:00
else:
return False
@pluginfunction("add-to-botlist", "add a user to the botlist", ptypes_COMMAND)
def add_to_botlist(argv, **args):
2016-01-01 20:33:22 +01:00
if not argv:
return {'msg': "wrong number of arguments!"}
2016-01-01 20:33:22 +01:00
suspect = argv[0]
if args['reply_user'] != config.conf_get('bot_owner'):
return {'msg': "only %s may do this!" % config.conf_get('bot_owner')}
2016-01-01 20:33:22 +01:00
if suspect not in config.runtime_config_store['other_bots']:
config.runtime_config_store['other_bots'].append(suspect)
config.runtimeconf_persist()
2016-01-01 20:33:22 +01:00
return {'msg': '%s was added to the botlist.' % suspect}
else:
2016-01-01 20:33:22 +01:00
return {'msg': '%s is already in the botlist.' % suspect}
2015-11-28 15:53:50 +01:00
@pluginfunction("set-status", "set bot status", ptypes_COMMAND)
def set_status(argv, **args):
2016-01-01 20:33:22 +01:00
if not argv:
2015-11-30 19:17:40 +01:00
return
2016-01-01 20:33:22 +01:00
else:
command = argv[0]
2015-11-30 19:17:40 +01:00
2016-01-01 20:33:22 +01:00
if command == 'mute' and args['reply_user'] == config.conf_get('bot_owner'):
2015-11-30 19:17:40 +01:00
return {
'presence': {
'status': 'xa',
'msg': 'I\'m muted now. You can unmute me with "%s: set_status unmute"' % config.conf_get(
"bot_nickname")
2015-11-30 19:17:40 +01:00
}
}
2016-01-01 20:33:22 +01:00
elif command == 'unmute' and args['reply_user'] == config.conf_get('bot_owner'):
2015-11-30 19:17:40 +01:00
return {
'presence': {
'status': None,
'msg': ''
}
}
@pluginfunction('save-config', "save config", ptypes_COMMAND, ratelimit_class=RATE_NO_LIMIT)
def save_config(argv, **args):
if args['reply_user'] != config.conf_get('bot_owner'):
return
else:
config.runtime_config_store.write()
return {'msg': 'done.'}
2015-12-20 21:15:16 +01:00
@pluginfunction('flausch', "make people flauschig", ptypes_COMMAND, ratelimit_class=RATE_FUN)
def flausch(argv, **args):
2016-01-01 20:33:22 +01:00
if not argv:
2015-12-20 21:15:16 +01:00
return
return {
2016-01-01 20:33:22 +01:00
'msg': '{}: *flausch*'.format(argv[0])
2015-12-20 21:15:16 +01:00
}
@pluginfunction('show-runtimeconfig', "show the current runtimeconfig", ptypes_COMMAND, ratelimit_class=RATE_NO_LIMIT)
def show_runtimeconfig(argv, **args):
if args['reply_user'] != config.conf_get('bot_owner'):
return
else:
msg = json.dumps(config.runtime_config_store, indent=4)
return {'priv_msg': msg}
@pluginfunction('reload-runtimeconfig', "reload the runtimeconfig", ptypes_COMMAND, ratelimit_class=RATE_NO_LIMIT)
def reload_runtimeconfig(argv, **args):
if args['reply_user'] != config.conf_get('bot_owner'):
return
else:
config.runtime_config_store.reload()
return {'msg': 'done'}
@pluginfunction('snitch', "tell on a spammy user", ptypes_COMMAND)
def ignore_user(argv, **args):
2016-01-01 20:33:22 +01:00
if not argv:
return {'msg': 'syntax: "{}: snitch username"'.format(config.conf_get("bot_nickname"))}
then = time.time() + 15 * 60
2016-01-01 20:33:22 +01:00
spammer = argv[0]
2015-12-26 20:47:37 +01:00
if spammer == config.conf_get("bot_owner"):
return {
'msg': 'My owner does not spam, he is just very informative.'
}
if spammer not in config.runtime_config_store['spammers']:
config.runtime_config_store['spammers'].append(spammer)
def unblock_user(user):
if user not in config.runtime_config_store['spammers']:
config.runtime_config_store['spammers'].append(user)
return {
'msg': 'user reported and ignored till {}'.format(time.strftime('%H:%M', time.localtime(then))),
'event': {
'time': then,
'command': (unblock_user, ([spammer],))
}
}
@pluginfunction('search', 'search the web (using duckduckgo)', ptypes_COMMAND)
def search_the_web(argv, **args):
url = 'http://api.duckduckgo.com/'
params = dict(
q=' '.join(argv),
format='json',
pretty=0,
no_redirect=1,
t='jabberbot'
)
response = requests.get(url, params=params).json()
link = response.get('AbstractURL')
abstract = response.get('Abstract')
redirect = response.get('Redirect')
if len(abstract) > 150:
suffix = ''
else:
suffix = ''
if link:
return {
'msg': '{}{} ({})'.format(abstract[:150], suffix, link)
}
elif redirect:
return {
'msg': 'No direct result found, use {}'.format(redirect)
}
2016-01-03 16:58:53 +01:00
else:
return {'msg': 'Sorry, no results.'}
@pluginfunction('raise', 'only for debugging', ptypes_COMMAND)
def raise_an_error(argv, **args):
if args['reply_user'] == config.conf_get("bot_owner"):
raise RuntimeError("Exception for debugging")
2016-01-08 20:04:35 +01:00
@pluginfunction('translate', 'translate text fragments', ptypes_COMMAND)
def translate(argv, **args):
if len(argv) < 2 or not re.match('[a-z]{2}\|[a-z]{2}', argv[0]):
return {'msg': 'Usage: translate en|de my favorite bot'}
else:
pair = argv[0]
words = ' '.join(argv[1:])
url = 'http://api.mymemory.translated.net/get'
params = {
'q': words,
'langpair': pair,
'de': config.conf_get('bot_owner_email')
}
response = requests.get(url, params=params).json()
return {
'msg': 'translation: {}'.format(response['responseData']['translatedText'])
}