NickN
Convex Community14mo ago
9 replies
Nick

How to get `ctx` through indirection?

I'm writing a telegram bot that uses webhooks. I was able to set it up like this:

convex/http.ts
import { httpRouter } from "convex/server";
import { webhook } from "./telegramWebhook";

const http = httpRouter();

http.route({
  path: "/telegram/bot/webhook",
  method: "POST",
  handler: webhook,
});

export default http;


convex/telegramWebhook.ts
import { httpAction } from "./_generated/server";
import { webhookCallback } from "grammy";
import bot from "./bot";

const handleUpdate = webhookCallback(bot, "std/http");

export const webhook = httpAction(async (ctx, req) => {
  try {
    const url = new URL(req.url);
    if (url.searchParams.get("token") !== bot.token) {
      return new Response("not allowed", { status: 405 });
    }
    return await handleUpdate(req);
  } catch (err) {
    console.error(err);
    return new Response();
  }
});

export default webhook;


Now, in the bot itself, how can I access the convex ctx?
bot
import { Bot } from "grammy";
const bot = new Bot(process.env.TELEGRAM_BOT_SECRET!);

bot.command("start", (ctx) => ctx.reply("Welcome! Up and running."));

bot.command("getMessages", (ctx) => {
  // TODO: How do I get the convex ctx here?
  const poll = await messages.list(ctx); // not the same ctx!
  ctx.reply(`You have ${messages.length} messages.`)
});

export default bot


Can I do some sort of global / thread-local trick to get access to the convex context at a distance? Or do I need to somehow pass it through indirection? Would it be safe to try to attach the convex context to my bot somehow in the webhook http handler? How unique is the convex context? Is it different in each request or is it really just the same thing? Is there a reason we can't just import it from somewhere?
Was this page helpful?