Do not fail if webhook already exists or if already subscribed

master
Nikola Forró 4 years ago
parent 4ba72d899a
commit 6efa8a47cc

@ -8,9 +8,10 @@ import pathlib
import flask import flask
import persistqueue import persistqueue
import requests
import tweepy import tweepy
from twitivity import Twitivity, TwitivityError
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read('settings.cfg') config.read('settings.cfg')
@ -55,14 +56,27 @@ def push_event(data):
queue.task_done() queue.task_done()
def call_account_activity_api(api, method, endpoint, data=None): def setup_webhook(api):
url = 'https://{0}{1}/account_activity/all/{2}'.format(api.host, api.api_root, environment_name) twitivity = Twitivity(api, environment_name)
r = requests.request(method, '{0}/{1}'.format(url, endpoint), auth=api.auth.apply_auth(), data=data) try:
if not r.ok: webhook_id = twitivity.check_webhook()
errors = r.json().get('errors') except TwitivityError:
if errors: webhook_id = None
app.logger.error(errors.pop().get('message')) if not webhook_id:
return r 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') @app.route('/auth')
@ -88,12 +102,8 @@ def callback():
if not user: if not user:
return 'Authentication failure', 500 return 'Authentication failure', 500
update_tokens(user.id_str, [handler.access_token, handler.access_token_secret]) update_tokens(user.id_str, [handler.access_token, handler.access_token_secret])
# TODO: check if the webook already exists if not setup_webhook(api):
if not call_account_activity_api(api, 'POST', 'webhooks.json', data=dict(url=webhook_url)).ok: return 'Webhook setup failure', 500
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
return 'Success', 200 return 'Success', 200

Loading…
Cancel
Save