Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
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');

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: '[email protected]',
    // 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}`);

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 Answer

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

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share