From 27fc81d700e1b70fa3e64257135a380952d9ec7f Mon Sep 17 00:00:00 2001 From: Morgan McMillian Date: Tue, 9 Jan 2018 16:28:53 -0800 Subject: [PATCH] replace pnutlib with pnutpy in appservice issue #17 --- appservice.py | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/appservice.py b/appservice.py index c634f4f..26d8633 100644 --- a/appservice.py +++ b/appservice.py @@ -2,9 +2,10 @@ import json import requests import logging import re +import pnutpy from bot import MonkeyBot -from pnutlib import Pnut +# from pnutlib import Pnut from flask import Flask, jsonify, request, abort from models import * @@ -93,9 +94,10 @@ def on_receive_events(transaction): requests.put(url, headers={"Content-Type": "application/json"}, data=json.dumps({})) else: if text: - r = Pnut(token).channel_post(chan_id, text, embed) - if r.status_code == 201: - msgid = json.loads(r.text)['data']['id'] + pnutpy.api.add_authorization_token(token) + try: + msg, meta = pnutpy.api.create_message(chan_id, data={'text': text, 'raw': embed}) + if token == app.config['MATRIX_PNUT_TOKEN']: puser = app.config['MATRIX_PNUT_USER'] else: @@ -105,12 +107,13 @@ def on_receive_events(transaction): cname = get_channel_settings(chan_id)['name'] text = text[:-2] text += '\n\n[' + cname + "](https://patter.chat/room.html?channel=" + chan_id + ")" - r = Pnut(token).post(text) + r, meta = pnutpy.api.create_post(data={'text': text}) - el = MatrixMsgEvents(event['event_id'], event['room_id'], msgid, puser, chan_id) + el = MatrixMsgEvents(event['event_id'], event['room_id'], msg.id, puser, chan_id) db.session.add(el) db.session.commit() - elif r.status_code == 401: + + except pnutpy.errors.PnutAuthAPIException: txId += 1 err_notice = event["user_id"] + ": The pnut.io channel this room is connected with is restricted to valid " err_notice += "pnut.io users only. Start a direct chat to link your account." @@ -119,8 +122,10 @@ def on_receive_events(transaction): url += '/_matrix/client/r0/rooms/{0}/send/m.room.message/{1}'.format(event['room_id'], str(txId)) url += "?access_token=" + app.config['MATRIX_AS_TOKEN'] requests.put(url, headers={"Content-Type": "application/json"}, data=json.dumps(body)) - else: - logging.debug(r.text) + + except: + logging.debug('*** an error occured while posting a message ***') + elif event['type'] == 'm.room.redaction': r_event = MatrixMsgEvents.query.filter_by(event_id=event['redacts'],room_id=event['room_id']).first() @@ -134,7 +139,8 @@ def on_receive_events(transaction): else: return jsonify({}) - r = Pnut(token).delete_channel_post(r_event.pnut_chan, r_event.pnut_msgid) + pnutpy.api.add_authorization_token(token) + r, meta = pnutpy.api.delete_message(r_event.pnut_chan, r_event.pnut_msgid) elif event['type'] == 'm.room.member':