From 6efa8a47cc09aa6688fde3f7f0ad7cbb5efa86c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Forr=C3=B3?= Date: Fri, 4 Sep 2020 11:39:20 +0200 Subject: [PATCH] Do not fail if webhook already exists or if already subscribed --- endpoint.py | 40 +++++++++++++++++++++++++--------------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/endpoint.py b/endpoint.py index 5140201..d01ceec 100644 --- a/endpoint.py +++ b/endpoint.py @@ -8,9 +8,10 @@ import pathlib import flask import persistqueue -import requests import tweepy +from twitivity import Twitivity, TwitivityError + config = configparser.ConfigParser() config.read('settings.cfg') @@ -55,14 +56,27 @@ def push_event(data): queue.task_done() -def call_account_activity_api(api, method, endpoint, data=None): - url = 'https://{0}{1}/account_activity/all/{2}'.format(api.host, api.api_root, environment_name) - r = requests.request(method, '{0}/{1}'.format(url, endpoint), auth=api.auth.apply_auth(), data=data) - if not r.ok: - errors = r.json().get('errors') - if errors: - app.logger.error(errors.pop().get('message')) - return r +def setup_webhook(api): + twitivity = Twitivity(api, environment_name) + try: + webhook_id = twitivity.check_webhook() + except TwitivityError: + webhook_id = None + if not webhook_id: + try: + twitivity.register_webhook(webhook_url) + except TwitivityError as e: + app.logger.error(str(e)) + return False + try: + twitivity.check_subscription() + except TwitivityError: + try: + twitivity.subscribe() + except TwitivityError as e: + app.logger.error(str(e)) + return False + return True @app.route('/auth') @@ -88,12 +102,8 @@ def callback(): if not user: return 'Authentication failure', 500 update_tokens(user.id_str, [handler.access_token, handler.access_token_secret]) - # TODO: check if the webook already exists - if not call_account_activity_api(api, 'POST', 'webhooks.json', data=dict(url=webhook_url)).ok: - return 'Webhook registration failure', 500 - # TODO: check if already subscribed - if not call_account_activity_api(api, 'POST', 'subscriptions.json').ok: - return 'Webhook subscription failure', 500 + if not setup_webhook(api): + return 'Webhook setup failure', 500 return 'Success', 200