【问题标题】:How to work with firebase realtime database from Firebase Functions? (Telegram Bot)如何使用 Firebase Functions 中的 firebase 实时数据库? (电报机器人)
【发布时间】:2021-01-13 08:33:44
【问题描述】:

我想通过 Telegram bot 使用 Telegraf 存储和接收来自 firebase 实时数据库的数据。

我正在为此使用 Firebase Functions / Cloud Functions。

目前在数据库中存储数据正在工作,但我不知道如何从 firebase 获取数据,然后将其作为电报消息发送。

以下是 /database 命令的响应

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const Telegraf = require('telegraf');
admin.initializeApp();

const bot = new Telegraf(functions.config().telegram_token.key);
bot.hears('hello', (ctx) => ctx.reply('Hi from Firebase Function!'));

bot.command('database', (ctx) => {
    // store data on firebase realtime database - it's working
    admin.database().ref('users/' + ctx.message.chat.id).set({
        username: ctx.message.from.first_name,
        email: 'test@test.gmail.com',
      });
    // HOW TO? get data from firebase realtime database
    const userId = ctx.message.chat.id;
    const dataFromDb = admin.database().ref('users/' + userId).once('value');
    ctx.reply(`Data from firebase: ${dataFromDb}`);
});

bot.launch();
exports.bot = functions.region('europe-west1').https.onRequest((req, res) => {
    bot.handleUpdate(req.body, res).then( (rv) => !rv && res.sendStatus(200));
});

有人可以分享有用的例子吗? :)

感谢您的关注, 问候!

【问题讨论】:

    标签: javascript node.js firebase firebase-realtime-database telegram


    【解决方案1】:

    从 Firebase 读取数据是一个异步操作,因此您需要等待它完成:

    const dataFromDb = await admin.database().ref('users/' + userId).once('value');
    

    此外,您需要从返回的快照中获取值,而不是发回整个快照:

    ctx.reply(`Data from firebase: ${dataFromDb.val()}`);
    

    【讨论】:

      猜你喜欢
      • 2017-09-14
      • 2021-04-04
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多