This module provide a simple way to implement twitter webhooks with ExpressJs.
This module is very new, feel free to make requests or to give some feedbacks in the github issues.
Read, write, and direct messages
permissionnpm i -s twitter-webhooks
const express = require ('express');
const bodyParser = require ('body-parser');
const twitterWebhooks = require('twitter-webhooks');
const https = require ('https');
const app = express();
app.use(bodyParser.json());
const userActivityWebhook = twitterWebhooks.userActivity({
serverUrl: 'https://yourdomain.com',
route: '/your/webhook/route', //default : '/'
consumerKey: '[YOUR CONSUMER KEY]',
consumerSecret: '[YOUR CONSUMER SECRET]',
accessToken: '[YOUR APP ACCESS TOKEN]',
accessTokenSecret: '[YOUR APP ACCESS TOKEN SECRET]',
environment: '[your-env]', //default : 'env-beta'
app
});
//Register your webhook url - just needed once per URL
userActivityWebhook.register();
//Subscribe for a particular user activity
userActivityWebhook.subscribe({
userId: '[TWITTER USER ID]',
accessToken: '[TWITTER USER ACCESS TOKEN]',
accessTokenSecret: '[TWITTER USER ACCESS TOKEN SECRET]'
})
.then(function (userActivity) {
userActivity
.on('favorite', (data) => console.log (userActivity.id + ' - favorite'))
.on ('tweet_create', (data) => console.log (userActivity.id + ' - tweet_create'))
.on ('follow', (data) => console.log (userActivity.id + ' - follow'))
.on ('mute', (data) => console.log (userActivity.id + ' - mute'))
.on ('revoke', (data) => console.log (userActivity.id + ' - revoke'))
.on ('direct_message', (data) => console.log (userActivity.id + ' - direct_message'))
.on ('direct_message_indicate_typing', (data) => console.log (userActivity.id + ' - direct_message_indicate_typing'))
.on ('direct_message_mark_read', (data) => console.log (userActivity.id + ' - direct_message_mark_read'))
.on ('tweet_delete', (data) => console.log (userActivity.id + ' - tweet_delete'))
});
//listen to any user activity
userActivityWebhook.on ('event', (event, userId, data) => console.log (userId + ' - favorite'));
//listen to unknown payload (in case of api new features)
userActivityWebhook.on ('unknown-event', (rawData) => console.log (rawData));
const server = https.createServer({
...yourHttpsConfig
});
server.listen(443);
You can check that your webhook is working by hitting it with a web browser :
https://yourdomain.com/your/webhook/route?crc_token=123456
If your webhook is properly working you'll see this kind of response :
{"response_token":"sha256=3d5U20ieYMPd/+sofKdOeSE6BkVKMqFiq+acNgeUGrYg"}
This is the root module when your require twitter-webhooks.
const twitterWebhooks = require ('twitter-webhooks');
Create an UserActivity middleware and automatically mount it on an express app if config.app
is provided.
config - Object
:
string
: The server URL where twitter can reach the webhook app (eg: 'https://my.aweso.me/service')string
: the route of the middleware in the app (eg: '/user-activity-webhook')string
: Your Twitter app consumerKeystring
: Your Twitter app consumerSecretstring
: Your Twitter app accessTokenstring
: Your Twitter app accessTokenSecretstring
: The environment name of the webhook. You can find it in your twitter dashboardExpress App
(optional): The express app on which to mount the middleware. If not provided, don't forget to mount the middleware (eg : app.use(userActivity.route, userActivity)
)string
(optional): Your Twitter app bearer token. If not provided a request will be made to twitter's API to get the token.UserActivity
This method returns a UserActivity middleware.
An UserActivity middleware is created using the twitterWebhooks.userActivity(config) method. This middleware can be mounted on an ExpressJs app. Each middleware is associated with one User Activity webhook. UserActivity middlewares has a set of methods that helps to configure the webhook by sending calls to the twitter API.
The UserActivity middlewares implements EventEmitters.
string
: The name of the event. This can be any event documented in UserActivityEmitterstring
: The id of the user who triggered this event.This event is sent for each message received on the webhook.
Object
: The raw object sent by the Twitter API.This event is sent for each unknown message received on the webhook. This is useful in case of Twitter's API change not implemented on this module.
Get the subscriptions count of your Twitter app.
Promise<Object>
This method returns a promise that is resolved with a javascript Object provided by the Twitter API :
{
"subscriptions_count_all": "2",
"subscriptions_count_direct_messages": "1"
}
Warning : This method will certainly be modified.
Get information about the current registered webhooks of an environment.
Promise<Array>
This method returns a promise that is resolved with a javascript Array provided by the Twitter API.
[
{
"id": "1234567890",
"url": "https://my.aweso.me/service/user-activity-webhook",
"valid": true,
"created_at": "2016-06-02T23:54:02Z"
}
]
Get information about webhooks for all the environments of your twitter app.
return Promise<Array>
This method returns a promise that is resolved with a javascript Array provided by the Twitter API. For more information about the response, please read Twitter's doc.
Check if a subscription exists for a twitter account.
Object
string
: The twitter account accessTokenstring
: The twitter account accessTokenSecretstring
: The twitter account IdPromise<Boolean>
This method returns a promise that is resolved to true
if the account is subscribed to this middleware's webhook. Otherwise the resolve value is false
.
Registers the webhook with the parameters given in the config of the middleware constructor. Read Twitter's doc
Promise<Object>
This method returns a promise that is resolved with a javascript Object provided by the Twitter API :
{
"id": "1234567890",
"url": "https://my.aweso.me/service/user-activity-webhook",
"valid": true,
"created_at": "2016-06-02T23:54:02Z"
}
Subscribes to all events of a twitter account.
Object
string
: The twitter account accessTokenstring
: The twitter account accessTokenSecretstring
: The twitter account IdPromise<UserActivityEmitter>
This method returns a promise that is resolved to a UserActivityEmitter instance that will emit all the events received for this account on the webhook.
Manually trigger a CRC request on the webhook. Read Twitter's doc
string
: The webhook idUnregisters the webhook with the parameters given in the config of the middleware constructor. Read Twitter's doc
Object
string
: The webhook id that you wan't to unregisterPromise
The promise is resolved if the webhook was unregistered with success and is rejected if not.
Deletes a subscription for the specified account.
Object
:
string
: The twitter account accessTokenstring
: The twitter account accessTokenSecretstring
: The twitter account IdPromise
The promise is resolved if the subscription was deleted with success and is rejected if not.
Utility function that perform a CRC check request in order to estimate a the server timing.
Promise<int>
The promise is resolved with the timing of the request in milliseconds.
Instances of the UserActivityEmitter class are EventEmitters that represent activity of one twitter account. You can get an instance of UserActivityEmitter by using the subscribe method of an UserActivity middleware.
Object
:
string
: ID of the eventstring
: Timestamp of when the event happened<Tweet Object>
: The blocked User. For more details on User Objects : Read Twitter's doc<User Object>
: The blocking User. For more details on User Objects : Read Twitter's doc{
"type": "follow",
"created_timestamp": "1517588749178",
"target": "<User Object>",
"source": "<User Object>"
}
Object
:
string
: ID of the eventstring
: Date string of when the event happenednumber
: Timestamp of when the event happened<Tweet Object>
: The favorited tweet object. For more details on Tweet Objects : Read Twitter's doc<User Object>
: The user object of the account who favorited the tweet. For more details on User Objects : Read Twitter's doc
{
"id": "a7ba59eab0bfcba386f7acedac279542",
"created_at": "Mon Mar 26 16:33:26 +0000 2018",
"timestamp_ms": 1522082006140,
"favorited_status": "<Tweet Object>",
"user": "<User Object>"
}
Object
:
string
: ID of the eventstring
: Timestamp of when the event happened<Tweet Object>
: The followed User. For more details on User Objects : Read Twitter's doc<User Object>
: The following User. For more details on User Objects : Read Twitter's doc
{
"type": "follow",
"created_timestamp": "1517588749178",
"target": "<User Object>",
"source": "<User Object>"
}
Object
:
string
: ID of the eventstring
: Timestamp of when the event happened<Tweet Object>
: The muted User. For more details on User Objects : Read Twitter's doc<User Object>
: The muting User. For more details on User Objects : Read Twitter's doc
{
"type": "follow",
"created_timestamp": "1517588749178",
"target": "<User Object>",
"source": "<User Object>"
}
Not tested yet. Please provide feedback if you are using this.
Not tested yet. Please provide feedback if you are using this.
Not tested yet. Please provide feedback if you are using this.
string
: Id of the user who revoked the subscription. This is the same id as the UserActivityEmitter instance id.Emitted when the user revokes the subscription.
<Tweet Object>
: The created tweet object. For more details on Tweet Objects : Read Twitter's docObject
:
object
:
string
: id of the deleted tweetstring
: id of the user who deleted the tweetstring
: Timestamp of when the event happened
{
"status": {
"id": "601430178305220608",
"user_id": "3198576760"
},
"timestamp_ms": "1432228155593"
}
For more details on each event : Read Twitter's doc
MIT License
Copyright (c) 2018 Vivien Anglesio
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.