Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

javascript - How to work with firebase realtime database from Firebase Functions? (Telegram Bot)

I want to store and receive data from firebase realtime database by Telegram bot using Telegraf.

I'm using Firebase Functions / Cloud Functions for this.

Right now storing data on database is working, but I can't figure out how to get data from firebase and then send it as telegram message.

Below is response for /database command

enter image description here

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

Can someone please share useful example? :)

Thank U for your attencion, Regards!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Reading data from Firebase is an asynchronous operation, so you'll need to wait for it to complete:

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

In addition, you'll need to get the value from the snapshot you get back, instead of sending the entire snapshot back:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...