telebot icon indicating copy to clipboard operation
telebot copied to clipboard

Asyncrounous mods

Open Fuzzyma opened this issue 8 years ago • 4 comments

Is there a possibility to use mod() with an asyncrounous function which returns a Promise? I would like to authenticate my user and that happens asyncronous. Only then I want to proceed with evaluating the request.

Usecase:

  bot.mod('message', async (data) => {
    const user = await getUser(data.message.from.id)
    if(!user) {
      return bot.sendMessage(data.message.from.id, 'User not found');
    }
    data.user = user
  })

PS: Is data.message.from.id the correct way to access the id at this place?

Fuzzyma avatar Dec 11 '17 00:12 Fuzzyma

I saw that in some plugins you use data.promise to do something. But using this doesnt yield correct results. The data flow is not stopped as long as the promise is unfullfilled. Thats why (in my case) the user is not loaded yet when hitting the route.

Here is what I tried:

  bot.mod('message', (data) => {
    console.log(data)
    if(data.message.text.startsWith('/start')) {
      return data
    }

    data.promise = getUser(data.message.from.id).then((user) => {
      data.message.user = user
      if(!user) {
        bot.sendMessage(data.message.from.id, 'User not found');
        throw new Error('User unknown')
      }
    })
    
    return data
  })

  bot.on('/update', (msg) => {
    console.log(msg.user) // is undefined
  }

Fuzzyma avatar Dec 11 '17 01:12 Fuzzyma

Hi @Fuzzyma, Did you find any solution? wish there was a way to use async/await with bot.mod

mehrancodes avatar Mar 12 '18 11:03 mehrancodes

Not really. I ended up writing my own libraray which I find easier to use for this sort of stuff: https://github.com/Fuzzyma/yata

Fuzzyma avatar Mar 12 '18 11:03 Fuzzyma

@Fuzzyma Surly will give it a try!! :raised_hands:

mehrancodes avatar Mar 12 '18 11:03 mehrancodes