How do I get the user picture/avatar using the Telegram bot chat API?

Antonio Carlos Ribeiro picture Antonio Carlos Ribeiro · Apr 20, 2016 · Viewed 11.7k times · Source

The user object has no photo_id, so is there way to get the user's avatar?

Answer

Bagherani picture Bagherani · Dec 25, 2017

I didn't find any php code, but this nodejs snippet worked for me so I put this to give you the idea that how it works.

  1. Create a bot(start chatting with @botfather in your telegram)
  2. After creation of bot finished, it will give you a token for HTTP API
  3. $ npm install --save node-telegram-bot-api
  4. create a js file beside the node_modules folder(for example: server.js)
  5. put this codes in the server.js file and then run it with $ node server.js

        const TelegramBot = require('node-telegram-bot-api');
        // replace the value below with the Telegram token you receive from @BotFather  
        const token = 'XXXX35XXXX:XXXX7DCYw5IsY6DHcwXXXXXXXXX';
        // Create a bot that uses 'polling' to fetch new updates    
        const bot = new TelegramBot(token, {
            polling: true
        });
        // Matches "/echo [whatever]"    
        bot.onText(/\/echo (.+)/, (msg, match) => {
            // 'msg' is the received Message from Telegram    
            // 'match' is the result of executing the regexp above on the text content    
            // of the message    
    
            const chatId = msg.chat.id;
            const resp = match[1]; // the captured "whatever"    
    
            // send back the matched "whatever" to the chat    
            bot.sendMessage(chatId, resp);
        });
        // Listen for any kind of message. There are different kinds of  
        // messages.  
        bot.on('message', (msg) => {
            const chatId = msg.chat.id;
            var user_profile = bot.getUserProfilePhotos(msg.from.id);
            user_profile.then(function (res) {
                var file_id = res.photos[0][0].file_id;
                var file = bot.getFile(file_id);
                file.then(function (result) {
                    var file_path = result.file_path;
                    var photo_url = `https://api.telegram.org/file/bot${token}/${file_path}`
                    bot.sendMessage(chatId, photo_url);
                });
            });
        });