This endpoint has been updated to include Post edit metadata. Learn more about these metadata on the “Edit Posts” fundamentals page. This endpoint is often used with the Direct Messages endpoints. We have launched new v2 Direct Messages endpoints. Note that the Enterprise and Premium Account Activity APIs support v2 one-to-one messages, but do not yet support group conversations.
OverviewEnterpriseThe Account Activity API provides you the ability to subscribe to realtime activities related to a user account via webhooks. This means that you can receive realtime Posts, Direct Messages, and other account events from one or more of your owned or subscribed accounts through a single connection.You will receive all related activities below for each user subscription on your webhook registration:
Activity types
* Posts (by user)
* Post deletes (by user) * @mentions (of user) * Replies (to or from user) * Retweets (by user or of user) * Quote Tweets (by user or of user) * Retweets of Quoted Tweets (by user or of user) * Likes (by user or of user) * Follows (by user or of user)
* Unfollows (by user)
* Blocks (by user) * Unblocks (by user) * Mutes (by user) * Unmutes (by user) * Direct Messages sent (by user) * Direct Messages received (by user) * Typing indicators (to user) * Read receipts (to user) * Subscription revokes (by user)
Please note - We do not deliver home timeline data via the Account Activity API. Please use the GET statuses/home_timeline to pull this data.
⏱ 10 min readThe enterprise Account Activity API provides you webhook-based JSON messages any time there are events associated with X accounts subscribed to your service. X delivers those activities to your registered webhook. In the following steps, you will learn how to manage webhooks and subscribed users.You will learn how to register, view, and remove, both webhooks and subscribed users. We’ll be using simple cURL commands to make requests to the various API endpoints. cURL is a command-line tool for getting or sending requests using the URL syntax.You will need:
Before you get started, we recommend you check out our Github repo here that provides a sample web app and helper scripts to get started with X’s Account Activity API
Using a webhook provides you the ability to subscribe to realtime activities related to a user account through a single connection.
Let’s begin with registering a new webhook URL for the given application context.The URL will be validated via a CRC request before saving. Once you’ve registered a webhook, make sure to document the webhook ID as you will need it later on.Copy the following cURL request into your command line after making changes to the following:
URL<URL> e.g. https://yourdomain.com/webhooks/twitter/
Consumer key<CONSUMER_KEY> e.g. xvz1evFS4wEEPTGEFPHBog
Access token<ACCESS_TOKEN> e.g. 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb
Once you’ve registered a Webhook, you can add a subscribed user to the Account Activity API to begin receiving their account activities.
We’ll begin with subscribing a user so you recieve all event types.Copy the following cURL request into your command line after making changes to the following:
Webhook ID<:WEBHOOK_ID> e.g. 1234567890
Consumer key name<CONSUMER_KEY> e.g. xvz1evFS4wEEPTGEFPHBog
Subscribing user’s access token<SUBSCRIBING_USER'S_ACCESS_TOKEN> e.g. 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb
In this video walkthrough, you will learn about the capabilities of the premium and enterprise tiers of the Account Activity API.By the end of this video, you will learn about the following capabilities.
The Account Activity API is a webhook-based API that sends account events to a web app you develop, deploy and host. There are several ‘plumbing’ details that need attention before you can start receiving webhook events in your event consumer application. As described below, you will need to create a X app, obtain Account Activity API access, and develop a web app that consumes webhook events.
Create a X app with an approved developer account from the developer portal. If you are creating the app on behalf of your company, it is recommended you create the app with a corporate X account. To apply for a developer account, click here.
Enable “Read, Write and Access direct messages” on the permissions tab of your app page.
On the “Keys and Access Tokens” tab, take note of your app’s Consumer Key (API Key) and Consumer Token (API Secret).
On the same tab, generate your app’s Access Token and Access Token Secret. You will need these Access Tokens to register your webhook URL, which is where X will send account events.
If you are unfamiliar with X Sign-in and how user contexts work with the X API review Obtaining Access Tokens. As you add accounts for which to receive events, you will subscribe them using that account’s access tokens.
Take note of your app’s numeric ID, as seen in the “Apps” page of the developer portal. When you apply for Account Activity API access, you’ll need this app ID.
After creating a X app, the next step is applying for Account Activity API access. Account Activity API is only availble on Enterprise, so you will need to submit an application using the link below.
Once you have received Account Activity API access, you need to develop, deploy and host a web app that will receive X webhook events.
Create a web app with a URL to use as your webhook to receive events. This is the endpoint deployed on your server to listen for incoming X webhook events.
The URI path is completely up to you. This example would be valid: https://mydomain.com_/service/listen_
As described in our Securing Webhooks guide, a first step is writing code that receives a X Challenge Response Check (CRC) GET request and responds with a properly formatted JSON response.
Register your webhook URL. You will make a POST request to a /webhooks.json?url= endpoint. When you make this request X will issue a CRC request to your web app. When a webhook is successfully registered, the response will include a webhook id. This webhook id is needed later when making some requests to the Account Activity API.
X will send account webhook events to the URL you registered. Make sure your web app supports POST requests for incoming events. These events will be encoded in JSON. See HERE for example webhook JSON payloads.
Once your web app is ready, the next step is adding accounts to receive activities for. When adding (or deleting) accounts you will make POST requests referencing the account id. See our guide on adding subscriptions for more information.
To validate your app and webhook are configured correctly, favorite a Post posted by one of the X accounts your app is subscribed to. You should receive a favorite_events via a POST request to your webhook URL for each Favorite your subscribers receive.
Note that it may take up to 10 seconds for events to start being delivered after a subscription has been added.
Important Notes
When registering your webhook URL, your web app must authenticate with its consumer token and secret and the app owner’s user access token and secret.
All incoming Direct Messages will be delivered via webhooks. All Direct Messages sent via POST direct_messages/events/new (message_create) will also be delivered via webhooks. This is so your web app can be aware of Direct Messages sent via a different client.
Note that every webhook event includes a for_user_id user ID that indicates which subscription the event was delivered for.
If you have two users using your web app for Direct Messages in the same conversation, your webhook will receive two duplicate events (one for each user). Your web app should account for this.
If you have more than one web app sharing the same webhook URL and the same user mapped to each app, the same event will be sent to your webhook multiple times (once per web app).
In some cases, your webhook may receive duplicate events. Your webhook app should be tolerant of this and dedupe by event ID.
Do not expect Quick Reply response to directly follow a request. A user has the ability to ignore a Quick Reply request and may respond via traditional Direct Message. The user may also provide a Quick Reply response to a request they have not replied to earlier in the message thread.
The SnowBot chatbot, a Ruby web app built on the Account Activity and Direct Message APIs. This code base includes a script to help set up Account Activity API webhooks.
In order to verify that you are both the owner of the app and the webhook URL, X will perform a Challenge-Response Check (CRC), which is not to be confused with a cyclic redundancy check. When a CRC is sent, X will make a GET request of your web app with a ;crc_token parameter. When that request is received, your web app needs to build an encrypted response_token based on the crc_token parameter and your app’s Consumer Secret (details below). The response_token must be encoded in JSON (see example below) and returned within three seconds. When successful, a webhook id will be returned. A CRC will be sent when you register your webhook URL, so implementing your CRC response code is a fundamental first step. Once your webhook is established, X will trigger a CRC roughly every 24 hours from the last time we received a successful response. Your app can also trigger a CRC when needed by making a PUT request with your webhook id. Triggering a CRC is useful as you develop your webhook application, after deploying new code and restarting your service. The crc_token should be expected to change for each incoming CRC request and should be used as the message in the calculation, where your Consumer Secret is the key.In the event that the response is not posted within 3 seconds or becomes invalid, events will cease to be sent to the registered webhook.
Approximately hourly to validate your webhook URL.
You can manually trigger a CRC by making a PUT request. As you develop your webhook client, you should plan on manually triggering the CRC as you develop your CRC response.
When receiving a POST request from X, sending a GET request to create a webhook, or sending a GET request to perform a manual CRC, a hash signature will be passed in the headers as x-twitter-webhooks-signature. This signature can be used to validate the source of the data is X. The POST hash signature starts with sha256= indicating the use of HMAC SHA-256 to encrypt your X App Consumer Secret and payload. The GET hash is calculated from the query parameter string crc_token=token&nonce=nonce. Steps to validate a request
Create a hash using your consumer secret and incoming payload body.
Compare created hash with the base64 encoded x-twitter-webhooks-signature value. Use a method like compare_digest to reduce the vulnerability to timing attacks.
The following are additional security guidelines to consider for your web application. Not having these guidelines implemented will not prevent your webhook from functioning, but are highly reccomended by the X Information Security team. If you are unfamilair with the below recommendations consult with your server administrator.
Turn off Session Tickets unless you rotate session ticket keys.
Set the “ssl_prefer_server_ciphers” or “SSLHonorCipherOrder” option in the SSL Configuration “on”.
Ensure the list of ciphers is a modern list such as:
ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA
In order to change webhook URLs, you must delete your existing webhook and then create a new one. Note that when you do this, you will be required to re-add user subscriptions to the new webhook.
Why are webhook configurations immutable? X takes security very seriously. If your webhook URL is changed, there is a possibility that your application consumer key and consumer secret have been compromised. By requiring you to create a new webhook configuration, you are also required to re-subscribe to your user’s events. This requires the use of access tokens that a malicious party is less likely to possess. As a result, the likelihood that another party will receive your user’s private information is reduced.
Support for thousands of subscriptions is available with the enterprise tier. If you already have an account manager, please reach out to them with questions. To apply for access to the enterprise APIs, click here.
Please note: X needs to enable access to the Account Activity API for your developer App before you can start using the API. To this end, make sure to share the App ID that you intend to use for authentication purposes with your account manager or technical support team.
The Account Activity API consists of a set of endpoints that allow you to create and manage user subscriptions to receive real-time account activities for all of your subscribed accounts through a single connection. There are two authentication methods available with the Account Activity API (OAuth 1.0a and OAuth 2.0 Bearer Token. The authentication method that you should use will depend on which endpoint you are using.
Description
**Endpoint **
OAuth 1.0a (user context)
OAuth 2.0 Bearer Token (application-only)
Register a new webhook URL for the given application context
*_ Authentication requires the access tokens of the subscribing user. _For those endpoints that require OAuth 1.0a user context authentication, you will need to provide the following credentials to authenticate the request:
Consumer Keys (API Key and Secret)
Access Tokens (Access Token and Secret)
In the case of the following three endpoints, you perform write actions within the context of your application (no X users are involved). Therefore, the Access Tokens you need to provide are the ones belonging to your developer App. These can be generated directly from within the developer portal, under the “Keys and tokens” tab for your App.
On the other hand, in the case of the following three endpoints, you are making a request that allows your application to access protected data on behalf of a X user (for example, Direct Messages). You must therefore provide the Access Tokens that belong to the subscribing user in question. The required Access tokens can be obtained using the 3-legged OAuth flow (see OAuth 1.0a: how to obtain a user’s Access Tokens). These endpoints have been marked with an asterisk in the above table (*).
Please note: Make sure that your developer App is enabled for “Read, Write, and Direct Messages.” You can change this setting in the Projects & Apps section of your developer account, under “App permissions” for the selected developer App. You will need to regenerate your App credentials after changing the permissions settings.
A list of all endpoints available with the Account Activity API, including associated description and example cURL requests with authentication implementation examples, can be found inthe API reference documentation.For additional information, check out XDev’s sample web app and helper scripts to get started with the Enterprise Account Activity API.
Please note: X needs to enable access to the Account Activity API for your developer App before you can start using the API. To this end, make sure to share the App ID that you intend to use for authentication purposes with your account manager or technical support team.
The Account Activity API consists of a set of endpoints that allow you to create and manage user subscriptions to receive real-time account activities for all of your subscribed accounts through a single connection. There are two authentication methods available with the Account Activity API (OAuth 1.0a and OAuth 2.0 Bearer Token). The authentication method that you should use will depend on which endpoint you are using.
Description
**Endpoint **
OAuth 1.0a (user context)
OAuth 2.0 Bearer Token (application-only)
Register a new webhook URL for the given application context
*_ Authentication requires the access tokens of the subscribing user. _For those endpoints that require OAuth 1.0a user context authentication, you will need to provide the following credentials to authenticate the request:
Consumer Keys (API Key and Secret)
Access Tokens (Access Token and Secret)
In the case of the following three endpoints, you perform write actions within the context of your application (no X users are involved). Therefore, the Access Tokens you need to provide are the ones belonging to your developer App. These can be generated directly from within the developer portal, under the “Keys and tokens” tab for your App.
On the other hand, in the case of the following three endpoints, you are making a request that allows your application to access protected data on behalf of a X user (for example, Direct Messages). You must therefore provide the Access Tokens that belong to the subscribing user in question. The required Access tokens can be obtained using the 3-legged OAuth flow (see OAuth 1.0a: how to obtain a user’s Access Tokens). These endpoints have been marked with an asterisk in the above table (*).
Please note: Make sure that your developer App is enabled for “Read, Write, and Direct Messages.” You can change this setting in the Projects & Apps section of your developer account, under “App permissions” for the selected developer App. You will need to regenerate your App credentials after changing the permissions settings.
A list of all endpoints available with the Account Activity API, including associated description and example cURL requests with authentication implementation examples, can be found inthe API reference documentation.For additional information, check out XDev’s sample web app and helper scripts to get started with the Enterprise Account Activity API.
EnterpriseOne of the benefits of the enterprise tier of the Account Activity API is a retry mechanism for webhook events. If a ‘success’ 200 HTTP response code is not received, the X server will initiate a retry mechanism, resending the webhook event up to three times over a five-minute period. This webhook event retry service helps provide reliability and event recovery when network problems occur and during client-side service interruptions and deploys.
The Account Activity API provides a retry feature when the client’s web app does not return a ‘success’ 200 response for an account activity webhook event. When the client-side does not confirm the successful receipt of an event, X assumes the event was not received. If a non-200 response is received, a response isn’t received within three seconds, or we don’t receive a response at all, we retry the request and leave that open for three seconds. This means that you have roughly five seconds over two attempts to respond to receive the activity that we are trying to send to your webhook URL. In the event that your server doesn’t response or returns a transient error, we will retry for five minutes. There will be a total of three retry attempts to confirm validation. This allows redundancy and insurance that you receive all webhook events. Note that subscriptions with retries will get retried events for any/all activities for all subscribed users on their webhook.If you do not confirm validation within these eight attempts, the activity will no longer be available via the Account Activity API.
The Account Activity API will retry up to three times over a five-minute period until a 200 response is received. Refer to the table below for more details. After around five minutes, the activity cannot be resent through the Account Activity API. You will need to use other X endpoints to collect missed data. For example, the search APIs can be used to retrieve relevant Posts, Retweets, Quote Tweets, Mentions, and Replies. Missed Direct Messages can be retrieved with this endpoint.
Post status payload when any of the following actions are taken by or to the subscription user: Posts, Retweets, Replies, @mentions, QuoteTweets, Retweet of Quote Tweets.
EnterpriseThe Account Activity Replay API is a data recovery tool that allows you to retrieve events from as far back as five days. It should be utilized to recover data in scenarios where your webhook server misses events, — whether due to disconnections lasting longer than the retry window, or for those disaster recovery scenarios where you need a few days to restore your system back to normal.The Account Activity Replay API was developed for any scenario where you fail to ingest activities for a period of time. It delivers activities to the same webhook used for the original real-time delivery of activities. This product is a recovery tool and not a backfill tool, which means events will only be replayed if a previous delivery of them was attempted. The Account Activity Replay API cannot deliver events for a time period prior to a subscription’s creation time.
If your account is configured with Replay functionality, you can make requests in a similar manner as requests to the Account Activity API. It is important to note that your request must specify a webhook id parameter to indicate which webhook’s activities you would like to replay. In other words, a Replay request asks Account Activity Replay API to retrieve events from a start date and time to an end date and time based on the webhook id and application id.Please note that UTC time is expected. These activities are delivered through the registered webhook associated with the id at a rate of up to 2,500 events per second. Also keep in mind that only one Replay job per webhook may be running at a time, although all subscriptions that were active during the date/time specified on that webhook will be replayed.Events are delivered beginning with the first (oldest) minute of the specified time period, continuing chronologically (as best as possible) until the final minute is delivered. At that point, Replay will deliver a job completion event to the webhook. Because we work chronologically in delivering activities, if there are little or no matching results near the start time, there will likely be a period of time before the first results are delivered.
Replay is intended as a tool for easily recovering activities as far back as five days ago, but it will not deliver events prior to a subscription’s creation time. For example, if three days ago, you added a new subscription and ran a Replay job with a window for five days prior to today, you would only receive data for the three days that this new subscription was active.
Activities from the Account Activity Replay API are available five days from the initiation of the request, with new data becoming available roughly 10 minutes after a given activity is created. You will be able to make requests specifying a timeframe within this five day window using the from_date and to_date parameters within the request. Events that were originally delivered prior to having access to Replay cannot be replayed. For example, if your account was enabled for access to the Account Activity Replay API on June 1, 2019 at 3:30PM UTC, you would not be able to use Replay to retrieve any events prior to that date and time.Continue to the Account Activity Replay API reference
We retired the Site Streams, User Streams, and standard beta version of the Account Activity API - DM Only products in 2018. If you had been using those products, please make sure to migrate over to the premium or enterprise version of the Account Activity API.**We have also retired the legacy Direct Message endpoints. If you had been using those endpoints, please make sure to migrate over to either the new DM endpoints, or to the premium or enterprise version of the Account Activity API. **Please review this announcment to learn more.Here are the endpoints that will be affected by these changes:
User Streams
Site Streams
GET direct_messages
GET direct_messages/sent
GET direct_messages/show
POST direct_messages/new
POST direct_messages/destroy
We have new endpoints and services available that provide similar access and, for Direct Messages, some additional functionality:
Additionally, we have a series of videos about the Account Activity API and how to get started.And, finally, we have code samples to further your understanding and help you get started quickly:
The Account Activity Dashboard is a sample Node.js web app with helper scripts to get started with the Account Activity API.
SnowBot is a sample chatbot using the Account Activity API and REST Direct Message endpoints. It’s written in Ruby, uses the Sinatra web app framework, and is deployed on Heroku.
Migration Guide: Moving from User Streams/Site Streams to Account Activity API
As of August 23rd, 2018, we retired both Site Streams and User Streams. Please make sure to migrate over to the Account Activity API.Please review this announcement to learn more.This guide is designed to help you migrate from legacy User Streams and Site Streams APIs to their replacement, the Account Activity API. Below you will find a summary of the changes, new features list, as well as key differences and considerations to help with the transition. For guidance in migrating from basic DM endpoints, please refer to the Direct Message migration guide.
The Account Activity API will deliver you events for authenticated and subscribed accounts via webhooks as opposed to a streaming connection like with User Streams and Site Streams.
GET userGET site (including control streams: GET site/c/:stream_id, GET site/c/:stream_id/info.json, GET site/c/:stream_id/friends/ids.json, POST site/c/:stream_id/add_user.json, POST /site/c/:stream_id/remove_user.json)
API format: The new Account Activity API operates differently than User Streams and Site Streams. You will need to alter your web app to receive data with webhooks. You can find more information on webhooks here.Data Available: Another key difference you will notice is in regards to the data being delivered. X will no longer send events from people that you follow on X (aka your home timeline). This was an intentional change and is not something we plan to alter going forward.Reliability: Unlike streaming, webhooks enable confirmation of delivery and options to retry POSTed activities that do not make it to the webhook URL. This gives more assurance that the app is receiving all applicable activities, even if there are brief disconnections or periods of downtime.
The Account Activity API offers many new features, most notably that data is now delivered via webhooks as opposed to streaming. Webhooks offer many benefits compared to streaming, but the most prominent are speed and reliability. The API will send you data in the form of JSON events as they become available and you will no longer need to maintain an active connection or poll the endpoint. This limits the need for redundancy features and increases efficiency overall. More information on webhooks can be found in the technical documentation.
The Account Activity API allows multiple subscriptions for a single registered webhook. This allows multiple user subscriptions activities to be delivered to the same location, similar to the Site Streams architecture, with webhooks. This means you can track subscriptions, as they pertain to your subscription limits, independently from the webhook connection. This also allows scalability from only one or a few subscriptions to thousands of subscriptions for a single webhook.
Follow the steps below to easily migrate from the Site Streams API to the Account Activity API
Step 1: Decide on a PackageDepending on how you are currently operating with User Streams or Site Streams, you should consider moving to either the enterprise or premium version of the Account Activity API. Consider the number of applications or authorized users you are currently supporting and scale appropriately to the volume and reliability needed. When deciding on the package that best suits your needs, some things worth considering are:
Number of webhooks needed
Current/projected subscriptions/authorized users managed on your application
Current number of X client applications
The level of support you’d prefer from X (forum support or managed enterprise level 1:1 support)
Price of each package
Step 2:Check the Setup of your X app in the developer portalThe X app currently used for User Streams or Site Streams will be listed for the owning user within the developer portal. This X app can also be used for Account Activity API to retain authorized users for that application. A new app can also be created, and users can be re-authorized for this new app if desired. If you are creating a new app on behalf of a business, it is recommended that you create the app with a corporate X @handle account.
Enable “Read, Write and Access direct messages” on the permissions tab of your X app page.
*Note that changing these settings is not retroactive, any authorized users will keep the authorization settings from the time at which they were authorized. If a user has not already given you read, write and direct message access, you will need to have that user re-authorize your application.
Generate access tokens for the X app owner at the bottom of the “Keys and Tokens” tab. On this same tab take note of your Consumer Key, Consumer Secret, Access Token and Access Token Secret. You will need these to use the API.
Generate a bearer token using your Consumer Key and Consumer Secret for application-only API methods.
Use your Consumer Key, Consumer Secret, Access Token and Access Token Secret when creating your webhook, Note that your endpoint must return a JSON response with a response_token that is a base64 encoded HMAC SHA-256 hash created from the crc_token and your app Consumer Secret.
Review Securing Webhooks documentation taking special note of the Challenge Response Check (CRC) requirements.
Make sure your webhook supports POST requests for incoming events and GET requests for the CRC.
Make sure your webhook has low latency (<3 seconds to respond to POST requests)
Step 4: Validate Your Webhook Setup
Webhook APIs will secure your webhooks in two ways:
- Require challenge response checks to validate that the webhook owner is the web app owner. - A signature header in each POST request for your web app to validate the source.
In order to verify that you are both the owner of the web app and the webhook URL, X will perform a Challenge Response Check (CRC), which is not to be confused with a cyclic redundancy check.
A GET request with a parameter named crc_token will be sent to your webhook URL. Your endpoint must return a JSON response with a response_token that is a base64 encoded HMAC SHA-256 hash created from the crc_token and your app Consumer Secret.
The crc_token should be expected to change for each incoming CRC request. The crc_token should be used as the message in the calculation, where your Consumer Secret is the key.
In the event that the response is invalid, events will cease to be sent to the registered webhook.
Step 5: Create Subscriptions for Each User Stream or Site Streams Authorized UserConverting to the Account Activity API from User Streams:
Generate a list of your current user subscriptions on User Streams
Set up your new Account Activity API subscriptions using the request: POST account_activity/all/:env_name/subscriptions
Confirm your Account Activity API subscriptions using the request: _GET account_activity/all/:env_name/subscriptions/list
_
Converting to the Account Activity API from Site Streams: (using control streams):
Generate a list of your current subscriptions on Site Streams using the request: GET /1.1/site/c/:stream_id/info.json
Set up your new Account Activity API subscriptions using the request: POST account_activity/all/:env_name/subscriptions
Confirm your Account Activity API subscriptions using the request: _GET account_activity/all/:env_name/subscriptions/list
_
Registering a Webhook and Creating Subscriptions (not migrating from Site Streams or User Streams)
Register your webhook URL with your app using POST webhooks and receive a webhook_id.
Blank lines will no longer be delivered in the Account Activity API as they were used as keep-alive messages in User Streams and Site Streams.
Limit notices
Limit notices will no longer be sent to a given webhook. Instead, users can call the API to get current usage of available handles. This will be included in the developer portal at some time in the future.
Disconnect messages
Disconnect notices will no longer be necessary as webhooks do not rely on an active connection.
Stall warnings
Stall warnings will no longer be necessary as webhooks do not rely on an active connection being able to handle large numbers of incoming messages.
Friends list
Friends lists will no longer be sent proactively. There will now be a REST endpoint to get this information.
On September 17th, 2018 we retired the legacy Direct Message endpoints.
If you had been using those endpoints, please make sure to migrate over to the new Direct Message endpoints or the Account Activity API.Please review this announcment to learn more.This guide is designed to help you migrate from legacy Direct Message REST APIs to their enhanced replacements which have graduated from beta. Below you will find a summary of the changes, a new features list, and key differences and considerations to help with the transition. The new Direct Message endpoints are available now to all developers. For guidance in migrating from User Streams or Site Streams, see the migration guide to Account Activity API.
The new Direct Message API endpoints support a number of new capabilities and provide improved access to previous Direct Messages. New features include:
Support for media attachments (image, GIF, and video).
Ability to prompt users for structured replies with a predefined options list.
Up to 30 days of access to past Direct Messages.
For a full list of new Direct Message features and additional new API endpoints refer to the technical documentation.
The new API endpoints behave very differently from their previous counterparts. Simply updating the endpoint URLs will result in errors in your application. Consider the following when updating your application for the migration.
The first thing you are likely to notice is the new object structure of Direct Messages. This new Message Create object structure has been introduced to support new capabilities like Quick Replies and Attachments. The new object also contains a smaller condensed user object. Your application will need to be updated to account for this new object structure when parsing and potentially in data models or storage. For descriptions of each property see the full documentation on the Message Create Object.Example message create object
POST direct_messages/events/new is a direct replacement for sending Direct Messages. The most significant difference with this endpoint is that all information is now sent as JSON in the POST request body as opposed to individual POST params.Example Twurl request
Copy
Ask AI
twurl -A 'Content-type: application/json' -X POST /1.1/direct\_messages/events/new.json -d '{"event": {"type": "message\_create", "message\_create": {"target": {"recipient\_id": "4534871"}, "message_data": {"text": "Hello World!"}}}}'
Note in the above request that the content-type is set to application/json as opposed to application/x-www-form-urlencoded. Additionally, if you are constructing the OAuth 1.0a signature, note that the JSON body is not included in the generation of the signature. Most OAuth libraries already account for this. If you are using twurl, ensure you are using at least version 0.9.3.
Retrieving past Direct Message is now accomplished with a single API endpoint: GET direct_messages/events/list. The significant difference with this new endpoint is that it now returns both sent and received messages in reverse chronological order. This may make it easier to rebuild a conversation. However, if you are only looking for sent or received messages you will need to post-process the response by referring to the sender_id property.Pagination is now based on a cursor value rather an ID of a Direct Message. A cursor property is returned with each response. GET direct_messages/events/list will return up to 30 days of past messages, regardless of how many messages exist within the past 30 days. When a cursor is not returned, there are no more messages to be returned. The method for accessing individual Direct Messages with GET direct_messages/events/show remains the same, although the Direct Message object returned has a different structure as described previously.Finally, real-time access to Direct Messages will now be accomplished via webhook with the Account Activity API. For guidance in migrating from User Streams or Site Streams, see the migration guide to Account Activity API for more information.
Direct Messages can now be deleted with DELETE direct_messages/events/destroy. The interface is largely the same requiring the ID of the message to delete. The key differences is the endpoint now requires a DELETE request instead of a POST request.How deleted Direct Messages are reflected in official X clients remains the same. Direct Messages are only removed from the interface of the user context provided. Other members of the conversation can still access the Direct Message.
What are the advantages of using the Account Activity API?The Account Activity API uses webhooks, meaning that unlike for the streaming APIs we don’t require you to have an open connection for us to send you information. Webhooks are also different from Rest APIs because you don’t have to pull us hundreds of times every 15 minutes to get the data you care about. This increases the efficiency between a user and your app, as it delivers data when it happens.The Account Activity API has a number of benefits:
Speed: we deliver data at the speed of X.
Simplicity: we deliver all of an account’s events, through one single webhook connection. The activities delivered in the API include Posts, @mentions, replies, Retweets, Quote Tweets, Retweets of Quote Tweets, favorites, Direct Messages sent, Direct Messages received, follows, blocks, mutes.
Scale: you receive all of the activities for an account that you manage without being restricted by any rate limits of event caps.
The Account Activity API is available as a premium sandbox, premium paid, and enterprise offering, so you can scale as you require more accounts for liability features or additional functionality.To get started, download sample code snippets from GitHub.
How do I identify which product tier is best for me?Please read through our Account Activity API Overview page to learn more about the differences between the Premium options and the Enterprise option.
What is the difference between a Premium environment and an Enterprise webhook?There is no difference. Each Premium environment will have its own webhook_id.
I need a development, staging and production environment for Account Activity API, is this possible?Yes! With the paid tiers of Account Activity API (Paid Premium and Enterprise), it’s possible to register multiple webhook URLs and manage subscriptions separately for each through the API methods. Additionally, multiple client apps may be added to an allowlist to maintain authorization for your current authorized users.
Do you have any step-by-step guides on how to get set up with the Account Activity API?As a matter of fact, we do!
The SnowBot chatbot, a Ruby web app built on the Account Activity and Direct Message APIs. This code base includes a script to help set up Account Activity API webhooks.
Is there a way to recover data if our system goes down for a period of time?With the paid tiers of Account Activity API (Paid Premium and Enterprise), our system will retry to send the activities to you several times over a four hour period. If your system does not respond within that four hour period, then the activity will be lost and you will have to use other REST endpoints to recover data within 7 days.We suggest that you use your different webhooks, or environments, as a redundancy tool like the Account Activity Replay API to ensure that you don’t miss any activities if one of your systems goes down.
What authentication do I have to use with the Account Activity API?The authorization methods required for Account Activity API is described per method in the API reference pages. If you are just starting out with X authentication, we recommend that you read through this section.What is a challenge-response check (CRC)?The Account Activity API challenge response check is a security feature put in place to ensure that the Account Activity API’s activities are being sent to the proper developer. It also can be used by developers to ensure that the data that they are receiving is coming from X. X will automatically send a CRC to your webhook URL once every 24 hours, starting the last time the webhook URL was validated. Your system must respond with a valid response within 3 seconds to remain validated. Please visit our page Securing webhooks for more details.
Is there anything that would immediately invalidate my webhook URL?If one of the following occurs, we will immediately mark your webhook as invalid:
The server responds to a CRC with an incorrect token. In this case, our system will not retry to send you the activity.
The webhook URL has an incorrect certificate configured. In this case, our system will not retry to send you the activity.
Your server returning a non-2XX, non-4XXX, non-5XXX response code.
You specify the use of gzip without actually sending it.
You do not specify the use of gzip, but actually send it in the response.
Will I get duplicate activities if subscribed to users that are interacting with each other?Yes. If your web app has active subscriptions for User A and User B, and User A mentions User B in a Post, there will be two POST activities sent to the registered webhook. Each activity will have an indicator of “for_user_id” to show which subscription the activity belongs to.
**When I make a subscription to my webhook, can I replace the /all/ portion of the following endpoint with other account activity data objects to limit the activities the API delivers? **POST https://api.x.com/1.1/account_activity/all/:env_name/subscriptions.jsonNo, this is not possible. As it currently stands, we only have the /all/ product available.
**Is there any way of using the Account Activity API without requesting Direct Messages permissions from users? **At this point, Direct Messages permissions are required because there is no way to ‘filter out’ the Direct Messages activities for this API.
Is there a free version of the Account Activity API?Yes, we offer the sandbox version as a free tier. Our sandbox option is limited to a single webhook with a limit of a maximum of 15 subscriptions. You can read more about the sandbox option in our documentation. **Is it possible to use the Account Activity API to get Retweets of Posts that mention subscribed users? **Unfortunately, this is not part of the activities delivered with this API. For this, we suggest using the Streaming API instead.
What are the possible activity types that are represented by a tweet_create_event?A tweet_create_event payload will be sent:If the subscription user does any of the following actions:
Creates a Post
Retweets
Replies to a Post
If another user:
@mentions* the subscription user
Quotes a Tweet created by the subscription user
*Note: The Account Activity API only delivers events when the subscription user would receive a notification from X and could see the event publicly. This means, If the mentioned account (@userA) follows the protected account (@userB) then UserA will get a notification UserB mentioned them. If UserA is not following UserB (and approved by UserB) UserA will not get a notification, and therefore a tweet_create_event would not be sent via AAA if @userA had a subscription.If a blocked user mentions my subscribed user, how can I identify this?You will see a boolean field `user_has_blocked` on the top level of the json response, set to either “true” or “false”. This field will only be exposed on Post mentions. EnterpriseHow can I add my app to an allowlist or check if my app is already on the allowlist?To manage the X apps that you have added to an allowlist for access via the Enterprise APIs, please reach out to your account manager with your app ID. You can find your app ID by navigating to the “Apps” page in the developer portal.
If I have access to three webhooks, can I use three webhooks for each of the apps that I have registered for enterprise use?The webhook limit is set on the account level, not the app level. If you have access to three webhooks and two apps registered for enterprise use, you can use two webhooks on one app and the third on the other app, but not three on each app. Can I specify which types of events will be redelivered using the Account Activity Replay API?The types of events to replay cannot be specified. All events delivered during the date and time window specified will be replayed. Will there be any retries if my application fails to ingest an Account Activity Replay API event?No, there will not be any retries. If an application fails to ingest an event sent by the Account Activity Replay API, another Replay job can be submitted for the same time period to attempt redelivery of any missed Replay events. What should I do when I receive a partial success completion event?We suggest making note of the timestamps for the events that were received and requesting another Replay job for the events that were missed. How many Account Activity Replay API jobs can I have running at a time?Only one Account Activity Replay API job per webhook may be running at a time. How can I differentiate Account Activity Replay API events from real-time production events as they are delivered to my webhook?Since the Account Activity Replay API will always deliver events from the past, events can be differentiated from real-time production events based on the event’s timestamp. How soon can I start using the Account Activity Replay API to redeliver an activity my application dropped or missed?An activity becomes available for redelivery about 10 minutes after it was created.
This error generally means that something is either malformed in the request, headers, authorization, or url that you are specifying. This is not an Account Activity API error, it’s an authorization error and X isn’t getting the proper Oauth setup or url.
Enterprise - Make sure the consumer keys and access tokens you are using belong to a X app that has been registered for use of Enterprise products. If you don’t have your consumer keys and access tokens, or need to add your X app to the allowlist, please reach out to your account manager.
If authenticating with user context, make sure you have properly authorized your request with the proper oauth nonce, oauth_signature, and oauth_timestamp.
Make sure that your access tokens have the proper permission level.
When on the ‘Keys and tokens’ tab in the app dashboard, please make sure that your access tokens have the ‘Read, write, and direct messages’ permission level.
If the tokens’ permission level is set to anything less than this, please navigate to the ‘Permissions’ tab, adjust the access permission to ‘Read, write, and direct messages’, then regenerate your access tokens and secret from the ‘Keys and tokens’ tab.
Make sure that your URL is formed properly.
Please keep in mind that :env_name is case sensitive.
Premium - Make sure that you have an approved developer account before you try to make a request to the API. You also must use the proper :env_name in the request, which you can setup on the dev environments page.
Enterprise - Make sure that your account manager has set you up with access to the Account Activity API.
Make sure you have set up your URI properly. This error can trigger if you have entered the incorrect URI in your request.
Enterprise - You have already used all of your webhooks. Use the GET webhooks endpoint with each of your registered apps to identify where your webhooks are distributed.
The app that you are using with the API does not have the proper permission level set for its access token and access token secret. Please navigate to the ‘Keys and tokens’ tab on the X apps dashboard and check the permission levels assigned to your access token and access token secret. If it is set to anything other than ‘Read, write and Direct Messages,’ then you are going to have to adjust the settings under the ‘Permission’ tab and regenerate your access token and access token secret to apply the new settings.
Alternatively, you are trying to register a webhook using app-only authentication, which is not supported. Please authenticate with user context instead as noted in the API reference sections for registering a webhook for Enterprise Account Activity API.
Registers a new webhook URL for the given application context. The URL will be validated via CRC request before saving. In case the validation failed, returns comprehensive error message to the requester.The number of allowed webhooks is determined by billing package.
Returns all URLs and their statuses for the given application.We mark a URL as invalid if it fails the daily validation check. In order to re-enable the URL, call the update endpoint.
Triggers the challenge response check (CRC) for the given webhook’s URL. If the check is successful, returns 204 and reenables the webhook by setting its status to valid.
POST account_activity/webhooks/:webhook_id/subscriptions/all
Subscribes the provided application to all events for the provided user context for all message types. After activation, all events for the requesting user will be sent to the application’s webhook via POST request.Subscriptions are currently limited based on your account configuration. If you have a need to add more subscriptions, please contact your account manager.
Returns the count of subscriptions that are currently active on your account. Note that the /count endpoint requires application-only OAuth, so that you should make requests using a bearer token instead of user context.
GET account_activity/webhooks/:webhook_id/subscriptions/all
Provides a way to determine if a webhook configuration is subscribed to the provided user’s events. If the provided user context has an active subscription with provided application, returns 204 OK. If the response code is not 204, then the user does not have an active subscription. See HTTP Response code and error messages below for details.
GET account_activity/webhooks/:webhook_id/subscriptions/all/list
Returns a list of the current All Activity type subscriptions for the specified webhook. Note that the /list endpoint requires application-only OAuth, so requests should be made using a bearer token instead of user context.
Removes the webhook from the provided application’s configuration. The webhook ID can be accessed by making a call to GET /1.1/account_activity/webhooks.
Deactivates subscription(s) for the provided user context and application. After deactivation, all events for the requesting user will no longer be sent to the webhook URL.
Deactivates subscription for the specified webhook and user id. After deactivation, all events for the requesting user will no longer be sent to the webhook URL. Note, that this endpoint requires application-only OAuth, so requests should be made using a bearer token instead of user context.
POST /1.1/account_activity/replay/webhooks/:webhook_id/subscriptions/all.json ¶Submits a request to retrieve activities from up to the past five days from all subscriptions present during the date and time windows specified in the request. If your webhook has active user subscriptions, you will concurrently receive those events as well. Note: We do perform a CRC before delivering replay events.
5 requests per 15 minutes. There is currently no maximum on the number of replay jobs that can requested.
from_date
The oldest (starting) UTC timestamp from which the events will be provided, must be in ‘yyyymmddhhmm’ format. Timestamp is in minute granularity and is inclusive (i.e. 12:00 includes the 00 minute). Valid times must be within the last 5 days, UTC time, and no more recent than 31 minutes before the current point in time. It’s recommended that the from_date and to_date should be within ~2 hours.
to_date
The latest (ending) UTC timestamp to which the event will be provided, must be in ‘yyyymmddhhmm’ format. Timestamp is in minute granularity and is exclusive (i.e. 12:30 does not include the 30th minute of the hour). Valid times must be within the last 5 days, UTC time, and no more recent than 10 minutes before the current point in time.
The following responses may be returned by the API. Most error codes are returned with a string including additional details in the body. For non-200 responses, you should resolve the error and try again.
Status
Text
Error Code
Description
Message
202
Accepted
N/A
The request was successful and the activities will be sent.
N/A
400
Bad Request
214
Webhook has been marked as invalid.
Webhook is marked invalid and requires a CRC check.
400
Bad Request
357
Query parameter is missing.
: queryParam is required.
400
Bad Request
358
Route or query parameter is malformed.
Unable to parse parameter.
400
Bad Request
360
Route parameter is negative.
webhook_id: [] is not greater than or equal to 0.
400
Bad Request
368
from_date or to_date is not in the past.
: [<field_value>] is not in the past.
400
Bad Request
356
from_date must be before to_date.
from_date must be before to_date.
400
Bad Request
356
from_date must be within the past 5 days.
from_date must be within the past 5 days.
401
Unauthorized
32
HTTP authentication failed due to 3-legged auth provided.
Invalid authentication method. Please use application-only authentication.
401
Unauthorized
61
Client is not permitted to request this method.
Client is not permitted to request this method.
403
Forbidden
200
Client does not have an enterprise account with Replay enabled.
Account Activity API enterprise account with replay is required. Please confirm you have an enterprise account and replay is enabled.
Once your job successfully completes, Account Activity Replay API will deliver the following job completion event. Once you receive this event, the job has finished running and another can be submitted.
In the event your job does not complete successfully, we will return the following message encouraging you to retry your Replay job. Once you receive this event, the job has finished running and another can be submitted.
Copy
Ask AI
{ "replay\_job\_status": { "webhook_id": "123451374207332352", "job_state": "Incomplete", "job\_state\_description": "Job failed to deliver all events, please retry your replay job", "job_id": "1093226942650736640" }}