2021-01-10 13:10:39 +00:00
|
|
|
"""XMPP bots for humans."""
|
|
|
|
|
2021-01-16 15:38:12 +00:00
|
|
|
import re
|
2021-01-14 21:26:13 +00:00
|
|
|
from argparse import ArgumentParser
|
2021-01-10 13:10:39 +00:00
|
|
|
from configparser import ConfigParser
|
2021-01-14 22:45:23 +00:00
|
|
|
from datetime import datetime as dt
|
2021-01-10 13:10:39 +00:00
|
|
|
from getpass import getpass
|
2021-01-15 10:08:07 +00:00
|
|
|
from imghdr import what
|
2021-01-16 12:05:30 +00:00
|
|
|
from inspect import cleandoc
|
2021-01-23 22:29:58 +00:00
|
|
|
from json import dumps, loads
|
2021-01-14 18:18:27 +00:00
|
|
|
from logging import DEBUG, INFO, basicConfig, getLogger
|
2021-01-17 20:20:52 +00:00
|
|
|
from os import environ
|
2021-01-10 13:10:39 +00:00
|
|
|
from os.path import exists
|
|
|
|
from pathlib import Path
|
2021-01-14 21:26:13 +00:00
|
|
|
from sys import exit, stdout
|
2021-01-10 13:10:39 +00:00
|
|
|
|
2021-01-14 22:45:23 +00:00
|
|
|
from humanize import naturaldelta
|
2021-01-10 13:10:39 +00:00
|
|
|
from slixmpp import ClientXMPP
|
|
|
|
|
|
|
|
|
2021-01-24 11:46:22 +00:00
|
|
|
class SimpleDatabase(dict):
|
|
|
|
"""A simple database.
|
|
|
|
|
|
|
|
It is a dictionary which saves to disk on all writes. It is optimised for
|
|
|
|
ease of hacking and accessibility and not for performance or efficiency.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, filename, *args, **kwargs):
|
|
|
|
"""Initialise the object."""
|
|
|
|
self.filename = Path(filename).absolute()
|
|
|
|
self._loads()
|
|
|
|
self.update(*args, **kwargs)
|
|
|
|
|
|
|
|
def _loads(self):
|
|
|
|
"""Load the database."""
|
|
|
|
if not exists(self.filename):
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
with open(self.filename, "r") as handle:
|
|
|
|
self.update(loads(handle.read()))
|
|
|
|
except Exception as exception:
|
|
|
|
message = f"Loading file storage failed: {exception}"
|
|
|
|
self.log.debug(message)
|
|
|
|
exit(1)
|
|
|
|
|
|
|
|
def _dumps(self):
|
|
|
|
"""Save the databse to disk."""
|
|
|
|
try:
|
|
|
|
with open(self.filename, "w") as handle:
|
|
|
|
handle.write(dumps(self))
|
|
|
|
except Exception as exception:
|
|
|
|
message = f"Saving file storage failed: {exception}"
|
|
|
|
self.log.debug(message)
|
|
|
|
exit(1)
|
|
|
|
|
|
|
|
def __setitem__(self, key, val):
|
|
|
|
"""Write data to the database."""
|
|
|
|
dict.__setitem__(self, key, val)
|
|
|
|
self._dumps()
|
|
|
|
|
|
|
|
def __delitem__(self, key):
|
|
|
|
"""Remove data from the database."""
|
|
|
|
dict.__delitem__(key)
|
|
|
|
self._dumps()
|
|
|
|
|
|
|
|
def update(self, *args, **kwargs):
|
|
|
|
"""Update the database."""
|
|
|
|
for k, v in dict(*args, **kwargs).items():
|
|
|
|
self[k] = v
|
|
|
|
self._dumps()
|
|
|
|
|
|
|
|
|
2021-01-13 13:00:59 +00:00
|
|
|
class SimpleMessage:
|
2021-01-10 13:49:22 +00:00
|
|
|
"""A simple message interface."""
|
|
|
|
|
2021-01-16 15:38:12 +00:00
|
|
|
def __init__(self, message, bot):
|
|
|
|
"""Initialise the object."""
|
2021-01-10 13:49:22 +00:00
|
|
|
self.message = message
|
2021-01-16 15:38:12 +00:00
|
|
|
self.bot = bot
|
2021-01-10 13:49:22 +00:00
|
|
|
|
|
|
|
@property
|
2021-01-16 15:38:12 +00:00
|
|
|
def text(self):
|
|
|
|
"""The entire message text."""
|
2021-01-10 13:49:22 +00:00
|
|
|
return self.message["body"]
|
|
|
|
|
2021-01-16 15:38:12 +00:00
|
|
|
@property
|
|
|
|
def content(self):
|
|
|
|
"""The content of the message received.
|
|
|
|
|
|
|
|
This implementation aims to match and extract the content of the
|
|
|
|
messages directed at bots in group chats. So, for example, when sending
|
|
|
|
messages like so.
|
|
|
|
|
|
|
|
echobot: hi
|
|
|
|
echobot, hi
|
|
|
|
echobot hi
|
|
|
|
|
|
|
|
The result produced by `message.content` will always be "hi". This
|
|
|
|
makes it easier to work with various commands and avoid messy parsing
|
|
|
|
logic in end-user implementations.
|
|
|
|
"""
|
|
|
|
body = self.message["body"]
|
|
|
|
|
|
|
|
try:
|
2021-01-16 16:46:50 +00:00
|
|
|
match = fr"^{self.bot.nick}.?(\s)"
|
2021-01-16 15:38:12 +00:00
|
|
|
split = re.split(match, body)
|
|
|
|
filtered = list(filter(None, split))
|
|
|
|
return filtered[-1].strip()
|
|
|
|
except Exception as exception:
|
|
|
|
self.bot.log.error(f"Couldn't parse {body}: {exception}")
|
|
|
|
return None
|
|
|
|
|
2021-01-10 13:49:22 +00:00
|
|
|
@property
|
2021-01-13 13:51:23 +00:00
|
|
|
def sender(self):
|
2021-01-16 15:38:12 +00:00
|
|
|
"""The sender of the message."""
|
2021-01-13 13:42:26 +00:00
|
|
|
return self.message["from"]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def room(self):
|
2021-01-16 15:38:12 +00:00
|
|
|
"""The room from which the message originated."""
|
2021-01-10 15:51:20 +00:00
|
|
|
return self.message["from"].bare
|
2021-01-10 13:49:22 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def receiver(self):
|
2021-01-16 15:38:12 +00:00
|
|
|
"""The receiver of the message."""
|
2021-01-10 13:49:22 +00:00
|
|
|
return self.message["to"]
|
|
|
|
|
2021-01-10 15:31:17 +00:00
|
|
|
@property
|
|
|
|
def type(self):
|
2021-01-16 15:38:12 +00:00
|
|
|
"""The type of the message."""
|
2021-01-10 15:31:17 +00:00
|
|
|
return self.message["type"]
|
|
|
|
|
2021-01-16 15:38:12 +00:00
|
|
|
@property
|
|
|
|
def nick(self):
|
|
|
|
"""The nick of the message."""
|
|
|
|
return self.message["mucnick"]
|
|
|
|
|
2021-01-17 19:49:57 +00:00
|
|
|
@property
|
|
|
|
def url(self):
|
|
|
|
"""The URL of a sent file."""
|
|
|
|
return self.message["oob"]["url"]
|
|
|
|
|
2021-01-10 13:49:22 +00:00
|
|
|
|
2021-01-14 21:26:13 +00:00
|
|
|
class Config:
|
|
|
|
"""Bot file configuration."""
|
|
|
|
|
2021-01-14 21:36:03 +00:00
|
|
|
def __init__(self, name, config):
|
2021-01-16 15:38:12 +00:00
|
|
|
"""Initialise the object."""
|
2021-01-14 21:36:03 +00:00
|
|
|
self.name = name
|
2021-01-14 21:26:13 +00:00
|
|
|
self.config = config
|
2021-01-14 21:36:03 +00:00
|
|
|
self.section = config[self.name] if self.name in config else {}
|
2021-01-14 21:26:13 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def account(self):
|
2021-01-16 15:38:12 +00:00
|
|
|
"""The account of the bot."""
|
2021-01-14 21:26:13 +00:00
|
|
|
return self.section.get("account", None)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def password(self):
|
2021-01-16 15:38:12 +00:00
|
|
|
"""The password of the bot account."""
|
2021-01-14 21:26:13 +00:00
|
|
|
return self.section.get("password", None)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def nick(self):
|
2021-01-16 15:38:12 +00:00
|
|
|
"""The nickname of the bot."""
|
2021-01-14 21:26:13 +00:00
|
|
|
return self.section.get("nick", None)
|
|
|
|
|
2021-01-16 19:30:08 +00:00
|
|
|
@property
|
|
|
|
def avatar(self):
|
|
|
|
"""The avatar of the bot."""
|
|
|
|
return self.section.get("avatar", None)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def redis_url(self):
|
|
|
|
"""The Redis connection URL."""
|
|
|
|
return self.section.get("redis_url", None)
|
|
|
|
|
2021-01-16 20:16:22 +00:00
|
|
|
@property
|
|
|
|
def rooms(self):
|
|
|
|
"""A list of rooms to automatically join."""
|
|
|
|
rooms = self.section.get("rooms", None)
|
2021-01-16 20:46:22 +00:00
|
|
|
|
|
|
|
if rooms is None:
|
|
|
|
return None
|
|
|
|
|
2021-01-19 19:39:51 +00:00
|
|
|
return [room.strip() for room in rooms.split(",")]
|
2021-01-16 20:16:22 +00:00
|
|
|
|
2021-01-16 20:46:22 +00:00
|
|
|
@property
|
|
|
|
def no_auto_join(self):
|
|
|
|
"""Disable auto-join when invited."""
|
|
|
|
return self.section.get("no_auto_join", None)
|
|
|
|
|
2021-01-17 14:09:34 +00:00
|
|
|
@property
|
|
|
|
def port(self):
|
|
|
|
"""The port to serve from."""
|
|
|
|
return self.section.get("port", None)
|
|
|
|
|
2021-01-17 19:18:04 +00:00
|
|
|
@property
|
|
|
|
def template(self):
|
|
|
|
"""The Jinja template to render."""
|
|
|
|
return self.section.get("template", None)
|
|
|
|
|
2021-01-23 20:40:12 +00:00
|
|
|
@property
|
|
|
|
def serve(self):
|
|
|
|
"""Turn on the web server."""
|
|
|
|
return self.section.get("serve", None)
|
|
|
|
|
2021-01-23 22:29:58 +00:00
|
|
|
@property
|
|
|
|
def storage(self):
|
|
|
|
"""Choice of storage back-end."""
|
|
|
|
return self.section.get("storage", None)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def storage_file(self):
|
|
|
|
"""Path to the file based storage back-end."""
|
|
|
|
return self.section.get("storage_file", None)
|
|
|
|
|
2021-01-14 21:26:13 +00:00
|
|
|
|
2021-01-10 13:10:39 +00:00
|
|
|
class Bot(ClientXMPP):
|
2021-01-14 21:26:13 +00:00
|
|
|
"""XMPP bots for humans."""
|
|
|
|
|
2021-01-16 15:38:12 +00:00
|
|
|
DIRECT_MESSAGE_TYPES = ("chat", "normal")
|
|
|
|
GROUP_MESSAGE_TYPES = ("groupchat", "normal")
|
|
|
|
|
2021-01-10 13:10:39 +00:00
|
|
|
def __init__(self):
|
2021-01-16 15:38:12 +00:00
|
|
|
"""Initialise the object."""
|
2021-01-14 21:36:03 +00:00
|
|
|
self.name = type(self).__name__.lower()
|
2021-01-14 22:45:23 +00:00
|
|
|
self.start = dt.now()
|
2021-01-14 21:36:03 +00:00
|
|
|
self.CONFIG_FILE = f"{self.name}.conf"
|
|
|
|
|
2021-01-12 20:39:50 +00:00
|
|
|
self.parse_arguments()
|
2021-01-13 22:19:06 +00:00
|
|
|
self.setup_logging()
|
2021-01-10 13:10:39 +00:00
|
|
|
self.read_config()
|
|
|
|
self.init_bot()
|
|
|
|
self.register_xmpp_event_handlers()
|
|
|
|
self.register_xmpp_plugins()
|
2021-01-23 22:29:58 +00:00
|
|
|
self.init_storage()
|
2021-01-10 13:10:39 +00:00
|
|
|
self.run()
|
|
|
|
|
2021-01-12 20:39:50 +00:00
|
|
|
def parse_arguments(self):
|
|
|
|
"""Parse command-line arguments."""
|
2021-01-14 21:26:13 +00:00
|
|
|
self.parser = ArgumentParser(description="XMPP bots for humans")
|
|
|
|
|
2021-01-13 22:19:06 +00:00
|
|
|
self.parser.add_argument(
|
|
|
|
"-d",
|
|
|
|
"--debug",
|
2021-01-23 20:40:45 +00:00
|
|
|
help="enable verbose debug logs",
|
2021-01-13 22:19:06 +00:00
|
|
|
action="store_const",
|
|
|
|
dest="log_level",
|
|
|
|
const=DEBUG,
|
|
|
|
default=INFO,
|
|
|
|
)
|
2021-01-14 21:26:13 +00:00
|
|
|
self.parser.add_argument(
|
|
|
|
"-a",
|
|
|
|
"--account",
|
|
|
|
dest="account",
|
2021-01-23 20:40:45 +00:00
|
|
|
help="account for the bot account",
|
2021-01-14 21:26:13 +00:00
|
|
|
)
|
|
|
|
self.parser.add_argument(
|
|
|
|
"-p",
|
|
|
|
"--password",
|
|
|
|
dest="password",
|
2021-01-23 20:40:45 +00:00
|
|
|
help="password for the bot account",
|
2021-01-14 21:26:13 +00:00
|
|
|
)
|
|
|
|
self.parser.add_argument(
|
|
|
|
"-n",
|
|
|
|
"--nick",
|
|
|
|
dest="nick",
|
2021-01-23 20:40:45 +00:00
|
|
|
help="nickname for the bot account",
|
2021-01-14 21:26:13 +00:00
|
|
|
)
|
2021-01-15 10:08:07 +00:00
|
|
|
self.parser.add_argument(
|
2021-01-23 20:40:45 +00:00
|
|
|
"-av", "--avatar", dest="avatar", help="avatar for the bot account"
|
2021-01-15 10:08:07 +00:00
|
|
|
)
|
2021-01-16 19:21:22 +00:00
|
|
|
self.parser.add_argument(
|
2021-01-16 20:04:16 +00:00
|
|
|
"-ru",
|
2021-01-16 19:21:22 +00:00
|
|
|
"--redis-url",
|
|
|
|
dest="redis_url",
|
2021-01-23 20:40:45 +00:00
|
|
|
help="redis storage connection URL",
|
2021-01-16 19:21:22 +00:00
|
|
|
)
|
2021-01-16 20:16:22 +00:00
|
|
|
self.parser.add_argument(
|
|
|
|
"-r",
|
|
|
|
"--rooms",
|
|
|
|
dest="rooms",
|
|
|
|
nargs="+",
|
2021-01-23 20:40:45 +00:00
|
|
|
help="rooms to automatically join",
|
2021-01-16 20:16:22 +00:00
|
|
|
)
|
2021-01-16 20:46:22 +00:00
|
|
|
self.parser.add_argument(
|
2021-01-23 20:40:45 +00:00
|
|
|
"-naj",
|
2021-01-16 20:46:22 +00:00
|
|
|
"--no-auto-join",
|
|
|
|
default=False,
|
|
|
|
action="store_true",
|
|
|
|
dest="no_auto_join",
|
2021-01-23 20:40:45 +00:00
|
|
|
help="disable automatically joining rooms when invited",
|
2021-01-16 20:46:22 +00:00
|
|
|
)
|
2021-01-17 14:09:34 +00:00
|
|
|
self.parser.add_argument(
|
|
|
|
"-pt",
|
|
|
|
"--port",
|
|
|
|
dest="port",
|
2021-01-23 20:40:45 +00:00
|
|
|
help="the port to serve from",
|
2021-01-17 14:09:34 +00:00
|
|
|
)
|
2021-01-17 19:18:04 +00:00
|
|
|
self.parser.add_argument(
|
|
|
|
"-t",
|
|
|
|
"--template",
|
|
|
|
dest="template",
|
2021-01-23 20:40:12 +00:00
|
|
|
help="the template to render",
|
|
|
|
)
|
|
|
|
self.parser.add_argument(
|
|
|
|
"-s",
|
|
|
|
"--serve",
|
|
|
|
default=False,
|
|
|
|
action="store_true",
|
|
|
|
dest="serve",
|
|
|
|
help="turn on the web server",
|
2021-01-17 19:18:04 +00:00
|
|
|
)
|
2021-01-23 22:29:58 +00:00
|
|
|
self.parser.add_argument(
|
|
|
|
"-st",
|
|
|
|
"--storage",
|
|
|
|
dest="storage",
|
|
|
|
help="choice of storage back-end",
|
|
|
|
choices=("file", "redis"),
|
|
|
|
)
|
|
|
|
self.parser.add_argument(
|
|
|
|
"-stf",
|
|
|
|
"--storage-file",
|
|
|
|
dest="storage_file",
|
|
|
|
help="path to file based storage back-end",
|
|
|
|
)
|
2021-01-14 21:26:13 +00:00
|
|
|
|
2021-01-12 20:39:50 +00:00
|
|
|
self.args = self.parser.parse_args()
|
|
|
|
|
2021-01-13 22:19:06 +00:00
|
|
|
def setup_logging(self):
|
|
|
|
"""Arrange logging for the bot."""
|
|
|
|
basicConfig(
|
|
|
|
level=self.args.log_level, format="%(levelname)-8s %(message)s"
|
|
|
|
)
|
2021-01-14 18:18:27 +00:00
|
|
|
self.log = getLogger(__name__)
|
2021-01-13 22:19:06 +00:00
|
|
|
|
2021-01-10 13:10:39 +00:00
|
|
|
def read_config(self):
|
|
|
|
"""Read configuration for running bot."""
|
2021-01-14 21:26:13 +00:00
|
|
|
config = ConfigParser()
|
2021-01-12 20:39:50 +00:00
|
|
|
|
2021-01-10 13:10:39 +00:00
|
|
|
config_file_path = Path(self.CONFIG_FILE).absolute()
|
2021-01-14 21:26:13 +00:00
|
|
|
|
|
|
|
if not exists(config_file_path) and stdout.isatty():
|
2021-01-15 13:32:01 +00:00
|
|
|
self.log.info(f"Did not find {config_file_path}")
|
2021-01-12 20:39:50 +00:00
|
|
|
self.generate_config_interactively()
|
2021-01-10 13:10:39 +00:00
|
|
|
|
2021-01-12 20:39:50 +00:00
|
|
|
if exists(config_file_path):
|
2021-01-14 21:26:13 +00:00
|
|
|
config.read(config_file_path)
|
2021-01-10 13:10:39 +00:00
|
|
|
|
2021-01-14 21:36:03 +00:00
|
|
|
self.config = Config(self.name, config)
|
2021-01-10 13:10:39 +00:00
|
|
|
|
2021-01-12 20:39:50 +00:00
|
|
|
def generate_config_interactively(self):
|
2021-01-10 13:10:39 +00:00
|
|
|
"""Generate bot configuration."""
|
2021-01-16 21:06:01 +00:00
|
|
|
print(
|
2021-01-23 20:11:00 +00:00
|
|
|
"Please enter the XMPP user account of your bot",
|
|
|
|
"This is often referred to as the JID (Jabber ID)",
|
|
|
|
"An example: echobot@vvvvvvaria.org",
|
|
|
|
"See https://xmpp-servers.404.city to make an account",
|
2021-01-16 21:06:01 +00:00
|
|
|
sep="\n",
|
|
|
|
)
|
2021-01-14 21:26:13 +00:00
|
|
|
account = input("Account: ")
|
2021-01-16 21:06:01 +00:00
|
|
|
|
|
|
|
print("Please enter the password for your bot account")
|
2021-01-14 21:26:13 +00:00
|
|
|
password = getpass("Password: ")
|
2021-01-23 20:11:00 +00:00
|
|
|
|
|
|
|
print(
|
|
|
|
"Please enter the nickname for your bot",
|
|
|
|
"Others will use this name to refer to the bot",
|
|
|
|
sep="\n",
|
|
|
|
)
|
|
|
|
nick = input("Nickname: ")
|
|
|
|
|
|
|
|
print(
|
|
|
|
"Please list the rooms you want your bot to automatically join",
|
|
|
|
"An example: room1@muc.example.com, room2@muc.example.com",
|
|
|
|
"If your bot only responds to direct messages, leave it blank",
|
|
|
|
sep="\n",
|
|
|
|
)
|
|
|
|
rooms = input("Rooms: ")
|
|
|
|
|
|
|
|
if rooms:
|
|
|
|
rooms = [r.strip() for r in rooms.split(",")]
|
|
|
|
|
|
|
|
inputs = {
|
|
|
|
"account": account,
|
|
|
|
"password": password,
|
|
|
|
"nick": nick,
|
|
|
|
"rooms": rooms,
|
|
|
|
}
|
|
|
|
self.log.debug(f"Received {inputs} as input")
|
2021-01-16 21:06:01 +00:00
|
|
|
|
2021-01-10 13:10:39 +00:00
|
|
|
config = ConfigParser()
|
2021-01-23 20:11:00 +00:00
|
|
|
config[self.name] = inputs
|
2021-01-10 13:10:39 +00:00
|
|
|
|
2021-01-14 21:36:03 +00:00
|
|
|
with open(self.CONFIG_FILE, "w") as file_handle:
|
2021-01-10 13:10:39 +00:00
|
|
|
config.write(file_handle)
|
2021-01-16 21:06:01 +00:00
|
|
|
self.log.info(f"Generated {self.CONFIG_FILE}")
|
2021-01-10 13:10:39 +00:00
|
|
|
|
|
|
|
def init_bot(self):
|
|
|
|
"""Initialise bot with connection details."""
|
2021-01-14 21:26:13 +00:00
|
|
|
account = (
|
|
|
|
self.args.account
|
|
|
|
or self.config.account
|
|
|
|
or environ.get("XBOT_ACCOUNT", None)
|
|
|
|
)
|
|
|
|
password = (
|
|
|
|
self.args.password
|
|
|
|
or self.config.password
|
|
|
|
or environ.get("XBOT_PASSWORD", None)
|
|
|
|
)
|
|
|
|
nick = (
|
|
|
|
self.args.nick or self.config.nick or environ.get("XBOT_NICK", None)
|
|
|
|
)
|
2021-01-16 18:59:09 +00:00
|
|
|
avatar = (
|
|
|
|
self.args.avatar
|
|
|
|
or self.config.avatar
|
|
|
|
or environ.get("XBOT_AVATAR", None)
|
2021-01-16 19:24:03 +00:00
|
|
|
or "avatar.png"
|
2021-01-16 18:59:09 +00:00
|
|
|
)
|
2021-01-16 19:21:22 +00:00
|
|
|
redis_url = (
|
|
|
|
self.args.redis_url
|
|
|
|
or self.config.redis_url
|
|
|
|
or environ.get("XBOT_REDIS_URL", None)
|
|
|
|
)
|
2021-01-16 20:16:22 +00:00
|
|
|
rooms = (
|
|
|
|
self.args.rooms
|
|
|
|
or self.config.rooms
|
|
|
|
or environ.get("XBOT_ROOMS", None)
|
|
|
|
)
|
2021-01-16 20:46:22 +00:00
|
|
|
no_auto_join = (
|
|
|
|
self.args.no_auto_join
|
|
|
|
or self.config.no_auto_join
|
|
|
|
or environ.get("XBOT_NO_AUTO_JOIN", None)
|
|
|
|
)
|
2021-01-17 14:09:34 +00:00
|
|
|
port = (
|
|
|
|
self.args.port
|
|
|
|
or self.config.port
|
|
|
|
or environ.get("XBOT_PORT", None)
|
|
|
|
or "8080"
|
|
|
|
)
|
2021-01-17 19:18:04 +00:00
|
|
|
template = (
|
|
|
|
self.args.template
|
|
|
|
or self.config.template
|
|
|
|
or environ.get("XBOT_TEMPLATE", None)
|
|
|
|
or "index.html.j2"
|
|
|
|
)
|
2021-01-24 12:27:39 +00:00
|
|
|
serve_web = (
|
2021-01-23 20:40:12 +00:00
|
|
|
self.args.serve
|
|
|
|
or self.config.serve
|
|
|
|
or environ.get("XBOT_SERVE", None)
|
|
|
|
)
|
2021-01-23 22:29:58 +00:00
|
|
|
storage = (
|
|
|
|
self.args.storage
|
|
|
|
or self.config.storage
|
|
|
|
or environ.get("XBOT_STORAGE", None)
|
|
|
|
or "file"
|
|
|
|
)
|
|
|
|
storage_file = (
|
|
|
|
self.args.storage_file
|
|
|
|
or self.config.storage_file
|
|
|
|
or environ.get("XBOT_STORAGE_FILE", None)
|
|
|
|
or f"{nick}.json"
|
|
|
|
)
|
2021-01-14 21:26:13 +00:00
|
|
|
|
|
|
|
if not account:
|
|
|
|
self.log.error("Unable to discover account")
|
|
|
|
exit(1)
|
|
|
|
if not password:
|
|
|
|
self.log.error("Unable to discover password")
|
|
|
|
exit(1)
|
|
|
|
if not nick:
|
|
|
|
self.log.error("Unable to discover nick")
|
|
|
|
exit(1)
|
|
|
|
|
|
|
|
ClientXMPP.__init__(self, account, password)
|
|
|
|
|
|
|
|
self.account = account
|
|
|
|
self.password = password
|
|
|
|
self.nick = nick
|
2021-01-16 18:59:09 +00:00
|
|
|
self.avatar = avatar
|
2021-01-16 19:21:22 +00:00
|
|
|
self.redis_url = redis_url
|
2021-01-16 20:16:22 +00:00
|
|
|
self.rooms = rooms
|
2021-01-16 20:46:22 +00:00
|
|
|
self.no_auto_join = no_auto_join
|
2021-01-17 14:09:34 +00:00
|
|
|
self.port = port
|
2021-01-24 12:27:39 +00:00
|
|
|
self.serve_web = serve_web
|
|
|
|
|
|
|
|
self.template = None
|
|
|
|
if self.serve_web:
|
|
|
|
self.template = self.load_template(template)
|
|
|
|
|
2021-01-23 22:29:58 +00:00
|
|
|
self.storage = storage
|
|
|
|
self.storage_file = Path(storage_file).absolute()
|
2021-01-17 19:18:04 +00:00
|
|
|
|
|
|
|
def load_template(self, template):
|
|
|
|
"""Load template via Jinja."""
|
|
|
|
if not exists(Path(template).absolute()):
|
|
|
|
return None
|
|
|
|
|
2021-01-23 22:56:07 +00:00
|
|
|
try:
|
|
|
|
from jinja2 import Environment, FileSystemLoader
|
|
|
|
except ModuleNotFoundError:
|
|
|
|
print("Missing required dependency: jinja2")
|
|
|
|
print("Have you tried `pip install xbotlib[web]`")
|
|
|
|
exit(1)
|
|
|
|
|
2021-01-17 19:18:04 +00:00
|
|
|
try:
|
|
|
|
loader = FileSystemLoader(searchpath="./")
|
|
|
|
env = Environment(loader=loader)
|
|
|
|
return env.get_template(template)
|
|
|
|
except Exception:
|
|
|
|
self.log.info(f"Unable to load {template}")
|
2021-01-15 10:08:07 +00:00
|
|
|
|
2021-01-10 13:10:39 +00:00
|
|
|
def register_xmpp_event_handlers(self):
|
|
|
|
"""Register functions against specific XMPP event handlers."""
|
|
|
|
self.add_event_handler("session_start", self.session_start)
|
2021-01-13 21:49:52 +00:00
|
|
|
self.add_event_handler("groupchat_invite", self.group_invite)
|
2021-01-13 20:56:45 +00:00
|
|
|
self.add_event_handler("message", self.direct_message)
|
|
|
|
self.add_event_handler("groupchat_message", self.group_message)
|
2021-01-15 11:57:25 +00:00
|
|
|
self.add_event_handler("message_error", self.error_message)
|
|
|
|
|
|
|
|
def error_message(self, message):
|
2021-01-16 15:38:12 +00:00
|
|
|
message = SimpleMessage(message, self)
|
|
|
|
self.log.error(f"Received error message: {message.text}")
|
2021-01-10 13:10:39 +00:00
|
|
|
|
2021-01-13 20:56:45 +00:00
|
|
|
def direct_message(self, message):
|
2021-01-16 15:38:12 +00:00
|
|
|
"""Handle direct message events."""
|
|
|
|
message = SimpleMessage(message, self)
|
2021-01-14 22:45:23 +00:00
|
|
|
|
2021-01-16 15:38:12 +00:00
|
|
|
if message.type not in self.DIRECT_MESSAGE_TYPES:
|
|
|
|
return
|
2021-01-14 22:45:23 +00:00
|
|
|
|
2021-01-16 15:38:12 +00:00
|
|
|
if message.text.startswith("@"):
|
2021-01-16 19:33:53 +00:00
|
|
|
if self.command(message, to=message.sender):
|
|
|
|
return
|
2021-01-16 12:09:41 +00:00
|
|
|
|
2021-01-24 11:46:22 +00:00
|
|
|
if not hasattr(self, "direct"):
|
|
|
|
self.log.info(f"Bot.direct not implemented for {self.nick}")
|
|
|
|
return
|
|
|
|
|
2021-01-16 12:09:41 +00:00
|
|
|
try:
|
2021-01-16 15:38:12 +00:00
|
|
|
self.direct(message)
|
2021-01-24 11:46:22 +00:00
|
|
|
except Exception as exception:
|
|
|
|
self.log.info(f"Bot.direct threw exception {exception}")
|
|
|
|
|
|
|
|
if self.storage == "file":
|
|
|
|
self.db._dumps()
|
2021-01-10 13:10:39 +00:00
|
|
|
|
2021-01-13 21:49:52 +00:00
|
|
|
def session_start(self, message):
|
2021-01-10 13:10:39 +00:00
|
|
|
"""Handle session_start event."""
|
|
|
|
self.send_presence()
|
|
|
|
self.get_roster()
|
2021-01-15 10:08:07 +00:00
|
|
|
self.publish_avatar()
|
2021-01-16 20:16:22 +00:00
|
|
|
self.join_rooms()
|
2021-01-15 10:08:07 +00:00
|
|
|
|
|
|
|
def publish_avatar(self):
|
|
|
|
"""Publish bot avatar."""
|
|
|
|
try:
|
|
|
|
abspath = Path(self.avatar).absolute()
|
|
|
|
with open(abspath, "rb") as handle:
|
|
|
|
contents = handle.read()
|
|
|
|
except IOError:
|
|
|
|
self.log.info(f"No avatar discovered (tried '{abspath}')")
|
|
|
|
return
|
|
|
|
|
|
|
|
id = self.plugin["xep_0084"].generate_id(contents)
|
|
|
|
info = {
|
|
|
|
"id": id,
|
|
|
|
"type": f"image/{what('', contents)}",
|
|
|
|
"bytes": len(contents),
|
|
|
|
}
|
|
|
|
|
|
|
|
self.plugin["xep_0084"].publish_avatar(contents)
|
|
|
|
self.plugin["xep_0084"].publish_avatar_metadata(items=[info])
|
2021-01-10 13:10:39 +00:00
|
|
|
|
2021-01-16 20:16:22 +00:00
|
|
|
def join_rooms(self):
|
|
|
|
"""Automatically join rooms if specified."""
|
2021-01-16 20:46:22 +00:00
|
|
|
if self.rooms is None:
|
|
|
|
return
|
|
|
|
|
2021-01-16 20:16:22 +00:00
|
|
|
for room in self.rooms:
|
|
|
|
self.plugin["xep_0045"].join_muc(room, self.config.nick)
|
|
|
|
self.log.info(f"Joining {room} automatically")
|
|
|
|
|
2021-01-13 21:49:52 +00:00
|
|
|
def group_invite(self, message):
|
|
|
|
"""Accept invites to group chats."""
|
2021-01-16 20:46:22 +00:00
|
|
|
room = message["from"]
|
|
|
|
|
|
|
|
if self.no_auto_join:
|
|
|
|
return self.log.info(f"Not joining {room} (disabled)")
|
|
|
|
|
|
|
|
self.plugin["xep_0045"].join_muc(room, self.config.nick)
|
|
|
|
self.log.info(f"Joining {room} as invited")
|
2021-01-10 15:31:17 +00:00
|
|
|
|
2021-01-13 20:56:45 +00:00
|
|
|
def group_message(self, message):
|
2021-01-16 15:38:12 +00:00
|
|
|
"""Handle group chat message events."""
|
|
|
|
message = SimpleMessage(message, self)
|
2021-01-14 22:45:23 +00:00
|
|
|
|
2021-01-18 19:48:01 +00:00
|
|
|
if "@" in message.text:
|
|
|
|
if self.meta(message, room=message.room):
|
|
|
|
return
|
2021-01-16 12:09:41 +00:00
|
|
|
|
2021-01-16 15:38:12 +00:00
|
|
|
miss = message.type not in self.GROUP_MESSAGE_TYPES
|
|
|
|
loop = message.nick == self.nick
|
2021-01-18 10:13:25 +00:00
|
|
|
other = self.nick not in message.text and not message.url
|
2021-01-16 12:17:55 +00:00
|
|
|
|
2021-01-18 10:13:25 +00:00
|
|
|
if miss or other or loop:
|
2021-01-16 15:38:12 +00:00
|
|
|
return
|
2021-01-15 14:05:49 +00:00
|
|
|
|
2021-01-18 19:48:01 +00:00
|
|
|
if "@" in message.content:
|
2021-01-16 19:33:53 +00:00
|
|
|
if self.command(message, room=message.room):
|
|
|
|
return
|
2021-01-14 22:45:23 +00:00
|
|
|
|
2021-01-24 11:46:22 +00:00
|
|
|
if not hasattr(self, "group"):
|
|
|
|
self.log.info(f"Bot.group not implemented for {self.nick}")
|
|
|
|
return
|
|
|
|
|
2021-01-16 12:09:41 +00:00
|
|
|
try:
|
2021-01-16 15:38:12 +00:00
|
|
|
self.group(message)
|
2021-01-24 11:46:22 +00:00
|
|
|
except Exception as exception:
|
|
|
|
self.log.info(f"Bot.group threw exception: {exception}")
|
|
|
|
|
|
|
|
if self.storage == "file":
|
|
|
|
self.db._dumps()
|
2021-01-10 13:10:39 +00:00
|
|
|
|
|
|
|
def register_xmpp_plugins(self):
|
|
|
|
"""Register XMPP plugins that the bot supports."""
|
|
|
|
self.register_plugin("xep_0030") # Service Discovery
|
|
|
|
self.register_plugin("xep_0045") # Multi-User Chat
|
|
|
|
self.register_plugin("xep_0199") # XMPP Ping
|
2021-01-15 10:08:07 +00:00
|
|
|
self.register_plugin("xep_0084") # User Avatar
|
2021-01-17 19:49:57 +00:00
|
|
|
self.register_plugin("xep_0066") # Proces URIs (files, images)
|
2021-01-15 10:08:07 +00:00
|
|
|
|
2021-01-24 11:48:04 +00:00
|
|
|
if not hasattr(self, "plugins"):
|
|
|
|
self.log.info("No additional plugins loaded")
|
|
|
|
return
|
|
|
|
|
2021-01-16 19:37:25 +00:00
|
|
|
try:
|
|
|
|
for plugin in self.plugins:
|
|
|
|
self.register_plugin(plugin)
|
2021-01-16 20:48:33 +00:00
|
|
|
self.log.info(f"Loaded {plugin}")
|
2021-01-24 11:48:04 +00:00
|
|
|
except Exception as exception:
|
|
|
|
message = f"Loading additional plugins failed {exception}"
|
|
|
|
self.log.info(message)
|
2021-01-16 19:37:25 +00:00
|
|
|
|
2021-01-23 22:29:58 +00:00
|
|
|
def init_storage(self):
|
|
|
|
"""Initialise the storage back-end."""
|
|
|
|
if self.storage == "file":
|
|
|
|
try:
|
2021-01-24 11:46:22 +00:00
|
|
|
self.db = SimpleDatabase(self.storage_file)
|
2021-01-23 22:29:58 +00:00
|
|
|
self.log.info("Successfully loaded file storage")
|
|
|
|
except Exception as exception:
|
|
|
|
message = f"Failed to load {self.storage_file}: {exception}"
|
|
|
|
self.log.info(message)
|
|
|
|
exit(1)
|
|
|
|
else:
|
|
|
|
try:
|
2021-01-23 22:56:07 +00:00
|
|
|
from redis import Redis
|
|
|
|
|
2021-01-23 22:29:58 +00:00
|
|
|
self.db = Redis.from_url(self.redis_url, decode_responses=True)
|
|
|
|
return self.log.info("Successfully connected to Redis storage")
|
|
|
|
except ValueError as exception:
|
|
|
|
message = f"Failed to connect to Redis storage: {exception}"
|
|
|
|
self.log.info(message)
|
|
|
|
exit(1)
|
2021-01-23 22:56:07 +00:00
|
|
|
except ModuleNotFoundError:
|
|
|
|
print("missing required dependency using Redis")
|
|
|
|
print("Have you tried `pip install xbotlib[redis]`")
|
|
|
|
exit(1)
|
2021-01-15 20:14:04 +00:00
|
|
|
|
2021-01-10 13:10:39 +00:00
|
|
|
def run(self):
|
|
|
|
"""Run the bot."""
|
|
|
|
self.connect()
|
2021-01-10 14:37:10 +00:00
|
|
|
|
|
|
|
try:
|
2021-01-24 12:27:39 +00:00
|
|
|
if self.serve_web:
|
|
|
|
self.log.info("Running the web server")
|
|
|
|
self.run_web_server()
|
2021-01-24 12:00:47 +00:00
|
|
|
|
|
|
|
if hasattr(self, "setup"):
|
|
|
|
try:
|
|
|
|
self.setup()
|
2021-01-24 12:27:39 +00:00
|
|
|
self.log.info("Finished running setup")
|
2021-01-24 12:00:47 +00:00
|
|
|
except Exception as exception:
|
|
|
|
message = f"Bot.setup failed: {exception}"
|
|
|
|
self.log.info(message)
|
|
|
|
|
2021-01-17 11:52:46 +00:00
|
|
|
self.process(forever=False)
|
2021-01-17 13:38:37 +00:00
|
|
|
except (KeyboardInterrupt, RuntimeError):
|
2021-01-24 11:46:22 +00:00
|
|
|
pass
|
2021-01-10 13:49:22 +00:00
|
|
|
|
2021-01-24 12:27:39 +00:00
|
|
|
def run_web_server(self):
|
|
|
|
"""Run the web server."""
|
2021-01-23 22:55:46 +00:00
|
|
|
try:
|
|
|
|
from aiohttp.web import Application, get, run_app
|
|
|
|
except ModuleNotFoundError:
|
|
|
|
print("Missing required dependency: aiohttp")
|
|
|
|
print("Have you tried `pip install xbotlib[web]`")
|
|
|
|
exit(1)
|
|
|
|
|
2021-01-17 13:38:37 +00:00
|
|
|
self.web = Application()
|
|
|
|
|
2021-01-24 12:27:39 +00:00
|
|
|
if hasattr(self, "serve"):
|
2021-01-17 13:38:37 +00:00
|
|
|
self.web.add_routes([get("/", self.serve)])
|
2021-01-24 12:27:39 +00:00
|
|
|
else:
|
2021-01-17 13:38:37 +00:00
|
|
|
self.web.add_routes([get("/", self.default_serve)])
|
|
|
|
|
2021-01-24 12:11:47 +00:00
|
|
|
try:
|
|
|
|
self.routes()
|
|
|
|
self.log.info("Registered additional web routes")
|
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
|
2021-01-17 14:09:34 +00:00
|
|
|
self.log.info(f"Serving on http://0.0.0.0:{self.port}")
|
|
|
|
run_app(self.web, port=self.port, print=None)
|
2021-01-17 13:38:37 +00:00
|
|
|
|
|
|
|
async def default_serve(self, request):
|
|
|
|
"""Default placeholder text for HTML serving."""
|
2021-01-23 22:56:07 +00:00
|
|
|
try:
|
|
|
|
from aiohttp.web import Response
|
|
|
|
except ModuleNotFoundError:
|
|
|
|
print("Missing required dependency: aiohttp")
|
|
|
|
print("Have you tried `pip install xbotlib[web]`")
|
|
|
|
exit(1)
|
|
|
|
|
2021-01-17 13:38:37 +00:00
|
|
|
return Response(text=f"{self.nick} is alive and well")
|
|
|
|
|
2021-01-16 15:38:12 +00:00
|
|
|
def reply(self, text, to=None, room=None):
|
2021-01-10 18:17:10 +00:00
|
|
|
"""Send back a reply."""
|
|
|
|
if to is None and room is None:
|
2021-01-16 11:50:29 +00:00
|
|
|
self.log.error("`to` or `room` arguments required for `reply`")
|
2021-01-14 21:44:48 +00:00
|
|
|
exit(1)
|
2021-01-10 18:17:10 +00:00
|
|
|
|
|
|
|
if to is not None and room is not None:
|
2021-01-14 21:44:48 +00:00
|
|
|
self.log.error("Cannot send to both `to` and `room` for `reply`")
|
|
|
|
exit(1)
|
2021-01-10 18:17:10 +00:00
|
|
|
|
2021-01-16 15:38:12 +00:00
|
|
|
kwargs = {"mbody": text}
|
2021-01-10 18:17:10 +00:00
|
|
|
if to is not None:
|
|
|
|
kwargs["mto"] = to
|
|
|
|
kwargs["mtype"] = "chat"
|
|
|
|
else:
|
|
|
|
kwargs["mto"] = room
|
|
|
|
kwargs["mtype"] = "groupchat"
|
|
|
|
|
|
|
|
self.send_message(**kwargs)
|
2021-01-16 19:33:53 +00:00
|
|
|
return True
|
2021-01-10 18:29:34 +00:00
|
|
|
|
2021-01-14 22:45:23 +00:00
|
|
|
@property
|
|
|
|
def uptime(self):
|
|
|
|
"""Time since the bot came up."""
|
|
|
|
return naturaldelta(self.start - dt.now())
|
|
|
|
|
2021-01-16 15:38:12 +00:00
|
|
|
def meta(self, message, **kwargs):
|
|
|
|
"""Handle meta command invocations."""
|
2021-01-18 19:48:01 +00:00
|
|
|
if "@bots" in message.text:
|
2021-01-16 19:33:53 +00:00
|
|
|
return self.reply("🖐️", **kwargs)
|
2021-01-16 15:38:12 +00:00
|
|
|
|
2021-01-16 12:14:42 +00:00
|
|
|
def command(self, message, **kwargs):
|
|
|
|
"""Handle command invocations."""
|
2021-01-18 19:48:01 +00:00
|
|
|
if "@uptime" in message.content:
|
2021-01-16 19:33:53 +00:00
|
|
|
return self.reply(self.uptime, **kwargs)
|
2021-01-18 19:48:01 +00:00
|
|
|
elif "@help" in message.content:
|
2021-01-14 22:45:23 +00:00
|
|
|
try:
|
2021-01-16 19:33:53 +00:00
|
|
|
return self.reply(cleandoc(self.help), **kwargs)
|
2021-01-14 22:45:23 +00:00
|
|
|
except AttributeError:
|
2021-01-16 19:33:53 +00:00
|
|
|
return self.reply("No help found 🤔️", **kwargs)
|
2021-01-19 07:29:56 +00:00
|
|
|
|
|
|
|
def respond(self, response, content_type="text/html"):
|
|
|
|
"""Send this response back with the web server."""
|
2021-01-23 22:56:07 +00:00
|
|
|
try:
|
|
|
|
from aiohttp.web import Response
|
|
|
|
except ModuleNotFoundError:
|
|
|
|
print("Missing required dependency: aiohttp")
|
|
|
|
print("Have you tried `pip install xbotlib[web]`")
|
|
|
|
exit(1)
|
|
|
|
|
2021-01-21 18:21:02 +00:00
|
|
|
return Response(text=response, content_type=content_type)
|