Home > front end >  Nodejs code exited without doing anything in Lambda Function. How to fix?
Nodejs code exited without doing anything in Lambda Function. How to fix?

Time:12-20

I am a newbie at JS and AWS Lambda. I have difficulty making a code that using both Telegram API and OpenAI APi run properly. Basically Telegram chatbot takes a prompt and send to Dalle to request for a image which returns a url to display on telegram.

import { Configuration, OpenAIApi } from "openai";
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const TelegramBot = require("node-telegram-bot-api");
const dotenv = require("dotenv");

dotenv.config();
const token = process.env.TELEGRAM_BOT_TOKEN;
const configuration = new Configuration({
   apiKey: process.env.OPENAI_API_KEY,
   });
const openai = new OpenAIApi(configuration);
const bot = new TelegramBot(token, { polling: true });

export const handler = async (event, context) => {
  
  try {
   
    const result = async function generateImage(prompt) {
      return await openai.createImage({
        prompt: prompt ,
        n: 1,
        size: "1024x1024",
      });
    };
    
    bot.onText(/\/image (. )/, async (msg, match) => {
      const chatId = msg.chat.id;
      bot.sendMessage(chatId, "Your image is being generated. Please wait.");
      const response = await result(match[1]);
      bot.sendPhoto(chatId, response.data.data[0].url, { caption: match[1] });
      });
    return {
      statusCode:200,
      body: JSON.stringify('End of Lambda!'),
    };
  } catch (err) {
    console.log(err);
    throw err;
  }
};

The code works on my local server but not when i move it to Lambda. The code basically just ran "successfully" and exited almost immediately without waiting for the prompt from Telegram chatbot. Really appreciate if anyone can advise and point me in the correct direction.

CodePudding user response:

Looks like you should await bot.onText()

I believe that because of the Async nature of your Lambda handler and not properly awaiting, it's exiting early.

CodePudding user response:

You need to find a way to wait for the callback to execute, maybe creating a new promise like below:

await new Promise((resolve) => {
    bot.onText(/\/image (. )/, async (msg, match) => {
      const chatId = msg.chat.id;
      bot.sendMessage(chatId, "Your image is being generated. Please wait.");
      const response = await result(match[1]);
      bot.sendPhoto(chatId, response.data.data[0].url, { caption: match[1] });
      
     resolve(undefined);

  });
});

return {
      statusCode:200,
      body: JSON.stringify('End of Lambda!'),
    };
  • Related