#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import os import re import signal import subprocess import sys import time import sleekxmpp opts = { "muc": "room@conference.example.com", "nick": "botname", "jid": "botname@example.com", "resource": "resource", "password": "password", "connect": "xmpp.example.org:5222", } class Zhobe: def __init__(self, opts): if sys.version_info.major < 3: sleekxmpp.util.misc_ops.setdefaultencoding("utf-8") self.client = sleekxmpp.ClientXMPP("%s/%s" % (opts["jid"], opts["resource"]), opts["password"]) self.client.register_plugin("xep_0199") # XMPP Ping. self.client.register_plugin("xep_0045") # XMPP MUC. self.jid = opts["jid"] self.connect = opts["connect"] self.muc = opts["muc"] self.pure_nick = opts["nick"] self.nick = self.pure_nick def register_handlers(self): self.client.add_event_handler("session_start", self.on_session_start) self.client.add_event_handler("message", self.on_message, threaded=True) self.client.add_event_handler("muc::%s::presence" % self.muc, self.on_presence) def join_muc(self): muc_plugin = self.client.plugin["xep_0045"] if self.muc in muc_plugin.getJoinedRooms(): muc_plugin.leaveMUC(self.muc, self.nick, msg="Replaced by new connection") muc_plugin.joinMUC(self.muc, self.nick, wait=True) @classmethod def log_exception(cls, ex): logging.error("%s: %s" % (type(ex).__name__, str(ex))) @classmethod def log_message_event(cls, event): logging.debug("&{{jabber:client message} %s %s %s %s %s { }}" % (event["from"], event["id"], event["to"], event["type"], event["body"])) def is_muc_admin(self, muc, nick): muc_plugin = self.client.plugin["xep_0045"] if nick not in muc_plugin.rooms[self.muc]: return False affiliation = muc_plugin.getJidProperty(muc, nick, "affiliation") return True if affiliation in ("admin", "owner") else False _trim_regexp = re.compile("(`|\\$|\\.\\.)") _quote_regexp = re.compile("(\"|')") @classmethod def trim(cls, s): result = cls._trim_regexp.sub("", s) result = cls._quote_regexp.sub("“", result).strip() return result # letter(ASCII or cyrillic), number, underscore only. _cmd_validator_regexp = re.compile("^!(\\w|\\p{Cyrillic})*$") def parse_command(self, body, dir_path, nick, is_admin=False): cmd = body.split(" ", 1) cmd[0] = cmd[0].strip() is_admin = "true" if is_admin else "false" if not self._cmd_validator_regexp.match(cmd[0]): return None, "Bad command \"%s\"" % cmd[0] path = "%s/%s" % (dir_path, self.trim(cmd[0][1:])) if not os.access(path, os.F_OK): return None, "\"%s\" does not exist" % path if not os.path.isfile(path): return None, "\"%s\" is not a file" % path if not os.access(path, os.R_OK | os.X_OK): return None, "\"%s\" is not readable or executable" % path proc_args = [path, self.trim(nick), is_admin] if len(cmd) > 1: proc_args.append(self.trim(cmd[1])) return proc_args, None def exec_command(self, body, dir_path, from_id, nick, is_admin=False): cmd, err = self.parse_command(body, dir_path, nick, is_admin=is_admin) if err is not None: logging.error("Command: %s" % err) self.client.send_message(mto=self.muc, mbody="%s: WAT" % nick, mtype="groupchat") if is_admin: self.client.send_message(mto=from_id, mbody=err, mtype="chat") return try: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) cmd_out, cmd_outerr = proc.communicate() except subprocess.CalledProcessError as err: logging.error("Execute: %s" % str(err)) self.client.send_message(mto=self.muc, mbody="%s: WAT" % nick, mtype="groupchat") if is_admin: self.client.send_message(mto=from_id, mbody=str(err), mtype="chat") return if cmd_outerr and len(cmd_outerr) > 0: logging.error("Process: %s" % cmd_outerr.strip()) if is_admin: self.client.send_message(mto=from_id, mbody=cmd_outerr.strip(), mtype="chat") if cmd_out and len(cmd_out) > 0: self.client.send_message(mto=self.muc, mbody=cmd_out.strip(), mtype="groupchat") def on_session_start(self, event): self.client.get_roster() self.client.send_presence(pstatus="is there some food in this world?", ppriority=12) self.join_muc() def handle_self_message(self, body, nick, from_id): if not body.startswith("!"): self.client.send_message(mto=self.muc, mbody=body, mtype="groupchat") return self.exec_command(body, "./plugins", from_id, nick, is_admin=True) def handle_muc_message(self, body, nick, from_id): muc_plugin = self.client.plugin["xep_0045"] is_admin = self.is_muc_admin(self.muc, nick) # Has to be redone with the current bot nick. call_regexp = re.compile("^%s[:,]" % self.nick) if body == "!megakick": self.client.send_message(mto=self.muc, mbody="%s: WAT" % nick, mtype="groupchat") elif body.startswith("!megakick "): victim = body.split("!megakick ", 1)[1] is_bot_admin = self.is_muc_admin(self.muc, self.nick) is_victim_admin = self.is_muc_admin(self.muc, victim) if is_admin and victim != self.nick: if is_bot_admin and not is_victim_admin and \ victim in muc_plugin.rooms[self.muc]: muc_plugin.setRole(self.muc, victim, "none") else: self.client.send_message(mto=self.muc, mbody="%s: Can't megakick %s." % (nick, victim), mtype="groupchat") else: self.client.send_message(mto=self.muc, mbody="%s: GTFO" % nick, mtype="groupchat") elif body.startswith("!"): # Any external command. self.exec_command(body, "./plugins", from_id, nick, is_admin=is_admin) elif call_regexp.match(body): # Chat. cmd_body = call_regexp.sub("!answer", body) self.exec_command(cmd_body, "./chat", from_id, nick, is_admin=is_admin) def on_message(self, event): try: if not event["type"] in ("chat", "normal", "groupchat"): return self.log_message_event(event) body = event["body"] from_id = event["from"] if event["type"] == "groupchat": nick = event["mucnick"] self.handle_muc_message(body, nick, from_id) elif event["from"].bare == self.jid: # Use resource as a nickname with self messages. nick = from_id.resource self.handle_self_message(body, nick, from_id) except Exception as e: self.log_exception(e) def on_presence(self, event): muc_plugin = self.client.plugin["xep_0045"] try: typ = event["muc"]["type"] from_id = event["from"] nick = event["muc"]["nick"] if not typ: typ = event["type"] if not nick: nick = muc_plugin.getNick(self.muc, from_id) if typ == "error": if event["error"]["code"] == "409": self.nick = self.nick + "_" self.join_muc() elif typ == "unavailable": if nick == self.nick: self.nick = self.pure_nick time.sleep(0.5) self.join_muc() except Exception as e: self.log_exception(e) def run(self): # Reset the nick. self.nick = self.pure_nick if self.connect: connect = self.connect.split(":", 1) if len(connect) != 2 or not connect[1].isdigit(): logging.critical("Conn: Connection server format is " + "invalid, should be example.org:5222") sys.exit(1) else: connect = () if self.client.connect(connect): self.register_handlers() self.client.process(block=True) else: logging.critical("Auth: Could not connect to server, or " + "password mismatch!") sys.exit(1) if __name__ == "__main__": signal.signal(signal.SIGINT, signal.SIG_DFL) logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S") # Silence sleekxmpp debug information. logging.getLogger("sleekxmpp").setLevel(logging.CRITICAL) zhobe = Zhobe(opts) while True: zhobe.run() logging.error("Unknown: WTF am I doing here?") time.sleep(0.5)