How to send emoji via bash script to Telegram bot using curl?

守給你的承諾、 提交于 2019-12-12 21:05:35

问题


I'm trying to send an emoji/emoticon to my Telegram bot using a bash script. This bash script calls the Telegram API as follows:

curl -s -X POST 'https://api.telegram.org/'$API'/sendMessage' -F chat_id=$chat -F text=$text

Since the bash script isn't unicode, I cannot simply copy/paste the emojis from the web. Therefore I tried using the UTF-8 emoji variants, but the backslash character keeps getting escaped.

The expected json output should be as follows: "text":"\ud83d\udd14"

Instead, this is what I get:

Input: $text = \xF0\x9F\x98\x81 JSON Output = "text":"\\xF0\\x9F\\x98\\x81\\"

Input: $text = u'\U0001F604' JSON Output = "text": "u'\\U0001F604'\"

Input: $text = \U0001F514 JSON Output = "text":"\\U0001F514"

Input: $text = "(1f600)" JSON Output = "text":"\"(1f600)\""

Input: $text = \ud83d\ude08 JSON Output = "text":"\\ud83d\\ude08"

Input: $text = \\\ud83d\\\udd14 JSON Output = "text":"\\\\\\ud83d\\\\\\udd14"

What is the correct syntax to send an emoji using a bash script and curl to my Telegram bot?

Thank you very much!


回答1:


Generating JSON For The Telegram API

If your question is about JSON encoding, let jq figure it out for you:

s='🔔'  ## or s=$'\360\237\224\224'

json=$(jq -anc --arg id "$chat" --arg s "$s" '{"chat_id": $id, "text": $s}')
curl -X POST -H "Content-Type: application/json" -d "$json" \
  "https://api.telegram.org/$API/sendMessage"

From JSON To String Literal

In bash 4.0 or newer, the shell itself can be asked to give you an ASCII-printable literal string which will correspond to a multi-byte character.

LC_ALL=C printf "s=%q\n" "$(jq -r . <<<'"\ud83d\udd14"')"

...will output:

s=$'\360\237\224\224'

From String Literal To JSON

To go in the other direction:

s=$'\360\237\224\224'
jq -anM --arg s "$s" '$s'

...emits as output:

"\ud83d\udd14"



回答2:


You can use echo -e '\U0001F514' for get emoji

curl -F "text=`echo -e '\U0001F514'` - it's a bell" "https://api.telegram.org/$API/sendMessage?chat_id=$chat"

or $'\U0001F514'

curl -F "text="$'\U0001F514'" - it's a bell" "https://api.telegram.org/$API/sendMessage?chat_id=$chat"


来源:https://stackoverflow.com/questions/50009875/how-to-send-emoji-via-bash-script-to-telegram-bot-using-curl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!