Created
August 14, 2024 06:02
-
-
Save trentrand/1d6a86a90f5dfc9392e72469e2a75ddb to your computer and use it in GitHub Desktop.
Get Featured Tweets
This file contains hidden or 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
#!/usr/bin/env node | |
const { execSync } = require('child_process'); | |
const fs = require('fs'); | |
const path = require('path'); | |
const tweetIds = [ | |
'1723011519942648318', | |
'1641908734845755392', | |
'1495949891503366148' | |
]; | |
function replaceEntitiesWithLinks(body, entities) { | |
const { hashtags, mentionedUsers, urls } = entities; | |
const uniqueHashtags = [...new Set(hashtags)]; | |
const uniqueMentionedUsers = [...new Set(mentionedUsers)]; | |
const uniqueUrls = [...new Set(urls)]; | |
let updatedBody = body; | |
uniqueHashtags.forEach(tag => { | |
const regex = new RegExp(`#${tag}\\b`, 'g'); | |
updatedBody = updatedBody.replace(regex, `<a href="https://twitter.com/hashtag/${tag}">#${tag}</a>`); | |
}); | |
uniqueMentionedUsers.forEach(user => { | |
const regex = new RegExp(`@${user}\\b`, 'g'); | |
updatedBody = updatedBody.replace(regex, `<a href="https://twitter.com/${user}">@${user}</a>`); | |
}); | |
uniqueUrls.forEach(url => { | |
const regex = new RegExp(`\\b${url}\\b`, 'g'); | |
updatedBody = updatedBody.replace(regex, `<a href="${url}">${url}</a>`); | |
}); | |
return updatedBody; | |
} | |
function formatDate(inputDateString) { | |
const date = new Date(inputDateString); | |
if (isNaN(date.getTime())) { | |
throw new Error('Invalid date string'); | |
} | |
const formatter = new Intl.DateTimeFormat('en-US', { | |
day: 'numeric', | |
month: 'short', | |
year: 'numeric' | |
}); | |
let formattedDate = formatter.format(date).replace('.', ''); | |
return formattedDate; | |
} | |
const fetchTweetDetails = (id) => { | |
try { | |
const output = execSync(`npx rettiwt-api tweet details ${id}`).toString(); | |
const details = JSON.parse(output); | |
return { | |
id: details.id, | |
timestamp: formatDate(details.createdAt), | |
author: { | |
username: details.tweetBy.userName, | |
imageUrl: details.tweetBy.profileImage, | |
}, | |
body: replaceEntitiesWithLinks(details.fullText, details.entities), | |
}; | |
} catch (error) { | |
console.error(`Error fetching tweet ${id}:`, error); | |
return null; | |
} | |
}; | |
const main = () => { | |
try { | |
const tweets = tweetIds.map(id => fetchTweetDetails(id)).filter(tweet => tweet !== null); | |
fs.writeFileSync('posts.json', JSON.stringify(tweets, null, 2)); | |
console.log('Posts have been written to posts.json'); | |
} catch (error) { | |
console.error('Error:', error); | |
} | |
}; | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment