Skip to content

Instantly share code, notes, and snippets.

@tmyt
Created February 7, 2022 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmyt/93295813acfab09ff33dc55aabb5ec1d to your computer and use it in GitHub Desktop.
Save tmyt/93295813acfab09ff33dc55aabb5ec1d to your computer and use it in GitHub Desktop.
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