Saturday, 6 February 2021

Telegram bot with telegraf.js : can't send random photo to chat using flickr api

I am newbie in telegram bots creation and want to make a simple bot which allows user to choose between singer or actor photo in commands and then using flickr API send it to chat:

const Telegraf = require('telegraf')
const { Router, Markup } = Telegraf
const axios = require('axios')
const api_key = '123'

const telegram = new Telegraf('123')

const inlineMessageRatingKeyboard = Markup.inlineKeyboard([
    Markup.callbackButton('Singer', 'singer'),
    Markup.callbackButton('Actor', 'actor')
]).extra()


const getSingerPhoto = () => {
    axios.get(`https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=${api_key}&tags=gerard+way&format=json&nojsoncallback=1`)
        .then(photosInfo => {
            const photosArray = (photosInfo.data && photosInfo.data.photos && photosInfo.data.photos.photo) || null;
            const photoObject = (photosArray && photosArray[photosArray.length * Math.random() | 0]) || null;
            let { server, id, secret } = photoObject;
            telegram.action('singer', (ctx) => {
                ctx.replyWithPhoto({
                    url: `https://live.staticflickr.com/${server}/${id}_${secret}_q.jpg`
                })
            })
        })
        .catch(error => console.log(error));
}

telegram.on('message', (ctx) => ctx.telegram.sendMessage(
    ctx.from.id,
    'What kind of photo do you want?',
    inlineMessageRatingKeyboard
)
)

telegram.command('singer', getSingerPhoto());

telegram.action('actor', (ctx) => {
    ctx.replyWithPhoto({
        source: './way.png'
    })
})

telegram.startPolling()

Flickr API is okay - I get photo array (photosArray) and then take random photo object (photoObject) from it, then I put it to necessary photo URL (https://live.staticflickr.com/${server}/${id}_${secret}_q.jpg) and it generates okay too.

The problem is that it's always exactly the same photo, I have to always restart the bot to generate a new photo URL. What am I doing wrong, how to avoid it and send random photo every time user call command singer? Any help will be appreciate



from Telegram bot with telegraf.js : can't send random photo to chat using flickr api

No comments:

Post a Comment