1

I have built a simple telegram bot using telegraf and used this code to log a specific information that I need :

bot.on('text', (ctx, next) => {
  console.log(`[text] ${ ctx.message.chat.id } ${ ctx.from.username } ${ ctx.message.chat.first_name+ " " + ctx.message.chat.last_name } ${ ctx.message.text }`);
   return next();
});

and as result, the log be something like this

[text] 563789142 xMA3x Mohammed Abbas /start

Now I want to save that information in a google spreadsheet, I had followed this Tutorial and was able to push a quotation marked values into the spreadsheet only, but i don't know how to push the console.log result into the spreddsheet

anyway, here is my code

const { Telegraf } = require('telegraf');
const bot = new Telegraf("xyz")
const { google } = require("googleapis");
const keys = require("./Keys.json")

bot.on('text', (ctx, next) => {
  console.log(`[text] ${ ctx.message.chat.id } ${ ctx.from.username } ${ ctx.message.chat.first_name+ " " + ctx.message.chat.last_name } ${ ctx.message.text }`);
   return next();
});

bot.start((ctx) => ctx.reply('Welcome'))
bot.help((ctx) => ctx.reply('Send me a sticker'))
bot.on('sticker', (ctx) => ctx.reply(''))
bot.hears('hi', (ctx) =>  ctx.reply('Hey there'))


const client = new google.auth.JWT(
  keys.client_email, 
  null, 
  keys.private_key, 
  ["https://www.googleapis.com/auth/spreadsheets"]
);


client.authorize(function(err){

    if(err){
      console.log(err);
      return;
    } else {
      console.log("connected");
      gsrun(client);
    }

});

async function gsrun(cl){

  const gsapi = google.sheets({version:"v4", auth: cl});
    
  const updateOptions = {
    spreadsheetId: "xyz",
    range: "Sheet1",
    valueInputOption: "RAW",
    insertDataOption: "INSERT_ROWS",
    resource: {
      values:[
        ["this is working"]
      ]}
  };
 let res = await gsapi.spreadsheets.values.append(updateOptions);
 console.log(res);
}
bot.launch()

so as you see the "this is working" is pushed successfully in the spreadsheet, but when I try to add another value like ctx.message.chat.id it give me ReferenceError: ctx is not defined

so how I can make the google sheet API recognize the telegraf commands? or to be more general, how I can save the *ctx.message.chat.id,ctx.from.username..etc * info (that come form the telegram) into the spreedhsset ?

1 Answers1

1

ctx lives within your bot hooks, so to save the information to the sheet, you have to call your googlesheets function inside the relevant hook.

Possible updates:

const { Telegraf } = require('telegraf');
const bot = new Telegraf("xyz")
const { google } = require("googleapis");
const keys = require("./Keys.json")

const client = new google.auth.JWT(
  keys.client_email, 
  null, 
  keys.private_key, 
  ["https://www.googleapis.com/auth/spreadsheets"]
);

async function gsrun(cl, data){

    const gsapi = google.sheets({version:"v4", auth: cl});
      
    const updateOptions = {
      spreadsheetId: "xyz",
      range: "Sheet1",
      valueInputOption: "RAW",
      insertDataOption: "INSERT_ROWS",
      resource: {
        values:[
          [data]
        ]}
    };
   let res = await gsapi.spreadsheets.values.append(updateOptions);
   console.log(res);
  }

const saveMetadataToSheets = (data) => {
    client.authorize(function(err){
        if(err){
          console.log(err);
          return;
        } else {
          console.log("connected");
          gsrun(client, data);
        }
    });
}


bot.on('text', (ctx, next) => {
    const data = `[text] ${ ctx.message.chat.id } ${ ctx.from.username } ${ ctx.message.chat.first_name+ " " + ctx.message.chat.last_name } ${ ctx.message.text }`
    console.log(data);
    // pass any data that you need to save to the sheets
    saveMetadataToSheets(data)
     return next();
  });
  
bot.start((ctx) => ctx.reply('Welcome'))
bot.help((ctx) => ctx.reply('Send me a sticker'))
bot.on('sticker', (ctx) => ctx.reply(''))
bot.hears('hi', (ctx) =>  ctx.reply('Hey there'))
bot.launch()