Skip to content

Instantly share code, notes, and snippets.

@jogerj
Forked from dideler/bot.rb
Last active October 7, 2022 17:37
Show Gist options
  • Save jogerj/47eca63335c93b214c9bc72347139756 to your computer and use it in GitHub Desktop.
Save jogerj/47eca63335c93b214c9bc72347139756 to your computer and use it in GitHub Desktop.
Send Telegram messages from bash
#!bin/bash
TELEGRAM_BOT_TOKEN="botid:token"
CHAT_ID="1234567890"
send_telegram () {
title="$1"
timestamp="$(date -R)"
msg="$title\n$timestamp\n\n$(echo "$2" | sed -z -e 's|\\|\\\\|g' -e 's|\n|\\n|g' -e 's|\t|\\t|g' -e 's|\"|\\"|g')"
entities="[{\"offset\":0,\"length\":${#title},\"type\":\"bold\"},{\"offset\":$((${#title}+1)),\"length\":${#timestamp},\"type\":\"italic\"}]"
data="{\"chat_id\":\"$CHAT_ID\",\"text\":\"$msg\",\"entities\":$entities,\"disable_notification\": true}"
curl -s -o /dev/null -H 'Content-Type: application/json' -d "$data" -X POST https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage
}
  1. Create a bot

  2. Get the bot's API token from @BotFather

  3. Add your bot to the chat you'll be sending messages to

  4. Get the ID of the chat
    Fetch bot updates and look for the chat id:

    curl https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/getUpdates | jq .message.chat.id
    

    The bot may need temporary message access: @BotFather > Bot Settings > Group Privacy > Turn off

  5. Set both parameters TELEGRAM_BOT_TOKEN and CHAT_ID in telegram-http.sh

  6. To send a message using the HTTP API: https://core.telegram.org/bots/api#sendmessage From another bash script, import with source /path/to/telegram-http.sh then can call the function each time you want to send a message like so send_telegram "title in bold" "this is the message body".

    Output: title in bold Sat, 07 Oct 2022 00:24:57 +0100 this is the message body

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment