/Twitter-Bots-Maybe

Maybe Twitter Bots?

Primary LanguageJavaScriptMIT LicenseMIT

Twitter Bot with Node.js

At the present time, the hellscape formerly known as Twitter has made drastic changes to the API and its policies. The free tier of the API is now extremely limited. All v1 endpoints are no longer available or supported I think? The node.js package I'm using here is also no longer maintained.

You can read more in this discussion.

But if you still want to try, here is the basic setup for creating a Twitter bot using Node.js and the twitter-api-v2 library.

Setup

Dependencies

npm install dotenv twitter-api-v2

Configure Environment Variables

Create a .env file and add your keys:

TWITTER_API_KEY=your_api_key
TWITTER_API_SECRET=your_api_secret
TWITTER_ACCESS_TOKEN=your_access_token
TWITTER_ACCESS_TOKEN_SECRET=your_access_token_secret

Initialize API Client

import { config } from 'dotenv';
import { TwitterApi } from 'twitter-api-v2';

config();

const twitterKeys = {
  appKey: process.env.TWITTER_API_KEY,
  appSecret: process.env.TWITTER_API_SECRET,
  accessToken: process.env.TWITTER_ACCESS_TOKEN,
  accessSecret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
};

const client = new TwitterApi(twitterKeys);

Tweet

This function generates a random number and tweets a message containing that number.

async function tweet() {
  const r = Math.floor(Math.random() * 100000);
  const response = await client.v2.tweet(
    `Today's tweet is brought to you by the number ${r}!`
  );
  const { id, text } = response.data;
  console.log(`${id} : ${text}`);
}

Upload Media

This function tweets an image with alt text.

async function tweetImage() {
  const mediaId = await client.v1.uploadMedia('rainbow.png', { mimeType: 'image/png' });
  await client.v1.createMediaMetadata(mediaId, { alt_text: { text: 'Rainbow!' } });
  const response = await client.v2.tweet({
    text: 'Rainbow!',
    media: { media_ids: [mediaId] },
  });
  const { id, text } = response.data;
  console.log(`${id} : ${text}`);
}

Usage

To tweet text or an image, uncomment the respective function call in your code and run the script.

node bot.js

Additional Resources