draftbit / twitter-lite

A tiny, full-featured, flexible client / server library for the Twitter API
https://npm.im/twitter-lite
MIT License
794 stars 96 forks source link

How to post link text / images #185

Open pguardiario opened 2 years ago

pguardiario commented 2 years ago

Can someone point me to some docs? I'm trying html, markdown, I'm out of guesses. Thanks in advance

charlesr1971 commented 2 years ago

Please nudge the authors to approve my PR:

https://github.com/draftbit/twitter-lite/pull/187

This provides proper support for uploading images, using the:

POST media/upload [v1.1] endpoint

This can then be combined with the:

POST statuses/update [v1.1] endpoint

So that a tweet can be posted, with an image

charlesr1971 commented 2 years ago

Once my PR is merged, this is the code you will need:

async function createNewTwitterClient (subdomain, extension, response, twitterAppConfig, version) {
  const twitter = require(‘twitter-lite’);
  return new twitter({
    subdomain,
    consumer_key: twitterAppConfig.consumerKey, // from Twitter.
    consumer_secret: twitterAppConfig.consumerSecret,
    extension, // true is the default (this must be set to false for v2 endpoints),
    access_token_key: twitterAppConfig.accessTokenKey, // from your User (oauth_token)
    access_token_secret: twitterAppConfig.accessTokenSecret, // from your User (oauth_token_secret)
    bearer_token: response ? response?.access_token : null,
    version
  });
}

async function shareTwitterCircle(filename, twitterAppConfig, message) {
  const twitterApiClient = await createNewTwitterClient('api', true, null, twitterAppConfig,'1.1');
  const uploadClient = await createNewTwitterClient('upload', false, null, twitterAppConfig,'1.1');
  const uploadResponse = await uploadClient.getBearerToken();
  const twitterUploadClient = await createNewTwitterClient('upload', true, uploadResponse, twitterAppConfig,'1.1');
  const mediaFile = path.join(someDir, filename);
  return new Promise(function (resolve, reject) {
    const base64image = Buffer.from(mediaFile).toString('base64');
    twitterUploadClient.post('media/upload', { media_data: base64image }).then(media => {
      const media_id = media.media_id_string;
      twitterApiClient.post('statuses/update', { status: message, media_ids: media_id }).then(tweet => {
        resolve(tweet);
      }).catch((err)=>{
        reject(err);
      });
    }).catch((err)=>{
      reject(err);
    });
  });
}

const filename = 'some/file/path',
  twitterAppConfig = {
    consumerKey: ‘CONSUMER_KEY’,
    consumerSecret: ‘CONSUMER_SECRET’,
    accessTokenKey: ‘ACCESS_TOKEN_KEY’,
    accessTokenSecret: ‘ACCESS_TOKEN_SECRET’,
  },
  message = 'Hello World!';

(async function () {
  const tweet = await shareTwitterCircle(filename, twitterAppConfig, message);
})();
pguardiario commented 2 years ago

It feels like this project is abandoned so I'm looking for another one. Anyone have a suggestion?