Slackbot help: How can I make sure my variable is updated before sending to a new function?

Hey All,

I’m working on creating a translation slackbot. Users use the command “/translate word” and it will return the translated word and then prompt the user to save it to mongoDB.

I have this weird bug where when I send the new word to be saved to the db, the function only sends the first word saved. Ex:

/translate word
word: từ in VNese
Saving word as từ.

Then if i translate another word it will say something like
/translate word two
word two is từ hai
Saving word as từ (it won’t send the updated word even though it will display the updated word.

//TODO not getting updated
                console.log('original before sending is ' + original);

                slapp.action('yesno_callback', 'answer', (msg, value) => {
                  if (value == 'yes') {
                    console.log('sending original ' + original);
                    oombawDB.saveVocab(res, msg, original, translated);
                    msg.respond(msg.body.response_url, `:thumbsup:`);
                  } else {
                    console.log('not saving');
                    msg.respond(msg.body.response_url, `:thumbsdown:`);
                  }
                });

The console.log before slapp.action displays the updated original but slapp.action only sends the FIRST original word.

Here’s my code in its entirety.

module.exports = function(slapp) {

  slapp.command('/translate', (msg, text) => {
    // returns current user, if doesn't exist then adds user and returns
    oombawDB.checkAddUser(msg).then(currentUser => {
      let userObj = currentUser.toObject();
      if (userObj.hasOwnProperty('translateTo')) {
        //console.log('has property');
        translateWord(currentUser, text);
      } else {
        msg.respond({
          "text": "What language would you like to translate to?",
          "response_type": "ephemeral",
          "attachments": [{
            //"text": "Choose a language to translate to",
            "fallback": "",
            "color": "#3AA3E3",
            "attachment_type": "default",
            "callback_id": "language_selection",
            "actions": [{
              "name": "language_choice",
              "text": "Pick a language...",
              "type": "select",
              "options": [{
                  "text": "Afrikaans",
                  "value": "af"
                },
                {
                  "text": "Albanian",
                  "value": "sq"
                },
                {
                  "text": "Arabic ",
                  "value": "ar"
                },
                {
                  "text": "Azerbaijani",
                  "value": "az"
                },
                {
                  "text": "Basque",
                  "value": "eu"
                },
                {
                  "text": "English",
                  "value": "en"
                },
                {
                  "text": "Vietnamese",
                  "value": "vi"
                }
              ]
            }]
          }]
        });
        slapp.action('language_selection', 'language_choice', (msg, value) => {
          msg.respond(msg.body.response_url, ` `);
          oombawDB.addUserPref(msg, value).then(response => {
            translateWord(response, text);
          });
        });


      } // end else
      function translateWord(currentUser, text) {
        console.log(text);
        var original;
        var translated;
        translate(text, {
            to: currentUser.translateTo
          })
          .then(res => {
            original = text.toLowerCase();
            translated = res.text.toLowerCase();
            console.log(original + ' is ' + translated);
            // console.log(res.text);
            // => I speak English
            // console.log(res.from.language.iso);
            // => nl
            msg.respond(original + ': ' + translated);
            translate('Do you want to save this?', {
                to: currentUser.translateTo
              }).then(translatedMessage => {
                msg.respond({
                  text: '',
                  attachments: [{
                    text: translatedMessage.text,
                    fallback: 'Yes or No?',
                    callback_id: 'yesno_callback',
                    actions: [{
                        name: 'answer',
                        text: ':thumbsup:',
                        type: 'button',
                        value: 'yes'
                      },
                      {
                        name: 'answer',
                        text: ':thumbsdown:',
                        type: 'button',
                        value: 'no'
                      }
                    ]
                  }]
                });

                //TODO not getting updated
                console.log('original before sending is ' + original);

                slapp.action('yesno_callback', 'answer', (msg, value) => {
                  if (value == 'yes') {
                    console.log('sending original ' + original);
                    oombawDB.saveVocab(res, msg, original, translated);
                    msg.respond(msg.body.response_url, `:thumbsup:`);
                  } else {
                    console.log('not saving');
                    msg.respond(msg.body.response_url, `:thumbsdown:`);
                  }
                });


              })
              .catch(err => {
                console.error(err);
              });
          });




      }
    });



  });


};

check your msg inside slapp.action

Not sure what you mean? Here’s the console.log for the msg and testing two words to be translated.

First one.

Message {
type: 'action',
body:
{ actions: [ [Object] ],
callback_id: 'yesno_callback',
team: { id: 'T5XH5T9LK', domain: 'languagebot' },
channel: { id: 'C5YJVM61L', name: 'testing-peter' },
user: { id: 'U5XNA24BX', name: 'iampeternguyen' },
action_ts: '1506748050.382353',
message_ts: '1506748045.000031',
attachment_id: '1',
token: 'FcG1FIq8sMcQex6FlN53qehy',
is_app_unfurl: false,
type: 'interactive_message',
response_url: 'https://hooks.slack.com/actions/T5XH5T9LK/248707193520/MEUWiITTxkXZUGkKJl9XgI7Z',
trigger_id: '250444886967.201583927699.4fea7ad97ec6be5dfbade92d4d970f17' },
meta:
{ verify_token: 'FcG1FIq8sMcQex6FlN53qehy',
user_id: 'U5XNA24BX',
channel_id: 'C5YJVM61L',
team_id: 'T5XH5T9LK',
app_token: 'xoxp-201583927699-201758072405-201754756497-ebe2a43d3ad34f55816a012fb951787e',
app_user_id: 'U5XNA24BX',
app_bot_id: 'B5YC3LFB7',
bot_token: 'xoxb-201646107248-TW3ac54WIgFIygb8K7PwReTG',
bot_user_id: 'U5XK0357A',
bot_user_name: 'oombaw',
team_name: 'languagebot-team',
team_domain: 'languagebot',
team_resource_id: '23044299b0a143c0aa68503c148b9236',
incoming_webhook_url: '',
incoming_webhook_channel: '',
error: undefined,
config: {} },
makeThreaded: null,
conversation_id: 'T5XH5T9LK::C5YJVM61L::U5XNA24BX',
_slapp:
Slapp {
domain: null,
_events: { info: [Function], error: [Function] },
_eventsCount: 2,
_maxListeners: undefined,
_middleware: [ [Function], [Function] ],
_matchers:
[ [Function: fn],
[Function: fn],
[Function: fn],
[Function: fn],
[Function: fn],
[Function: fn],
[Function: fn] ],
_registry: { 'how-are-you': [Function], color: [Function] },
verify_token: 'FcG1FIq8sMcQex6FlN53qehy',
log: true,
colors: false,
logger: [Function],
ignoreSelf: true,
ignoreBots: false,
defaultExpiration: 3600,
convoStore: ConvoStore { kv: [Object], keyPrefix: 'convo::' },
client:
{ apps: [Object],
api: [Object],
auth: [Object],
bots: [Object],
channels: [Object],
chat: [Object],
dnd: [Object],
emoji: [Object],
files: [Object],
groups: [Object],
im: [Object],
mpim: [Object],
oauth: [Object],
reactions: [Object],
reminders: [Object],
pins: [Object],
rtm: [Object],
search: [Object],
stars: [Object],
team: [Object],
usergroups: [Object],
users: [Object] },
receiver:
Receiver {
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
verify_token: 'FcG1FIq8sMcQex6FlN53qehy',
context: [Function: contextMiddleware] } },
_queue: null,
clearTimeout: [Function],
_response:
ServerResponse {
domain: null,
_events: { finish: [Function: resOnFinish] },
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedHeader: {},
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 10,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
destroyed: false,
_bytesDispatched: 218,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 34072,
parser: [Object],
on: [Function: socketOnWrap],
_paused: false,
read: [Function],
_consuming: true,
_httpMessage: [Circular] },
connection:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 10,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
destroyed: false,
_bytesDispatched: 218,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 34072,
parser: [Object],
on: [Function: socketOnWrap],
_paused: false,
read: [Function],
_consuming: true,
_httpMessage: [Circular] },
_header: null,
_headers: { 'x-powered-by': 'Express' },
_headerNames: { 'x-powered-by': 'X-Powered-By' },
_onPendingData: [Function: updateOutgoingData],
req:
IncomingMessage {
_readableState: [Object],
readable: false,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
socket: [Object],
connection: [Object],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Object],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '/slack/action',
method: 'POST',
statusCode: null,
statusMessage: null,
client: [Object],
_consuming: true,
_dumped: false,
next: [Function: next],
baseUrl: '',
originalUrl: '/slack/action',
_parsedUrl: [Object],
params: {},
query: {},
res: [Circular],
route: [Object],
body: [Object],
_body: true,
length: undefined,
read: [Function],
slapp: [Object] },
locals: {} },
_responseTimeout:
Timeout {
_called: false,
_idleTimeout: 2500,
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: false,
msecs: 2500 },
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: false,
msecs: 2500 },
_idleStart: 34087,
_onTimeout: [Function],
_repeat: null } } 

Is there any way to debug this one ?