DEV Community

Sze Ying 🌻
Sze Ying 🌻

Posted on • Edited on

Programming your Telegram bot to fetch Document content with Telegraf API

While working on send4me, a message scheduler bot on Telegram, I ran into the question of how my bot can fetch the contents of a document uploaded by a user. I couldn't find a complete example for this use case anywhere, so I put together what worked for me.

A simple demo for fetching Document content

A simple demo for fetching Document content

The following code snippet recreates the demo above. We will assume that you have already created a bot with BotFather and obtained your bot token.

const Telegraf = require('telegraf');
const axios = require('axios');

const BOT_TOKEN = ''; // TODO: get from BotFather

const bot = new Telegraf(BOT_TOKEN, {
  polling: true,
});

bot.start((ctx) => ctx.reply("Hello! Upload any document and I'll read it for you~"));

bot.on('document', async (ctx) => {
  const {file_id: fileId} = ctx.update.message.document;
  const fileUrl = await ctx.telegram.getFileLink(fileId);
  const response = await axios.get(fileUrl);
  ctx.reply('I read the file for you! The contents were:\n\n' + response.data);
});

bot.launch();

This should work for simple text files. For more complex files, response.data will need to be parsed before their content is usable.

Top comments (3)

Collapse
 
g_shemdoe profile image
Georgie Maricky

Can you explain a little bit about {polling: true} ?

Collapse
 
calculusky profile image
Nwankwo Chinedum

Please can you help out. I want a workflow that when my bot receives the file, it will read the data and send a json format

Collapse
 
pankajkb profile image
Pankaj Bhadane

how can i use this to read random lines / download random pictures from folder in my telegram bot ?