繁体   English   中英

Nodejs 代码在 Lambda 函数中没有执行任何操作就退出了。 怎么修?

[英]Nodejs code exited without doing anything in Lambda Function. How to fix?

我是 JS 和 AWS Lambda 的新手。 我很难编写同时使用 Telegram API 和 OpenAI APi 的代码来正常运行。 基本上 Telegram 聊天机器人接受提示并发送给 Dalle 以请求图像,该图像返回一个 url 以在电报上显示。

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;
  }
};

该代码在我的本地服务器上有效,但当我将其移至 Lambda 时却无效。 该代码基本上只是“成功”运行并几乎立即退出,而无需等待 Telegram 聊天机器人的提示。 如果有人能给我建议并指出正确的方向,我将不胜感激。

看起来你应该等待bot.onText()

我相信由于您的 Lambda 处理程序的异步性质并且没有正确等待,它会提前退出。

您需要找到一种方法来等待回调执行,也许创建如下所示的新承诺:

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!'),
    };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM