Skip to content

Broadcast

Create a cron that sends daily messages to your redis database subscribers. This app can run daily or according to your code:

Main code

Start the cron with the DB of subscribers

src/index.ts
const redisClient = await getRedisClient();
startCron(redisClient); 
 
run(async (context: HandlerContext) => {
  // Your logic
});

Cron middleware

Install dependencies

cmd
yarn add node-cron

Run a node cron daily to send message to users

src/lib/cron.ts
import cron from "node-cron";
import { xmtpClient } from "@xmtp/message-kit";
import { RedisClientType } from "@redis/client";
 
export async function startCron(redisClient: RedisClientType) {
  // Daily task
  const client = await xmtpClient();
  console.log("Starting daily cron");
  cron.schedule(
    "0 0 * * *", // Daily or every 5 seconds in debug mode
    async () => {
      const keys = await redisClient.keys("*");
      console.log(`Running daily task. ${keys.length} subscribers.`);
      for (const address of keys) {
        const subscriptionStatus = await redisClient.get(address);
        if (subscriptionStatus === "subscribed") {
          console.log(`Sending daily update to ${address}`);
          // Logic to send daily updates to each subscriber
          const conversation = await client?.conversations.newConversation([
            address,
          ]);
          await conversation.send("Here is your daily update!");
        }
      }
    },
    {
      scheduled: true,
      timezone: "UTC",
    },
  );
}