Home > Software engineering >  Unable to send curl output to discord using webhook which is otherwise printing it in my bash termin
Unable to send curl output to discord using webhook which is otherwise printing it in my bash termin

Time:02-06

status=$(curl -i -s -H "Authorization: token abc123" https://www.some_url.com | awk 'NR==18')

if [ "$status" != 200 ]; then
  echo "$status"
fi

The above code is working and echo is printing the output in my console.

But when I use discord webhook, it doesn't send message there and throws following error: {"code": 50109, "message": "The request body contains invalid JSON."}

webhook=https://discord.com/api/webhooks/abc123

status=$(curl -i -s -H "Authorization: token abc123" https://www.some_url.com | awk 'NR==18')

if [ "$status" != 200 ]; then
  curl -H "Content-Type: application/json" -X POST -d '{"content":"'"$status"'"}' $webhook
fi

I can send a normal message through webhook but not this curl output. The output is suppose to be HTML error message.

Even if I change awk 'NR==18' to awk 'NR==1', it's not sending even the one line output which is suppose to be something like: HTTP/1.1 401 Unauthorized

CodePudding user response:

I have a discord bot (webhook) running on a raspberry pi from a bash script, so I think it is the same thing you are looking for

sendcontent='{"username": "Botname", "content": "'"${messagearray[@]}"'"}'
curl -H "Content-Type: application/json" -d "$sendcontent" "$webhookurl"

I would suggest the following change to your code:

messagearray=($(curl -i -s -H "Authorization: token abc123" https://www.some_url.com | awk 'NR==18'))

EDIT: It seems that there are nasty invisible characters in the curl awk command return, therefore the above solution needs to be modified as below (This bash file test with the provided url from comments)

#!/bin/bash
webhookurl="https://mywebhook"
messagearray=($(curl -i -s https://www.google.com/ | awk 'NR==1'))
#this next line removes some nasty invisible characters | if the content also contains quotes that can mess with the bot so use: [$'\t\r\n"'] instead
messagearray=("${messagearray[@]//[$'\t\r\n']}")
sendcontent='{"username": "Botname", "content": "'"${messagearray[@]}"'"}'
curl -H "Content-Type: application/json" -d "$sendcontent" "$webhookurl"

This successfully sends HTTP/2 200 in discord

the removal is an adaptation of: How to remove a newline from a string in Bash

  •  Tags:  
  • Related