windows 使用curl在Slack上发布文件的一部分

e1xvtsh3  于 2023-04-07  发布在  Windows
关注(0)|答案(3)|浏览(190)

我想使用curl将给定行号后的文件内容发送到Slack。我希望它在一些消息后格式化为代码。ChatGPT在这里没有帮助。我使用的代码是:

log_text=$(awk -v n="$some_number" 'NR >= n' "$log_file" )

# Handle line breaks and special characters:
#log_text=$(printf '%s' "$log_text" | jq -Rs .) # Doesn't work
#log_text=$(printf '%s' "$log_text" | sed 's/"/\\"/g; s/$/\\n/' | tr -d '\n')  # Also doesn't work
log_text=$(echo "$log_text" | jq -R -s -c)  # Doesn't work as well
echo "============================"
echo "$log_text"
echo "============================"
curl -s -f  --retry 2 -X POST -H 'Content-type: application/json' --data "{\"text\": \" some text here  \`\`\`$log_text\`\`\` \"}" \
"$slack_hook" || echo "Failed to send message"

这总是无法发送消息。如果我设置了log_text="",那么它就可以正常工作,所以我假设这是log_text中内容的格式问题。该文件有几个特殊字符换行符等,但我想在json上整齐地发送它,以便它可以在Slack上阅读。这里是怎么回事?

qfe3c7zg

qfe3c7zg1#

ChatGPT永远不会为您做的事情是编写带有解释的工作代码,以便您学习一些东西
cat sendlog.sh

#!/usr/bin/env sh

# Configures Slack API URL here
SLACK_API=https://example.com/

# Creates markdown code block from standard input
# $1 : Optional language code
# shellcheck disable=SC2120 # Function uses optional arguments
md_codeBlock() {
  # Inserts content into code block, ensuring it ends with newline
  # shellcheck disable=SC2016 # Literal back-ticks intended
  printf '```%s\n%s\n```\n' "${1:-none}" "$(cat)"
}

# Turns stdin to Slack's JSON
slack_toJson() {
  jq -cRs '{"text":.}'
}

# Starting line as first argument with default 0 if omitted
start_line=${1:-0}

# Strips out leading non-digit signs (no +, - space...)
start_line=${start_line##[^[:digit:]]}

# Gets stdin text starting at given line number,
tail "-n+${start_line}" |

  # Turns stdin text into a markdown code block
  md_codeBlock |

  # Turns stdin text into Slack's JSON
  slack_toJson |

  # Sends the piped-in JSON data to Slack API.
  curl -s -f --retry 2 \
    -X POST -H 'Content-type: application/json' \
    --data-binary @- "$SLACK_API"

从第42行开始发送somefile.log内容的示例:

bash sendlog.sh 42 < somefile.log
j2cgzkjk

j2cgzkjk2#

我建议避免在curl命令中使用模板构建器,而是使用单个参数。
相反:

curl -s -f  --retry 2 -X POST -H 'Content-type: application/json' --data "{\"text\": \" some text here  \`\`\`$log_text\`\`\` \"}"

您可以执行以下操作:

curl -s -f  --retry 2 -X POST -H 'Content-type: application/json' --data "$log_text_2"

在这种情况下,您可以打印$log_text_2来了解错误所在。我认为可能是一些转义字符导致了这个问题。

zfciruhq

zfciruhq3#

最后是什么工作(不知道为什么):
首先复制斜杠,然后用'\n'替换所有换行符:

log_text="$(printf '%s' "$log_text" | sed 's/\\/\\\\/g' | sed ':a;N;$!ba;s/\n/\\n/g' )"

然后使用一个变量来创建整个payload,这样更容易调试:

json_string="{\"text\": \" some text \\n \`\`\`$log_text\`\`\` \"}"

最后发送消息:

curl -s -f  --retry 2 -X POST -H 'Content-type: application/json' --data "$json_string"

相关问题