skip to Main Content

So I have this simple telegraf bot that works when I run it locally with node. I also managed to create some simple Lambda functions, but I can’t figure out how to actually run the bot on the lambda. I tried this:

const { Telegraf } = require("telegraf");

exports.handler = async (event) => {
  const bot = new Telegraf(<token goes here>);
  bot.start((ctx) => ctx.reply("๐Ÿ‘"));
  bot.launch();

  const response = {
    statusCode: 200,
    body: JSON.stringify('OK'),
};

return response;
};


But I’m sure this is not the way it is supposed to be implemented

2

Answers


  1. I’m not that familiar with telegraf, however, if you must have it on Lambda function, you can add its package as Lambda layer.

    See what Lambda layer and how to leverage it in the following aws docs.

    By the way, like everyone mentioned above in the comment section, Lambda has limited resource such 15 minutes execution time as well as Lambda is one of expensive AWS resources compare to EC2.
    Also if telegraf is a heavy package or its process takes longer than 15 minutes, the Lambda function will be failed and you will have to configure DLQ.

    Maybe for these reasons, people don’t recommend you to run telegraf on Lambda function.

    Idealy, you can find more architecture using Fargate or EC2.

    Login or Signup to reply.
  2. You should use bot.handleUpdate(update) but don’t forget to parse message before, because it could be a string, and even more โ€“ base64 encoded string, e.g.:

    const { Telegraf } = require("telegraf")
    
    exports.handler = async (event) => {
      let message
      try {
        if (!event.body) {
          throw new Error("unknown request type")
        }
        let body = event.body
        if (event.isBase64Encoded) {
          body = base64Decode(body)
        }
        message = JSON.parse(body)
      } catch (error) {
        return {
          statusCode: 400,
          body: error.message,
        }
      }
      try {
        const botToken = await getToken() // e.g. get bot token from AWS Secrets Manager
        const bot = new Telegraf(botToken)
        await bot.handleUpdate(message)
      } catch (error) {
        return {
          statusCode: 500,
          body: error.message,
        }
      }
    }
    
    function base64Decode(str) {
      return Buffer.from(str, "base64").toString("utf8")
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search