Skip to content

Instantly share code, notes, and snippets.

@annthurium
Created May 11, 2020 18:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save annthurium/03f9acd190eaac0ce329149a3005bbca to your computer and use it in GitHub Desktop.
Save annthurium/03f9acd190eaac0ce329149a3005bbca to your computer and use it in GitHub Desktop.
Send a text message with Twilio and Deno
import * as base64 from "https://denopkg.com/chiefbiiko/base64/mod.ts";
const getAffirmations = async (fileName: string): Promise<Array<string>> => {
const decoder = new TextDecoder("utf-8");
const text: string = decoder.decode(await Deno.readFile("affirmations.txt"));
return text.split("\n");
};
const affirmations: Array<string> = await getAffirmations("affirmations.txt");
const affirmation =
affirmations[Math.floor(Math.random() * affirmations.length)];
const accountSid: string | undefined = Deno.env.get("TWILIO_ACCOUNT_SID");
const authToken: string | undefined = Deno.env.get("TWILIO_AUTH_TOKEN");
const fromNumber: string = "Replace with your Twilio number";
const toNumber: string = "Replace with your cell number";
const sendTextMessage = async (
messageBody: string,
accountSid: string | undefined,
authToken: string | undefined,
fromNumber: string,
toNumber: string,
): Promise<any> => {
if (!accountSid || !authToken) {
console.log(
"Your Twilio account credentials are missing. Please add them.",
);
return;
}
const url: string =
`https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages.json`;
const encodedCredentials: string = base64.fromUint8Array(
new TextEncoder().encode(`${accountSid}:${authToken}`),
);
const body: URLSearchParams = new URLSearchParams({
To: toNumber,
From: fromNumber,
Body: messageBody,
});
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": `Basic ${encodedCredentials}`,
},
body,
});
return response.json();
};
const response = await sendTextMessage(
affirmation,
accountSid,
authToken,
fromNumber,
toNumber,
);
console.log(response);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment