Nodejs代码在Lambda函数中没有做任何事情就退出了.如何修复?



我是JS和AWS Lambda的新手。我很难制作使用Telegram API和OpenAI API正常运行的代码。基本上,Telegram聊天机器人需要一个提示并发送给dale请求一个图像,该图像返回一个url以显示在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;
}
};

代码工作在我的本地服务器,但不是当我移动到Lambda。代码基本上只是运行"成功"。几乎没有等待Telegram聊天机器人的提示就立即退出了。如果有人能给我建议并指出正确的方向,我将不胜感激。

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

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

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

我认为这是因为你的Lambda处理程序的Async特性和没有正确等待,它提前退出了。

相关内容

最新更新