Botkit: Unhandled Promise Rejection/Cannot set property 'channel'

Created on 28 Mar 2018  路  3Comments  路  Source: howdyai/botkit

I'm working on a Slackbot using Google Maps API to reply to a user query with info from the Maps API, so I'm trying to have the bot wait for the API response before replying; however, I'm getting an unhandled promise rejection warning and a cannot set property 'channel' error. Can anyone help me understand asynchronously implementing an API like Google Maps into botkit?

My code:

let googleMapsClient = require('@google/maps').createClient({
  key: '**************************',
  Promise: Promise
});

function queryMaps(mapsQueryString) {
  googleMapsClient.geocode({
    address: mapsQueryString
  })
  .asPromise()
  .then(response =>  response.json.results[0].formatted_address)
  .catch(err => console.log(err))
}

const controller = Botkit.slackbot({debug: true})
controller
  .spawn({
    token: '**************'
  })
  .startRTM(function (err) {
    if (err) {
      throw new Error(err)
    }
  })

  controller.hears(
  ['\\b.*tell me about\s*([^\n\r?]*)', '\\b.*tell me something about\s*([^\n\r?]*)'], ['direct_message', 'direct_mention', 'mention'],
  async function (bot, message) {

    let returnedResult = await queryMaps(message.match[1]);
    bot.reply(message, returnedResult);

  });

And here's the debug output...

debug: I HEARD [ '\\b.*tell me abouts*([^\n\r?]*)',
  '\\b.*tell me something abouts*([^\n\r?]*)' ]
(node:96441) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot set property 'channel' of undefined
(node:96441) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
help wanted

Most helpful comment

queryMaps doesn't return anything, so returnedResult is undefined. When CoreBot tries to process it as a message object, it throws.

Try changing this:

function queryMaps(mapsQueryString) {
  googleMapsClient

to this:

function queryMaps(mapsQueryString) {
  return googleMapsClient

All 3 comments

queryMaps doesn't return anything, so returnedResult is undefined. When CoreBot tries to process it as a message object, it throws.

Try changing this:

function queryMaps(mapsQueryString) {
  googleMapsClient

to this:

function queryMaps(mapsQueryString) {
  return googleMapsClient

@koubenecn please let us know if this helped

Sure enough - changing the code as per @jschnurr 's suggestion works - thank you for the help! Here's what the working code looks like:

function queryMaps(mapsQueryString) {
  return googleMapsClient.geocode({
    address: mapsQueryString
  })
  .asPromise()
  .then(response =>  response.json.results[0].formatted_address)
  .catch(err => console.log(err))
} 
Was this page helpful?
0 / 5 - 0 ratings