Created
May 3, 2024 00:46
-
-
Save faustoct1/274bb1227b18c16ae28612d48676155a to your computer and use it in GitHub Desktop.
Tweet text & images via api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const admin = require("firebase-admin") | |
/* | |
const serviceAccount = require("./../key.json"); | |
const { exit } = require("process"); | |
admin.initializeApp({ | |
credential: admin.credential.cert(serviceAccount) | |
}) | |
*/ | |
const axios = require('axios'); | |
const { TwitterApi } = require( 'twitter-api-v2') | |
const tweet = async (data,callback) => { | |
console.log('tweet started') | |
if(!data) return null | |
const TWITTER_CREDENTIALS = JSON.parse(process.env.TWITTER_API || '{"appKey":"","appSecret":"","accessToken":"","accessSecret":""}') | |
const client = new TwitterApi(TWITTER_CREDENTIALS) | |
await callback(client,data) | |
console.log('tweet finished') | |
} | |
const getImage = async (remoteImageUrl) => { | |
// Download the remote image | |
const response = await axios.get(remoteImageUrl, { responseType: 'arraybuffer' }); | |
return {data:response.data,mime:response.headers['content-type']} | |
} | |
const getFromDb = async () => { | |
//XXX implement here | |
return null | |
} | |
const postPlaces = async () => { | |
const post = await getFromDb() | |
if(!post) return | |
await Promise.all([ | |
tweet(post, async (client,post)=>{ | |
try{ | |
let media = {} | |
if(post.image){ | |
const {data,mime} = await getImage(post.image) | |
const mediaId = await client.v1.uploadMedia(data,{ mimeType: mime }); | |
media = { media: {media_ids: [mediaId]} } | |
} | |
console.log(await client.v2.tweet(post.text,media)) | |
}catch(e){ | |
console.log(e) | |
} | |
}) | |
]) | |
} | |
exports.runTwitter = async () => { | |
try{ | |
console.log('runTwitter started') | |
try{ | |
await postPlaces() | |
}catch(e){ | |
console.log(e) | |
} finally{ | |
} | |
console.log('runTwitter finished') | |
}catch(e){ | |
console.log(e) | |
} | |
} | |
/* | |
//Uncomment to run locally. Execute "node wcdt-tweet.js" to run | |
(async ()=>{ | |
const { exit } = require("process") | |
await this.runTwitter() | |
exit(0) | |
})() | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment