Skip to content

Convex component for sending/receiving SMS messages with Twilio

License

Notifications You must be signed in to change notification settings

get-convex/twilio

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

86 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Convex Twilio Component

npm version

Note: Convex Components are currently in beta

Send and receive SMS messages in your Convex app using Twilio.

import Twilio from "@convex-dev/twilio";
import { components } from "./_generated/server.js";

export const twilio = new Twilio(components.twilio, {
  default_from: process.env.TWILIO_PHONE_NUMBER!,
});

export const sendSms = internalAction({
  handler: async (ctx, args) => {
    return await twilio.sendMessage(ctx, {
      to: "+14151234567",
      body: "Hello, world!",
    });
  },
});

Prerequisites

Twilio Phone Number

Create a Twilio account and, if you haven't already, create a Twilio Phone Number.

Note the Phone Number SID of the phone number you'll be using, you'll need it in a moment.

Convex App

You'll need a Convex App to use the component. Follow any of the Convex quickstarts to set one up.

Installation

Install the component package:

npm install @convex-dev/twilio

Create a convex.config.ts file in your app's convex/ folder and install the component by calling use:

// convex/convex.config.js
import { defineApp } from "convex/server";
import twilio from "@convex-dev/twilio/convex.config.js";

const app = defineApp();
app.use(twilio);

export default app;

Set your API credentials:

npx convex env set TWILIO_ACCOUNT_SID=ACxxxxx
npx convex env set TWILIO_AUTH_TOKEN=xxxxx

Instantiate a Twilio Component client in a file in your app's convex/ folder:

// convex/example.ts
import Twilio from "@convex-dev/twilio";
import { components } from "./_generated/server.js";

export const twilio = new Twilio(components.twilio, {
  // optionally pass in the default "from" phone number you'll be using
  // this must be a phone number you've created with Twilio
  default_from: process.env.TWILIO_PHONE_NUMBER!,
});

Register Twilio webhook handlers by creating an http.ts file in your convex/ folder and use the client you've exported above:

// http.ts
import { twilio } from "./example";
import { httpRouter } from "convex/server";

const http = httpRouter();
// this call registers the routes necessary for the component
twilio.registerRoutes(http);
export default http;

This will register two webhook HTTP handlers in your your Convex app's deployment:

  • YOUR_CONVEX_SITE_URL/twilio/message-status - capture and store delivery status of messages you send.
  • YOUR_CONVEX_SITE_URL/twilio/incoming-message - capture and store messages sent to your Twilio phone number.

Note: You may pass a custom http_prefix to registerRoutes if you want to route Twilio endpoints somewhere other than YOUR_CONVEX_SITE_URL/twilio.

Sending Messages

To send a message use the Convex action sendMessage exposed by the client, for example:

// convex/messages.ts
import { v } from "convex/values";
import { internalAction } from "./_generated/server";

export const sendSms = internalAction({
  args: {
    to: v.string(),
    body: v.string(),
  },
  handler: async (ctx, args) => {
    return await twilio.sendMessage(ctx, args);
  },
});

By querying the message (see below) you can check for the status (Twilio Statuses). The component subscribes to status updates and writes the most up-to-date status into the database.

Receiving Messages

To receive messages, you will associate a webhook handler provided by the component with the Twilio phone number you'd like to use. The webhook handler is mounted at

YOUR_CONVEX_SITE_URL/incoming-message

You can associate it with your Twilio phone number in two ways:

  1. Using the Twilio console in the "Configure" tab of the phone number, under "Messaging Configuration" -> "A messsage comes in" -> "URL".

  2. By calling registerIncomingSmsHandler exposed by the component client, passing it the phone number's SID:

// convex/messages.ts

// ...

export const registerIncomingSmsHandler = internalAction({
  args: {},
  handler: async (ctx) => {
    return await twilio.registerIncomingSmsHandler(ctx, {
      sid: "YOUR_TWILIO_PHONE_NUMBER_SID",
    });
  },
});

Now, incoming messages will be captured by the component and logged in the messages table.

You can execute your own logic upon receiving an incoming message, by providing a callback when instantiating the Twilio Component client:

// convex/example.ts
import { Twilio, messageValidator } from "@convex-dev/twilio";

const twilio = new Twilio(components.twilio, {
  default_from: process.env.TWILIO_PHONE_NUMBER || "",
});
twilio.incomingMessageCallback = internal.example.handleIncomingMessage;

export const handleIncomingMessage = internalMutation({
  args: messageValidator,
  handler: async (ctx, message) => {
    // Use ctx here to update the database or schedule other actions.
    // This is in the same transaction as the component's message insertion.
    console.log("Incoming message", message);
  },
});

Querying Messages

To list all the mssages, use the list method in your Convex function.

To list all the incoming or outgoing messages, use listIncoming and listOutgoing methods:

// convex/messages.ts

// ...

export const list = query({
  args: {},
  handler: async (ctx) => {
    const allMessages = await twilio.list(ctx);
    const receivedMessages = await twilio.listIncoming(ctx);
    const sentMessages = await twilio.listOutgoing(ctx);
    return { allMessages, receivedMessages, sentMessages };
  },
});

To get a single message by its sid, use getMessageBySid:

export const getMessageBySid = query({
  args: {
    sid: v.string(),
  },
  handler: async (ctx, args) => {
    return await twilio.getMessageBySid(ctx, args);
  },
});

Get messages by the "to" phone number:

export const getMessagesTo = query({
  args: {
    to: v.string(),
  },
  handler: async (ctx, args) => {
    return await twilio.getMessagesTo(ctx, args);
  },
});

Get messages by the "from" phone number:

export const getMessagesFrom = query({
  args: {
    from: v.string(),
  },
  handler: async (ctx, args) => {
    return await twilio.getMessagesFrom(ctx, args);
  },
});

You can also get all messages to and from a particular number:

export const getMessagesByCounterparty = query({
  args: {
    from: v.string(),
  },
  handler: async (ctx, args) => {
    return await twilio.getMessagesByCounterparty(ctx, args);
  },
});

πŸ§‘β€πŸ« What is Convex?

Convex is a hosted backend platform with a built-in database that lets you write your database schema and server functions in TypeScript. Server-side database queries automatically cache and subscribe to data, powering a realtime useQuery hook in our React client. There are also clients for Python, Rust, ReactNative, and Node, as well as a straightforward HTTP API.

The database supports NoSQL-style documents with opt-in schema validation, relationships and custom indexes (including on fields in nested objects).

The query and mutation server functions have transactional, low latency access to the database and leverage our v8 runtime with determinism guardrails to provide the strongest ACID guarantees on the market: immediate consistency, serializable isolation, and automatic conflict resolution via optimistic multi-version concurrency control (OCC / MVCC).

The action server functions have access to external APIs and enable other side-effects and non-determinism in either our optimized v8 runtime or a more flexible node runtime.

Functions can run in the background via scheduling and cron jobs.

Development is cloud-first, with hot reloads for server function editing via the CLI, preview deployments, logging and exception reporting integrations, There is a dashboard UI to browse and edit data, edit environment variables, view logs, run server functions, and more.

There are built-in features for reactive pagination, file storage, reactive text search, vector search, https endpoints (for webhooks), snapshot import/export, streaming import/export, and runtime validation for function arguments and database data.

Everything scales automatically, and it’s free to start.

About

Convex component for sending/receiving SMS messages with Twilio

Resources

License

Stars

Watchers

Forks

Packages

No packages published