Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsdiscord

Send a message to discord channels via google apps script


I am using some scripts to send message to discord via google apps script... I used a function such as :

function postMessageToDiscord(){

  message = "Hello World!";

  var discordUrl = "https://discordapp.com/api/webhooks/XXXXX";
  var payload = JSON.stringify({content: message});

  var params = {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    method: "POST",
    payload: payload,
    muteHttpExceptions: true
  };

  var response = UrlFetchApp.fetch(discordUrl, params);
  Logger.log(response.getContentText());
}

Everything was working perfectly for weeks, but since 2 or 3 weeks, nothing is sent to discord anymore... Could someone help me to understand what's going on?

Thanks a lot :)


Solution

  • How about the following modifications?

    Pattern 1:

    From:

    var params = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      method: "POST",
      payload: payload,
      muteHttpExceptions: true
    };
    

    To:

    var params = {
      method: "POST",
      payload: payload,
      muteHttpExceptions: true,
      contentType: "application/json"
    };
    

    Pattern 2:

    From:

    var payload = JSON.stringify({content: message});
    

    To:

    var payload = {content: message};
    

    Note:

    • In my environment, I could confirm that both patterns works fine while the error of {"message": "Cannot send an empty message", "code": 50006} occurs when your script is run.
    • If your webhook cannot be used, how about setting it again? Ref

    References:

    If this was not the direct solution of your issue, I apologize.