Skip to content

Instantly share code, notes, and snippets.

@tmyt
Created Feb 7, 2022
Embed
What would you like to do?
const Options = "max_results=100&expansions=author_id&user.fields=name,profile_image_url";
addEventListener("scheduled", event => {
event.waitUntil(handleScheduled(event.request))
})
async function handleScheduled(request) {
await fetchTweets("user-screen-name-here");
}
async function fetchTweets(screenName) {
console.log(`Fetching tweets for ${screenName}`);
const authorization = `Bearer ${APP_TOKEN}`;
const uid = await KV.get(`UID_${screenName}`);
const sid = await KV.get(`SID_${screenName}`);
const resp = await fetch(
`https://api.twitter.com/2/users/${uid}/tweets?since_id=${sid}&${Options}`,
{
headers: { authorization }
}
);
const { data, meta, includes } = await resp.json();
console.log(`Processed ${meta.result_count} tweets`);
if(!data) return;
const { users } = includes;
for(const d of data){
const user = users.find(({ id }) => id === d.author_id);
await writeDiscord(screenName, {
content: `https://twitter.com/${screenName}/status/${d.id}`,
username: user.name,
avatar_url: user.profile_image_url,
});
}
await KV.put(`SID_${screenName}`, meta.newest_id);
}
async function writeDiscord(screenName, content) {
const uri = await KV.get(`WEBHOOK_${screenName}`);
return fetch(uri, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(content)
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment