Search code examples
javascriptcrondiscorddiscord.jstrello

How to add a function to a function


I currently have a cron job function to send a message every morning at 7:00 am, and it works perfectly but now I want it to get the message from a Trello card and the Trello part works perfectly, but when I put them together it doesn’t work. Any ideas? Here what I have so far:

var job = new CronJob('01 15 18 * * *', function() {
        let listID = "5ec3fda8a26c384e44f063bb";
trello.getCardsOnListWithExtraParams(listID, "pos:top",
       function (error, trelloCard) {
        console.log('Found card:', trelloCard[0].name);
})
const wyrEmbed = new discord.RichEmbed()
      .setTitle("❓**WOULD YOU RATHER**❓")
      .addField(
        "**THE WOULD YOU RATHER**", "test: " + trelloCard[0].name)
      .setDescription(
        "🌞 Top o' the mornin’ to ya! All throughout the night, I’ve been preparing a would you rather question for all of you! I can’t wait to see all of the answers you guys think of! "
      )
      .setTimestamp()
      .setFooter("Munchies Ice Cream", client.user.avatarURL)
      .setThumbnail("https://t4.rbxcdn.com/366f4da2e1924b6e4b0816086b485f05")
      .setColor("7ab7e2"); 
        const wyrthing = client.channels.get("688177088573997066")
  wyrthing.send(wyrEmbed)
    console.log('You will see this message every second')
},
  null,
    true,
    'America/New_York'
);
})

Solution

  • Your code basically tries to do this (in this order):

    • Start getting the Trello card
    • Send the embed using the (non-existent) Trello card
    • Later, when the Trello card has been retrieved: Log "Found card: <card name>"

    This is because trello.getCardsOnListWithExtraParams is an asynchronous function. You're getting the result trelloCard as a parameter to your callback function, but you are trying to access it outside the callback when you add a field to your embed.

    Put this in your cron function:

    let listID = "5ec3fda8a26c384e44f063bb";
    trello.getCardsOnListWithExtraParams(listID, "pos:top", function (error, trelloCard) {
      console.log('Found card:', trelloCard[0].name);
      const wyrEmbed = new discord.RichEmbed()
        .setTitle("❓**WOULD YOU RATHER**❓")
        .addField("**THE WOULD YOU RATHER**", "test: " + trelloCard[0].name)
        .setDescription(
          "🌞 Top o' the mornin’ to ya! All throughout the night, I’ve been preparing a would you rather question for all of you! I can’t wait to see all of the answers you guys think of! "
        )
        .setTimestamp()
        .setFooter("Munchies Ice Cream", client.user.avatarURL)
        .setThumbnail("https://t4.rbxcdn.com/366f4da2e1924b6e4b0816086b485f05")
        .setColor("7ab7e2"); 
      const wyrthing = client.channels.get("688177088573997066")
      wyrthing.send(wyrEmbed)
    })