Skip to content

Instantly share code, notes, and snippets.

@checklyalex
Created April 24, 2024 11:33
Show Gist options
  • Save checklyalex/cf44dc668ba124aa4a8efe82eb1f48ee to your computer and use it in GitHub Desktop.
Save checklyalex/cf44dc668ba124aa4a8efe82eb1f48ee to your computer and use it in GitHub Desktop.
export const fetchLatestSMS = async (twilioClient, toNumber, timeout = 10000) => {
return new Promise((resolve, reject) => {
setTimeout(async () => {
try {
// Fetch the latest message to a specific number
const messages = await twilioClient.messages.list({
to: toNumber, // Filter messages sent to this number
limit: 1, // Fetch only the most recent message
order: 'desc' // Order by date sent in descending order
});
const latestMessage = messages[0];
if (latestMessage && latestMessage.body) {
resolve(latestMessage.body);
} else {
reject(new Error("No new message received"));
}
} catch (error) {
reject(error);
}
}, timeout); // Wait for 10 seconds to allow SMS to be delivered
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment