Search code examples
pythonpython-3.xtwitterwebhooks

Can't register webhook for Twitter Account Activity API [python3]


I'm trying to set up a Twitter app using the Account Activity API, to replace my old set up which used the user streaming endpoint. I want to be able to get DM messages to one user sent to a particular URL in real time.

Following these migration instructions, I've set up a webhook endpoint on my site, as described here. I've checked that process is working, by making sure that when I open https://example.com/webhook_endpoint?crc_token=foo in my browser, I get a token in response.

Now I'm trying and failing to register my webhook. I'm using the following code, and getting a 403 response.

from requests_oauthlib import OAuth1Session
import urllib

CONSUMER_KEY = 'my consumer key'
CONSUMER_SECRET = 'my consumer secret'
ACCESS_TOKEN = 'my access token'
ACCESS_SECRET = 'my access secret'

twitter = OAuth1Session(CONSUMER_KEY,
                        client_secret=CONSUMER_SECRET,
                        resource_owner_key=ACCESS_TOKEN,
                        resource_owner_secret=ACCESS_SECRET)
webhook_endpoint = urllib.parse.quote_plus('https://example.com/webhook/')
url = 'https://api.twitter.com/1.1/account_activity/all/env-beta/'
    'webhooks.json?url={}'.format(webhook_endpoint)
r = twitter.post(url)

403 response content: {"errors":[{"code":200,"message":"Forbidden."}]}

I can successfully post a status using the same session object and

r = twitter.post('https://api.twitter.com/1.1/statuses/update.json?status=Test')

What am I doing wrong here?


Solution

  • This turned out to be due to a combination of:

    1. Not having created an environment here: https://developer.twitter.com/en/account/environments as described here: https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/guides/getting-started-with-webhooks
    2. using the wrong consumer secret in the function that created the token returned at the /webhook endpoint