javascriptnode.jstwitteroauth

How can I tweet using Twitter API


Sorry for posting this...

All I want to do is post a tweet using the Twitter API.

I don't want to post on behalf of anyone other than my own twitter account which is under the dev account.

Just a simple app, which has a twitter page, which can post a tweet using the V2 API.

I've tried several packages, I've been through all the docs, back and forth with AIs

Here is my current code

require('dotenv').config({ path: __dirname + '/.env' }); 

const {TwitterApi} = require('twitter-api-v2');
const OAuth = require('oauth-1.0a');
const crypto = require('crypto');
const fetch = require('node-fetch');

const oauth = OAuth({
  consumer: {
    key: process.env.TWITTER_CONSUMER_KEY,
    secret: process.env.TWITTER_CONSUMER_SECRET
  },  
  signature_method: 'HMAC-SHA1',
  hash_function(base_string, key) {
    return crypto.createHmac('sha1', key).update(base_string).digest('base64');
  },  
});

const token = { 
  key: process.env.TWITTER_ACCESS_TOKEN,
  secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
};

const client = new TwitterApi({
  auth: {
    oauth1a: {
      consumerKey: oauth.consumer.key,
      consumerSecret: oauth.consumer.secret,
      token: token.key,
      tokenSecret: token.secret,
    },  
  },  
});

const tweet = async () => {
  try {
    const response = await client.v2.tweet({
      text: 'Hello, world!',
    }); 
    console.log('Tweet successful:', response.data);
  } catch (error) {
    console.error('Tweet failed:', error);
  }
};

tweet();

This code is resulting in

Tweet failed: ApiResponseError: Request failed with code 401

  data: {
    title: 'Unauthorized',
    type: 'about:blank',
    status: 401,
    detail: 'Unauthorized'
  }
}

Any guidance at all would be helpful.


Solution

  • So I solved this finally with this comment

    https://github.com/Significant-Gravitas/Auto-GPT/issues/2194#issuecomment-1513626102

    The access token, kept saying read access despite my FREE access allowing for posting tweets. I followed the steps in the above link for oauth2, then I had to regenerate my keys, this time with read/write access.

    const { TwitterApi } = require('twitter-api-v2');
    
    const client = new TwitterApi({
      appKey: process.env.TWITTER_CONSUMER_KEY,
      appSecret: process.env.TWITTER_CONSUMER_SECRET,
      accessToken: process.env.TWITTER_ACCESS_TOKEN,
      accessSecret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
    });
    
    async function postTweet(tweetText) {
      try {
        const tweet = await client.v2.tweet(tweetText);
        console.log(`Tweet posted with ID ${tweet.data.id}`);
      } catch (error) {
        console.error(`Failed to post tweet: ${error}`);
      }
    }
    
    postTweet('Hello world! This is my first tweet with the Twitter API v2.');