Account Activity API

Table of Contents

Part 1:

- Introduction
- Getting Started & Setting Up the Twitter App.
- Usage:
  - Stream Events in Real Time.
  - Configuration.
- Installation

Part 2:

- Deploying On Web Server
  - Code Snippet
  - Calling API From Local Machine.
  - How do you view account activity events in real-time?


The Account Activity API is designed to get an accounts activity events in real time. It works differently than Twitter’s REST API or the Streaming API – as it sends the activity events through a webhook URL. Developers need to set a webhook URL, pass a Challenge Response Check (CRC) validation , register the callback URL , and finally subscribe to an account’s activity. All of this sounds overwhelming but twitivity does all the heavy lifting under the hood.


  • Performs Challenge-Response Check validation.
  • Registers webhook URL.
  • Subscribes to current user’s context.
  • Receives Twitter Account Activity events in real-time.
  • List registered webhooks.
  • Delete webhooks

Getting Started#

  • Apply for a Twitter Developer Account
  • Create an application , fill in the required fields, the callback URL is your domain name with an added endpoint, for example Twitter will later use this URL to send you account activity data. Make sure to enable “Read, Write and Direct messages” permission.
  • Navigate to the Dev environment section and setup a dev environment for the Account Activity API. Name a dev environment label of your choosing and select your app.

The next step is to register your webhook URL. Twitter will send a GET request with Challenge-Response Check or CRC token to verify you are the owner of the app and the webhook URL. To validate, an encrypted response token based on your consumer key and the CRC token has to be sent back to Twitter. Upon successful validation, registration of the webhook URL and subscription. Twitter will send data to this endpoint (the webhook URL) as a POST request.


Ngrok is a handy tool to try out the API locally, on your machine. Install and run ngrok and replace your app’s URL and callback URL with the link ngrok provides. Make sure to use the one with https.

~$ ./ngrok http 5000

Stream events in real time.#


>>> from twitivity import Event
>>> import json

>>> class StreamEvent(Event):
     CALLBACK_URL: str = ""

     def on_data(self, data: json) -> None:
         # process data

>>> stream_events = StreamEvent()
>>> stream_events.listen()


The configuration below only has to be done once before running the application for the first time.

Store the credentials as environment variables.

App -> Details -> Keys and Tokens

~$ export consumer_key=API_KEY
~$ export consumer_secret=API_SECRET_KEY
~$ export access_token=ACCESS_TOKEN
~$ export access_token_secret=ACCESS_TOKEN_SECRET
~$ export env_name=ENV_NAME # this is the dev environment label name you choose.

Register & Subscribe

To register the webhook URL and subscribe to activities, run both programs in parallel (first then This will register the webhook URL and subscribe to the user’s activities.

>>> from twitivity import Activity

>>> account_activity = Activity()
>>> account_activity.register_webhook(
>>> account_activity.subscribe()

# Response
  'id': '1198870971131686912', # webhook id
  'url': '',
  'valid': True,
  'created_timestamp': '2019-11-25 07:48:08 +0000'


~$ pip3 install twitivity

Deploying On Web Servers

Code Snippet#

Here’s a small code snippet you can use to deploy it in a web server.


import flask
import json
import hmac
import os
import hashlib
import base64
import logging
import flask


app = flask.Flask(__name__)

os.environ["consumer_secret"] = f"{consumer_secret}"

@app.route("/webhook/twitter", methods=["GET", "POST"])
def callback() -> json:
    if flask.request.method == "GET"
      or flask.request.method == "PUT":
        hash_digest = hmac.digest(
        return {
            "response_token": "sha256="
            + base64.b64encode(hash_digest).decode("ascii")
    elif flask.request.method == "POST":
        data = flask.request.get_json()
        return {"code": 200}

Calling API From Local Machine#

Once the code running on the server. You can register and subscribe to events from your local machine.


from pprint import pprint
from twitivity import Activity

if __name__ == '__main__':
    activity = Activity()

How do you view account activity events in real-time?#

From your server, execute the following command.

~$ tail -f app.log