import requests import logging import yaml import sys import time import shlex import json import re from pnutlib import Pnut from matrix_client.client import MatrixClient from matrix_client.api import MatrixHttpApi from matrix_client.api import MatrixError, MatrixRequestError from models import * class MonkeyBot: txId = 0 def __init__(self): with open("config.yaml", "rb") as config_file: self.config = yaml.load(config_file) 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() logging.info(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() == 'help': room.send_text(self._help()) elif cmd.lower() == 'set_access_token': token = args[0] r = Pnut(token).get_user('me') if r.status_code == 200: rdata = json.loads(r.text) pnutid = rdata["data"]["username"] user = MatrixUser(matrix_id=event['user_id'], room_id=event['room_id'], pnut_id=pnutid, pnut_token=token) db.session.add(user) db.session.commit() reply = "Token verified, you are now linked as " + pnutid else: reply = "There was an error validating the account." room.send_text(reply) elif cmd.lower() == 'drop_access_token': user = MatrixUser.query.filter_by(matrix_id=event['user_id']).first() db.session.delete(user) db.session.commit() reply = "Your token has been removed." room.send_text(reply) else: room.send_text(self._help()) def _help(self): reply = "Visit the following URL to authorize pnut-matrix with your account on pnut.io.\n\n" reply += "https://pnut.io/oauth/authenticate?client_id=6SeCRCpCZkmZOKFLFGWbcdAeq2fX1M5t&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=stream,write_post,follow,update_profile,presence,messages&response_type=token\n\n" reply += "The following commands are available.\n\n" reply += "set_access_token \n" reply += " - Set your access token for matrix -> pnut.io account puppeting\n\n" reply += "drop_access_token\n" reply += " - Drop your access token to remove puppeting\n\n" return reply if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) bot = MonkeyBot() bot.list_rooms()