Skip to content

Instantly share code, notes, and snippets.

@sojinsamuel
Last active May 15, 2024 19:08
Show Gist options
  • Save sojinsamuel/07d59fb3ba5b8f809743690044f83d7d to your computer and use it in GitHub Desktop.
Save sojinsamuel/07d59fb3ba5b8f809743690044f83d7d to your computer and use it in GitHub Desktop.
// Part 1
import OAuth from "oauth-1.0a";
import crypto from "crypto";
import got from "got";
import { config } from "dotenv";
config();
const apiKey = process.env.TWITTER_API_KEY;
const apiKeySecret = process.env.TWITTER_API_KEY_SECRET;
const accessToken = process.env.TWITTER_ACCESS_TOKEN;
const accessTokenSecret = process.env.TWITTER_ACCESS_TOKEN_SECRET;
const ENDPOINT = "https://api.twitter.com/2/tweets";
const EXPANSIONS_AND_FIELDS =
"expansions=attachments.media_keys&media.fields=url,variants";
const oauth = OAuth({
consumer: { key: apiKey, secret: apiKeySecret },
signature_method: "HMAC-SHA1",
hash_function(baseString, key) {
return crypto.createHmac("sha1", key).update(baseString).digest("base64");
},
});
const tokenPair = {
key: accessToken,
secret: accessTokenSecret,
};
export async function getTweetMedia(id) {
if (!id) {
throw new Error("Tweet id is required");
}
try {
const authHeader = oauth.toHeader(
oauth.authorize(
{
url: `${ENDPOINT}/${id}?${EXPANSIONS_AND_FIELDS}`,
method: "GET",
},
tokenPair
)
);
const response = await got.get(`${ENDPOINT}/${id}?${EXPANSIONS_AND_FIELDS}`, {
responseType: "json",
headers: {
Authorization: authHeader["Authorization"],
accept: "application/json",
},
});
if (response.body.includes) {
return response.body;
}
return { ...response.body, notfound: "No media found" };
} catch (error) {
return error;
}
}
// Part 2
import sgMail from "@sendgrid/mail";
const { SENDGRID_API_KEY, FROM_EMAIL_ADDRESS } = process.env;
sgMail.setApiKey(SENDGRID_API_KEY);
export async function sendEmail(to, html, sendAt = 0) {
try {
await sgMail.send({
to,
from: FROM_EMAIL_ADDRESS,
subject: "Your Download is Ready",
html: `<pre>${html}</pre>`,
sendAt,
});
console.log("Email sent");
} catch (error) {
console.error(JSON.stringify(error, null, 2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment