gpt4 book ai didi

javascript - 如何在 Node.js 中将数据从一种方法传输到另一种方法?

转载 作者:行者123 更新时间:2023-11-30 20:32:29 27 4
gpt4 key购买 nike

我正在使用 Telegram bot API 和 AWS S3 从存储桶中读取数据。我需要在 Telgraf 中使用来自 s3 方法的数据方法,但我不知道如何:

'use strict'

const Telegraf = require('telegraf');
const bot = new Telegraf('TOKEN')

var AWS = require('aws-sdk')
var s3 = new AWS.S3({
accessKeyId: 'key',
secretAccessKey: 'secret'
})

var params = {Bucket: 'myBucket', Key:"ipsum.txt"};

var s3Promise = s3.getObject(params, function(err, data) {
if (err) console.log(err, err.stack);
else
var words= data.Body.toString(); //WHAT I WANT IN IN COMMAND METHOD
console.log('\n' + words+ '\n') //Returns ipsum.txt as string on console
})

bot.command('s', (ctx) => { //Bot Command
s3Promise; //Returns ipsum.txt as string on console
ctx.reply('Check console') //Meesage in Telegram
//ctx.reply(<I WANT data.Body.toSting() HERE>)
});

const { PORT = 3000 } = process.env
bot.startWebhook('/', null, PORT)

如何在 ctx.reply() 中使用来自 s3.getObject 方法的数据?

最佳答案

如果您想将文件作为附件发送,您必须使用:ctx.replyWithDocument。除此之外,您的问题是:How do I return the response from an asynchronous call?

在这种特殊情况下,您可以使用 s3.getObject(params).promise() 以避免回调 API,并在您的 bot.command 中轻松使用它> 听众。

使用 async/await (Node >= 7.6) 你的代码可以这样写

'use strict';

const Telegraf = require('telegraf');
const bot = new Telegraf('TOKEN');

const AWS = require('aws-sdk');
const s3 = new AWS.S3({
accessKeyId: 'key',
secretAccessKey: 'secret'
});

const params = {
Bucket: 'myBucket',
Key: 'ipsum.txt'
};

bot.command('s', async ctx => { // Bot Command

try {

// If you're sending always the same file and it won't change
// too much, you can cache it to avoid the external call everytime
const data = await s3.getObject(params).promise();

ctx.reply('Check console'); // Message in Telegram

// This will send the file as an attachment
ctx.replyWithDocument({
source: data.Body,
filename: params.Key
});

// or just as text
ctx.reply(data.Body.toString());

} catch(e) {
// S3 failed
ctx.reply('Oops');
console.log(e);
}
});

const {
PORT = 3000
} = process.env;

bot.startWebhook('/', null, PORT);

有关如何使用文件的更多信息可以在 telegraf docs 上找到

PS:我测试了代码,它完全可以工作:

enter image description here

关于javascript - 如何在 Node.js 中将数据从一种方法传输到另一种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50190880/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com