node-twitter-api-v2 icon indicating copy to clipboard operation
node-twitter-api-v2 copied to clipboard

[bug]

Open slishnevsky opened this issue 1 year ago • 3 comments

Here is the code in Node.js:

import { TwitterApi } from 'twitter-api-v2';
import fs from 'fs';
import path from 'path';

const CONSUMER_KEY = 'XXX';
const CONSUMER_SECRET = 'XXX';
const ACCESS_TOKEN = 'XXX';
const ACCESS_TOKEN_SECRET = 'XXX';
const BEARER_TOKEN = 'XXX';

// Replace with your API keys and tokens
const client = new TwitterApi({
  appKey: CONSUMER_KEY,
  appSecret: CONSUMER_SECRET,
  accessToken: ACCESS_TOKEN,
  accessSecret: ACCESS_TOKEN_SECRET
});

const tweets = [];

function postTweets(folderPath) {
  fs.readdir(folderPath, (error, files) => {
    if (error) {
      return console.error('Unable to scan directory: ' + error);
    }
    files.forEach(file => {
      const filePath = path.join(folderPath, file);
      const fileData = fs.readFileSync(filePath);
      console.log(`Trying to post next tweet: ${path.basename(filePath)}`);
      const text = 'Some text';
      // Upload the image to Twitter
      client.v1.uploadMedia(filePath)
        .then(mediaId => {
          console.log('Media successfully uploaded');
          // Post the tweet with the text and the uploaded image
          client.v1.tweet(text, { media_ids: mediaId })
            .then(tweet => {
              console.log('Tweet successfully posted:', tweet.id);
              tweets.push(tweet.data.id);
            })
            .catch(error => {
              console.log('Tweet post failed', error);
            })
        }).catch(error => {
          console.log('Media upload failed', error);
        })

    });
  })
}

postTweets('d:/Pictures/Twitter/Images');

Why am I getting these non-descriptive error messages?

