import requests import logging import yaml import sys import time import shlex import json import re from matrix_client.client import MatrixClient from matrix_client.api import MatrixHttpApi from matrix_client.api import MatrixError, MatrixRequestError class MonkeyBot: txId = 0 def __init__(self, config): self.config = config self.client = MatrixClient(self.config['MATRIX_HOST'], token=self.config['MATRIX_AS_TOKEN'], user_id=self.config['MATRIX_AS_ID']) self.api = MatrixHttpApi(self.config['MATRIX_HOST'], self.config['MATRIX_AS_TOKEN']) def list_rooms(self): rooms = self.client.get_rooms() for rm in rooms: logging.debug(rm) logging.debug(len(rooms)) def on_message(self, event): logging.info("<__on_message__>") logging.debug(event) rooms = self.client.get_rooms() room = rooms[event['room_id']] if event['type'] == 'm.room.message': if event['content']['msgtype'] == 'm.text': argv = shlex.split(event['content']['body']) cmd = argv[0] args = argv[1:] self._parse_cmd(room, event, cmd, args) def _parse_cmd(self, room, event, cmd, args): logging.debug("<__parse_cmd>") logging.debug(event) logging.debug(" " + cmd) logging.debug(args) if cmd.lower() == 'echo': room.send_text(' '.join(args)) elif cmd.lower() == 'help': room.send_text(self._help()) else: reply = "I'm afraid I don't know this.\n" + " ".join(args) room.send_text(self._help()) def _help(self): reply = "The following commands are available.\n\n" reply += "echo " reply += " - Echo some text back.\n" return reply if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) with open("config.yaml", "rb") as config_file: config = yaml.load(config_file) bot = MonkeyBot(config) bot.list_rooms()