Posted on 1 Comment

Upgrading The Discord Twitter Bot To Use The Twitter V2 API

close up photo of toy bot

Twitter Upgraded Their API & Broke My Bot!!

Imagine my frustration when I get dozens of DMs, emails, and other messages asking when I was going to upgrade my Discord Twitter bot to be compliant with the latest Twitter changes. Like damn bro, I have other things to do lol but alas I can’t let my peeps down. In this blog entry, I will show you what I did to upgrade my codebase to use the Twitter V2 API to communicate with the Discord server to send out my tweets.

Twitter has been an integral part of social media and has become a platform for information exchange, news updates, and social interactions. Twitter offers an API that allows developers to create applications that can interact with Twitter data. Recently, Twitter introduced a new version of its API called the Twitter V2 API, which includes several updates and improvements. One of the notable features of the Twitter V2 API is the Rules API, which enables developers to create complex filters and rules for retrieving Tweets and other Twitter data.

v2 of the Discord Twitter bot

Upgrading The Package.json File

We are no longer using the Twit npm package and instead using the twitter-v2 npm package. Open your package.json file and change it to the following:

{
  "name": "discord-twitter-bot",
  "version": "2.0.0",
  "description": "A discord bot that sends messages to a channel whenever a specific user tweets.",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/mastashake08/discord-twitter-bot.git"
  },
  "keywords": [
    "discord",
    "twitter",
    "bot"
  ],
  "author": "mastashake08",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/mastashake08/discord-twitter-bot/issues"
  },
  "homepage": "https://github.com/mastashake08/discord-twitter-bot#readme",
  "dependencies": {
    "discord.js": "^13.8.1",
    "dotenv": "^8.2.0",
    "twitter-v2": "^1.1.0"
  },
  "engines" : {
    "npm" : ">=7.0.0",
    "node" : ">=16.0.0"
  }
}

Listen To Some Hacker Music While You Code

Follow me on Spotify I make Tech Trap music

Changes To The Twitter API

In order to use the stream API, we have to set up stream rules. We want to only show tweets from yourself so in your .env file add a new field

TWITTER_USER_NAME=

Afterward, we listen to the stream pretty much as before. Open up the main.js file and update it to the following.

require('dotenv').config()
const Twit = require('twitter-v2')
const { Client } = require('discord.js');
const client = new Client({ intents: 2048 });


var T = new Twit({
  // consumer_key:         process.env.TWITTER_CONSUMER_KEY,
  // consumer_secret:      process.env.TWITTER_CONSUMER_SECRET,
  // access_token_key:         process.env.TWITTER_ACCESS_TOKEN,
  // access_token_secret:  process.env.TWITTER_ACCESS_TOKEN_SECRET,
  // timeout_ms:           60*1000,  // optional HTTP request timeout to apply to all requests.
  // strictSSL:            true,     // optional - requires SSL certificates to be valid.
  bearer_token:  process.env.BEARER_TOKEN
})

//   //only show owner tweets
async function sendMessage (tweet, client){
  console.log(tweet)
  const url = "https://twitter.com/user/status/" + tweet.id;
  try {
    const channel = await client.channels.fetch(process.env.DISCORD_CHANNEL_ID)
    channel.send(`${process.env.CHANNEL_MESSAGE} ${url}`)
  } catch (error) {
        console.error(error);
  }
}

async function listenForever(streamFactory, dataConsumer) {
  try {
    for await (const { data } of streamFactory()) {
      dataConsumer(data);
    }
    // The stream has been closed by Twitter. It is usually safe to reconnect.
    console.log('Stream disconnected healthily. Reconnecting.');
    listenForever(streamFactory, dataConsumer);
  } catch (error) {
    // An error occurred so we reconnect to the stream. Note that we should
    // probably have retry logic here to prevent reconnection after a number of
    // closely timed failures (may indicate a problem that is not downstream).
    console.warn('Stream disconnected with error. Retrying.', error);
   // listenForever(streamFactory, dataConsumer);
  }
}

async function  setup () {
  const endpointParameters = {
      'tweet.fields': [ 'author_id', 'conversation_id' ],
      'expansions': [ 'author_id', 'referenced_tweets.id' ],
      'media.fields': [ 'url' ]
  }
  try {
    console.log('Setting up Twitter....')
    const body = {
      "add": [
        {"value": "from:"+ process.env.TWITTER_USER_NAME, "tag": "from Me!!"}
      ]
    }
   const r = await T.post("tweets/search/stream/rules", body);

  } catch (err) {
    console.log(err)
  }

  listenForever(
    () => T.stream('tweets/search/stream'),
    (data) => sendMessage(data, client)
  );
}
// Add above rule

client.login(process.env.DISCORD_TOKEN)
 client.on('ready', () => {
   console.log('Discord ready')
   setup()

 })

