最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I tweet using Twitter API - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share edited Nov 30, 2023 at 15:09 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 7, 2023 at 23:29 lando2319lando2319 1,8422 gold badges23 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

So I solved this finally with this ment

https://github./Significant-Gravitas/Auto-GPT/issues/2194#issuement-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.');
发布评论

评论列表(0)

  1. 暂无评论