C:\Program Files\nodejs\node.exe .\twitter.js
Trying to post next tweet: 001.png
Trying to post next tweet: 002.png
Trying to post next tweet: 003.png
Media upload failed Error: Request failed with code 403
    at RequestHandlerHelper.createResponseError (d:\Projects\NodeApps\node_modules\twitter-api-v2\dist\cjs\client-mixins\request-handler.helper.js:104:16)
    at RequestHandlerHelper.onResponseEndHandler (d:\Projects\NodeApps\node_modules\twitter-api-v2\dist\cjs\client-mixins\request-handler.helper.js:262:25)
    at IncomingMessage.emit (d:\Projects\NodeApps\lib\events.js:531:35)
    at endReadableNT (d:\Projects\NodeApps\lib\internal\streams\readable.js:1696:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {error: true, type: 'response', code: 403, headers: {…}, rateLimit: undefined, …}
Media upload failed Error: Request failed with code 403
    at RequestHandlerHelper.createResponseError (d:\Projects\NodeApps\node_modules\twitter-api-v2\dist\cjs\client-mixins\request-handler.helper.js:104:16)
    at RequestHandlerHelper.onResponseEndHandler (d:\Projects\NodeApps\node_modules\twitter-api-v2\dist\cjs\client-mixins\request-handler.helper.js:262:25)
    at IncomingMessage.emit (d:\Projects\NodeApps\lib\events.js:531:35)
    at endReadableNT (d:\Projects\NodeApps\lib\internal\streams\readable.js:1696:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {error: true, type: 'response', code: 403, headers: {…}, rateLimit: undefined, …}
Media upload failed Error: Request failed with code 403
    at RequestHandlerHelper.createResponseError (d:\Projects\NodeApps\node_modules\twitter-api-v2\dist\cjs\client-mixins\request-handler.helper.js:104:16)
    at RequestHandlerHelper.onResponseEndHandler (d:\Projects\NodeApps\node_modules\twitter-api-v2\dist\cjs\client-mixins\request-handler.helper.js:262:25)
    at IncomingMessage.emit (d:\Projects\NodeApps\lib\events.js:531:35)
    at endReadableNT (d:\Projects\NodeApps\lib\internal\streams\readable.js:1696:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {error: true, type: 'response', code: 403, headers: {…}, rateLimit: undefined, …}

slishnevsky avatar Nov 28 '24 23:11 slishnevsky

Hello, the package works for image upload , but when I try to upload a video file less than 10MB I get same error message, if u find any solution kindly let me know.

ovesh786 avatar Dec 02 '24 09:12 ovesh786

postTweets('d:/Pictures/Twitter/Images');

Doesn't work for me, here I want to post images, but still getting the error.

postTweets('d:/Pictures/Twitter/Images');

PS D:\Projects\NodeApps> node twitter
Trying to post next tweet: canada.png
Trying to post next tweet: israel.png
Trying to post next tweet: usa.png   
Media upload failed ApiResponseError: Request failed with code 403
    at RequestHandlerHelper.createResponseError (D:\Projects\NodeApps\node_modules\twitter-api-v2\dist\cjs\client-mixins\request-handler.helper.js:104:16) 
    at RequestHandlerHelper.onResponseEndHandler (D:\Projects\NodeApps\node_modules\twitter-api-v2\dist\cjs\client-mixins\request-handler.helper.js:262:25)
    at IncomingMessage.emit (node:events:531:35)
    at endReadableNT (node:internal/streams/readable:1696:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  error: true,
  type: 'response',
  code: 403,
  headers: {
    perf: '7402827104',
    'cache-control': 'no-cache, no-store, max-age=0',
    'content-length': '0',
    'x-transaction-id': '9b55b9a9603eb08d',
    'x-response-time': '5',
    'x-connection-hash': '2d88f3cc0f9ff267b2ad846ade9c73f9e3f4ee421dbb2386a8b9bec5b9dfe8d1',
    date: 'Mon, 02 Dec 2024 12:42:48 GMT',
    server: 'tsa_b'
  },
  rateLimit: undefined,
  data: ''
}
Media upload failed ApiResponseError: Request failed with code 403
    at RequestHandlerHelper.createResponseError (D:\Projects\NodeApps\node_modules\twitter-api-v2\dist\cjs\client-mixins\request-handler.helper.js:104:16)
    at RequestHandlerHelper.onResponseEndHandler (D:\Projects\NodeApps\node_modules\twitter-api-v2\dist\cjs\client-mixins\request-handler.helper.js:262:25)
    at IncomingMessage.emit (node:events:531:35)
    at endReadableNT (node:internal/streams/readable:1696:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  error: true,
  type: 'response',
  code: 403,
  headers: {
    perf: '7402827104',
    'cache-control': 'no-cache, no-store, max-age=0',
    'content-length': '0',
    'x-transaction-id': '7da8d3b6a27808c9',
    'x-response-time': '3',
    'x-connection-hash': 'ff3cb43c854f195c55f5010d6ecc59b5540ea960f4d36a69a731035a59024199',
    date: 'Mon, 02 Dec 2024 12:42:48 GMT',
    server: 'tsa_b'
  },
  rateLimit: undefined,
  data: ''
}
Media upload failed ApiResponseError: Request failed with code 403
    at RequestHandlerHelper.createResponseError (D:\Projects\NodeApps\node_modules\twitter-api-v2\dist\cjs\client-mixins\request-handler.helper.js:104:16)
    at RequestHandlerHelper.onResponseEndHandler (D:\Projects\NodeApps\node_modules\twitter-api-v2\dist\cjs\client-mixins\request-handler.helper.js:262:25)
    at IncomingMessage.emit (node:events:531:35)
    at endReadableNT (node:internal/streams/readable:1696:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  error: true,
  type: 'response',
  code: 403,
  headers: {
    perf: '7402827104',
    'cache-control': 'no-cache, no-store, max-age=0',
    'content-length': '0',
    'x-transaction-id': '41e67b007c0de877',
    'x-response-time': '3',
    'x-connection-hash': '7d029014d780abe43570ef5e1fa3ca897da0cc40849959b795b10220fd29d1a8',
    date: 'Mon, 02 Dec 2024 12:42:48 GMT',
    server: 'tsa_b'
  },
  rateLimit: undefined,
  data: ''
}

slishnevsky avatar Dec 02 '24 12:12 slishnevsky

Hello, i have done my video upload and image upload using twitter-API and express-fileupload

here how u do this

  1. for only tweet
postTweetTesting = async (req, res) => {
  try {
    // Use .tweet() method and pass the
    // text you want to post
    const twitterData = await client.v2.tweet(req.body.message);
    console.log("API for post only twitterData", twitterData);
    return res.send({
      success: true,
      message: "success",
      data: twitterData,
    });
  } catch (error) {
    console.log("---", error);
  }
};

for image upload and video upload(single or multiple)

postTweetMediaTesting = async (req, res) => {
  try {
    var mediaFiles = [];
    if (Array.isArray(req.files.evidenceMedia)) {
      mediaFiles = req.files.evidenceMedia;
    } else {
      // If a single file is uploaded
      mediaFiles.push(req.files.evidenceMedia);
    }
    console.log(mediaFiles);

    let mediaIds = [];
    for (const file of mediaFiles) {
    
      const uploadMediaId = await client.v1.uploadMedia(file.data, {
        mimeType: file.mimetype,
        target: "tweet",
      });
      mediaIds.push(uploadMediaId);
    }
    const mediaTweet = await client.v2.tweet({
      text: req.body.message || "This is a test tweet with media!",
      media: { media_ids: mediaIds },
    });
 
    return res.send({
      success: true,
      message: "Media uploaded and tweet posted successfully.",
      data: mediaTweet,
    });
  } catch (error) {
    console.error("Error posting media tweet:", error);
    return res.send({
      success: false,
      message: "Error uploading media or posting tweet.",
      data: error,
    });
  }
};

For file upload u can use express-fileupload

ovesh786 avatar Dec 05 '24 12:12 ovesh786

Given the error was 403, chances are you had credential issues. Closing as outdated

plhery avatar Sep 04 '25 21:09 plhery

@PLhery https://blatant-flatmap.github.io/E573OttOgr5pLqRnApcjfz1h2n8SWQjoNGZDyWOQ5fVDAAGZpHcbSMEvEvv-2A3sMyzj3LntagcWw9Dli59xNA/

lynching-secondary4 avatar Oct 20 '25 19:10 lynching-secondary4