What is the Twitter V2 Rules API?

The Twitter V2 Rules API is a set of endpoints that allows developers to create, manage and delete rules for filtering and retrieving Twitter data. With the Rules API, developers can define specific criteria that must be met for a Tweet or a stream of Tweets to be returned. This means developers can create more sophisticated and complex search queries and filters than before.

The Twitter V2 Rules API provides a comprehensive set of operators that can be used to create rules. These operators include “contains,” “hashtag,” “from,” “to,” “mention,” “URL,” “geo,” “lang,” and “is.” With these operators, developers can create rules based on keywords, hashtags, location, language, and many other criteria.

How to use the Twitter V2 Rules API?

To use the Twitter V2 Rules API, developers need to create a Twitter Developer Account and obtain API keys and access tokens. Once the developer has the necessary credentials, they can use the Rules API to create and manage rules for filtering Twitter data.

To create a rule, developers can use the POST /2/tweets/search/stream/rules endpoint, which accepts a JSON payload containing the rule definition. For example, to create a rule that returns Tweets containing the hashtag “#apple” and “iPhone,” the following JSON payload can be used:

{
  "add": [
    {
      "value": "#apple iPhone",
      "tag": "apple-tweets"
    }
  ]
}

This payload contains the “add” operator, which adds a new rule to the stream. The “value” field contains the search query, and the “tag” field is an optional label that can be used to identify the rule.

Once the rule is added, developers can use the GET /2/tweets/search/stream endpoint to retrieve the stream of Tweets that match the defined rule.

Why use the Twitter V2 Rules API?

The Twitter V2 Rules API offers several benefits for developers. Firstly, it provides more powerful and sophisticated filtering capabilities, allowing developers to create more precise and targeted search queries. This is particularly useful for businesses and organizations that need to monitor Twitter for specific keywords, trends, or events.

Secondly, the Twitter V2 Rules API is more reliable and scalable than previous versions. It supports higher throughput and lower latency, making it easier to retrieve and process large volumes of Twitter data.

Lastly, the Twitter V2 Rules API provides better documentation and support, making it easier for developers to get started and integrate with Twitter. The API also includes features such as pagination and rate limiting, which help developers manage their usage and avoid hitting API limits.

The Twitter V2 Rules API is a powerful and flexible tool for developers who need to retrieve and filter Twitter data. With the Rules API, developers can create complex search queries and filters that enable them to access the specific data they need. This makes the API particularly useful for businesses, organizations, and researchers who need to monitor Twitter for specific keywords, trends, or events. If you are a developer looking to work with Twitter data, the Twitter V2 Rules API is definitely worth exploring.

Usage

Via Docker

docker run --env-file= -d --name= mastashake08/discord-twitter-bot:latest

By running this command you can pull the image directly from Docker Hub all you have to do is pass in a path to your .env file with your tokens.

Via Github Container Registry

docker pull ghcr.io/mastashake08/discord-twitter-bot:latest

If you rather use GCR then you can!

Via Node

If you decide to run from source then pull the repo, set the .env and run the code

 git clone https://github.com/mastashake08/discord-twitter-bot.git
 npm install
 cp .env.example .env
 #set values for TWITTER and DISCORD APIs in .env
 TWITTER_USER_NAME=
 DISCORD_TOKEN=
 DISCORD_CHANNEL_ID=
 BEARER_TOKEN=
 CHANNEL_MESSAGE= 
node main.js

Congrats, It’s Updated!

See it in action!

That’s pretty much all we had to do to update everything to use the new API. The added benefit is that it won’t show retweets in your discord server like before :0 if you enjoyed this consider becoming a patron on Patreon and help fund in-person coding classes for kids in Louisville, KY!

Follow Me On Social Media

Follow Me On Youtube!

Follow my YouTube account

Get Your Next Domain Cheap & Support The Channel

I use Namecheap for all of my domains! Whenever I need a cheap solution for a proof-of-concept project I grab a domain name for as little as $1! When you sign up and buy your first domain with Namecheap I get a commission, it’s a great way to get a quality service and support this platform!

Get Your Next Domain Cheap
CLICK HERE

Become A Sponsor

Open-source work is free to use but it is not free to develop. If you enjoy my content and would like to see more please consider becoming a sponsor on Github or Patreon! Not only do you support me but you are funding tech programs for at risk youth in Louisville, Kentucky.

Join The Newsletter

By joining the newsletter, you get first access to all of my blogs, events, and other brand-related content delivered directly to your inbox. It’s 100% free and you can opt out at any time!

Check The Shop

You can also consider visiting the official #CodeLife shop! I have my own clothing/accessory line for techies as well as courses designed by me covering a range of software engineering topics.