From 866dba98c1864654b0efcbe83e2ae0f54055af36 Mon Sep 17 00:00:00 2001 From: Derk Weijers Date: Mon, 21 Aug 2023 09:05:24 +0200 Subject: [PATCH] Switch to v2 of the Twitter API --- .env.example | 5 +---- package.json | 2 +- src/utils/TwitterClientV2.ts | 22 +++++++++++++--------- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/.env.example b/.env.example index d23d847..12c98fa 100644 --- a/.env.example +++ b/.env.example @@ -2,7 +2,4 @@ AMQP_URL= DEBUG= DB_LOCATION= SENTRY_DSN= -API_KEY= -API_SECRET= -ACCESS_TOKEN= -ACCESS_TOKEN_SECRET= +BEARER_TOKEN= diff --git a/package.json b/package.json index 58eb1a6..8405835 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snapi-twitter-bot", - "version": "1.5.0", + "version": "1.6.0", "description": "The official Twitter bot for the Spaceflight News API.", "main": "app.js", "scripts": { diff --git a/src/utils/TwitterClientV2.ts b/src/utils/TwitterClientV2.ts index f3905f6..ed08a88 100644 --- a/src/utils/TwitterClientV2.ts +++ b/src/utils/TwitterClientV2.ts @@ -1,13 +1,17 @@ -import {TweetV2PostTweetResult, TwitterApi} from 'twitter-api-v2'; +import {TweetV2PostTweetResult, TwitterApi, TwitterApiReadWrite} from 'twitter-api-v2'; import {Tweet} from "../entity/Tweet"; class TwitterClientV2 { - private client = new TwitterApi({ - appKey: process.env.API_KEY!, - appSecret: process.env.API_SECRET!, - accessToken: process.env.ACCESS_TOKEN!, - accessSecret: process.env.ACCESS_TOKEN_SECRET!, - }).v2; + private client: TwitterApiReadWrite + + constructor(bearerToken?: string) { + // Proccess.env.BEARER_TOKEN can be empty, so we need to check for that. + if (!bearerToken) { + throw new Error("No bearer token provided"); + } + + this.client = new TwitterApi(bearerToken).readWrite; + } async sendTweet(tweet: Tweet): Promise { const tweetText = `New ${tweet.type} from ${tweet.newsSite.name}: ${tweet.title} - ${tweet.url} #space #spaceflight #news`; @@ -15,9 +19,9 @@ class TwitterClientV2 { if (process.env.DEBUG) { return console.log("DEBUG!", tweetText); } else { - return this.client.tweet(tweetText); + return this.client.v2.tweet(tweetText) } } } -export const twitterClientV2: TwitterClientV2 = new TwitterClientV2(); +export const twitterClientV2: TwitterClientV2 = new TwitterClientV2(process.env.BEARER_TOKEN);