Skip to content

Instantly share code, notes, and snippets.

@dideler
Last active December 19, 2024 06:26
Show Gist options
  • Save dideler/85de4d64f66c1966788c1b2304b9caf1 to your computer and use it in GitHub Desktop.
Save dideler/85de4d64f66c1966788c1b2304b9caf1 to your computer and use it in GitHub Desktop.
Sending a notification message to Telegram using its HTTP API via cURL
  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
    a. Fetch bot updates and look for the chat id:
    curl https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/getUpdates | -r '.result[].message.chat.id'
    b. OR, run bot.rb and @-mention your bot in the chat. The chat id will appear in bot.rb's output.
    The bot may need temporary message access: @BotFather > Bot Settings > Group Privacy > Turn off
  5. Send a message using the HTTP API: https://core.telegram.org/bots/api#sendmessage
    curl -X POST \
         -H 'Content-Type: application/json' \
         -d '{"chat_id": "123456789", "text": "This is a test from curl", "disable_notification": true}' \
         https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage
# Use this script to test that your Telegram bot works.
#
# Install the dependency
#
# $ gem install telegram_bot
#
# Run the bot
#
# $ ruby bot.rb
#
# Send a message to the bot to get the current chat's ID in the console output.
# If it's a group chat, invite them to the chat first.
require 'logger'
require 'telegram_bot'
TELEGRAM_BOT_TOKEN = "YOUR_BOT_API_TOKEN"
bot = TelegramBot.new(token: TELEGRAM_BOT_TOKEN, logger: Logger.new(STDOUT))
bot.get_updates(fail_silently: true) do |message|
puts "@#{message.from.username}: #{message.text}"
puts "Chat-ID: #{message.chat.id}"
end
@thilinapiy
Copy link

Thanks for sharing this:
Also you can just use another curl to get the chat id instead of running this ruby code.

https://api.telegram.org/bot<YourBOTToken>/getUpdates
Eg:- 
https://api.telegram.org/bot123456789:jbd78sadvbdy63d37gda37bd8/getUpdates

Source: https://stackoverflow.com/a/32572159/516964

@dideler
Copy link
Author

dideler commented Jun 16, 2019

Thanks for the tip @thilinapiy! I've updated the instructions.

@azagramac
Copy link

TOKEN="YOUR_TOKEN" 
ID="YOUR_ID"
URL="https://api.telegram.org/bot$TOKEN/sendMessage"

curl -s -X POST $URL -d chat_id=$ID -d text="Hello World"

Example, copy script to /usr/local/bin/notify-on-ssh-login.sh:

#!/bin/bash

TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
ID="xxxxxxxxxxxxxx"
URL="https://api.telegram.org/bot$TOKEN/sendMessage"

if [ "$PAM_TYPE" != "open_session" ]
then
	exit 0
else
	curl -s -X POST $URL -d chat_id=$ID -d text="$(echo -e "Host: `hostname`\nUser: $PAM_USER\nHost: $PAM_RHOST")" > /dev/null 2>&1
	exit 0
fi

Add to end file /etc/pam.d/sshd

session    optional     pam_exec.so  /usr/local/bin/notify-on-ssh-login.sh

@zyadomer999
Copy link

Is there anyone here please can explain how can you send a media file through HTTP request in telegram bot?

@dideler
Copy link
Author

dideler commented Nov 16, 2020

@yvikt
Copy link

yvikt commented Dec 12, 2020

👍

@vortex0985
Copy link

In Windows I use a small BAT with the help of UnxUtils:

SET TOKEN_BOT=XXXXXXXXXX:YYYYYYYYYYYYYY_ZZZZZZZZZZZZZZZZZZZZ
SET ID_CHAT=-000000000
SET URL=https://api.telegram.org/bot%TOKEN_BOT%/sendMessage
SET MESSAGE="Hello from my Windows"
curl -v -X POST --silent --output /dev/null %URL% -d chat_id=%ID_CHAT% -d text=%MESSAGE%

And in UNIX I use the following SHELL which works very well for me:

#!/bin/bash
TOKEN="XXXXXXXXXX:YYYYYYYYYYYYYY_ZZZZZZZZZZZZZZZZZZZZ"
ID_CHAT="-000000000"
URL="https://api.telegram.org/bot$TOKEN/sendMessage"
SET MESSAGE="Hello from my Solaris"
curl -X POST --silent --output /dev/null $URL -d chat_id=$ID_CHAT -d text="$THE_MESSAGE"
exit 0

You only have to change the Token of the BOT and the ID_CHAT.

Regards.

@kitopopo
Copy link

Dear friens, i need help. Is it possible send a notification message to Telegram using its HTTP API via cURL but using ptiority.normal or priority.low to get a message withouth buzz or get a message in silence mode? Thanks in advanced. Best regards.

@sqrtroot
Copy link

Yes see https://core.telegram.org/bots/api#sendmessage
add: -d disable_notification=true

@kitopopo
Copy link

Yes see https://core.telegram.org/bots/api#sendmessage
add: -d disable_notification=true

Ohhh. thank you very much dear friend. Your answer was really useful for me. I have tried it and it works.

Would it be possible to deactivate the notification within a specific time via curl? This would be great for me, but I'm not sure if it would be possible. Thanks in advance. a cordial greeting

@sqrtroot
Copy link

I think at that moment you are either better of writing a shell script or writing it in another programming language

@dneprpi
Copy link

dneprpi commented Sep 17, 2021

hi guys,
is it possible to get the bot's API token from @Botfather NOT through telegram but using some api?
I need to create bots automatically in my .net app

@SanariSan
Copy link

This might be helpful if looking for cli examples

https://gist.github.com/SanariSan/4c7cca1aef10dfe0e27e55cfd97e9a53

@xjustbmw
Copy link

xjustbmw commented May 4, 2022

is it possible to write "to" a telegram bot using http request ?
i managed to send the message to the chat_id it but appears in the chat as its written by the bot

@GalileoCap
Copy link

What a great, quick tutorial! Thank you!

@alexstyl
Copy link

If you are getting an empty result list when doing getUpdates for your bot, kick the bot out of the group, invite again and fetch again.

@jogerj
Copy link

jogerj commented Oct 7, 2022

Very useful. Made a neat little script that you can import in bash. Adds a title/timestamp to it. Keeps me informed whenever my deployments need my attention.

#!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
}

Import with source /path/to/telegram.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

@a0s
Copy link

a0s commented Jan 30, 2023

The right curl:

curl -s https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/getUpdates | jq -r '.result[].message.chat.id'

@ArtemBay
Copy link

ArtemBay commented Mar 15, 2023

Can i send file with message instead? Like this, but with curl
Screenshot_20230315-093956_MDGram

@zakery1369
Copy link

Can i send file with message instead? Like this, but with curl

yes

curl -X POST https://api.telegram.org/bot/sendDocument -F chat_id='123456789' -F document=@'/path/to/file' -F caption='source: https://example.com'

@DavidPerezIngeniero
Copy link

Instead of:

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

I think it should be:

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

@BANGAAN44N
Copy link

Instead of:

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

I think it should be:

curl https://api.telegram.org/bot$7040428535:AAH-RtS-yODyP-CIbZrEr433Y2xrLuP13vk/getUpdates | jq 'result[].message.chat.id'

@tas33n
Copy link

tas33n commented Apr 17, 2024

hi guys, is it possible to get the bot's API token from @Botfather NOT through telegram but using some api? I need to create bots automatically in my .net app

its possible with account api, instead of bot api.

@MahouShoujoMivutilde
Copy link

MahouShoujoMivutilde commented Jul 29, 2024

Found myself in need to send an arbitrary text with unicode and quotes, the original example didn't work.

Here is updated one, forcing jq to do all of the string escaping:

#!/usr/bin/env bash
# noti-bot - send notification in telegram
# Usage:
#   echo "your text" | noti-bot
# or
#   noti-bot "your text" | noti-bot

API=yours
chat_id=yours

if [[ -n "$1" ]]; then
    msg="$1"
else
    msg="$(cat)"
fi


# to escape " and unicode, no, printf is not enough, neither is multiple -d for curl
data="$(echo '{"chat_id": "aaa", "text": "aaa", "disable_notification": false}' |
    jq --arg msg "$msg" --arg chat "$chat_id" '{"chat_id": $ARGS.named.chat, "text": $ARGS.named.msg, "disable_notification": false}')"

# echo "$data"

ans="$(curl -s --tlsv1.2 -X POST \
     -H 'Content-Type: application/json' \
     -d "$data" \
     https://api.telegram.org/bot$API/sendMessage)"

if [[ "$(echo "$ans" | jq -r '.ok')" != "true" ]]; then
    echo "$ans" | jq -r '"error \(.error_code) - \(.description)"'
fi

Demo:

echo -e 'Nope!";$(pwd)"\nyes - приветこんにちは' | ./noti-bot

I know, I know, "at this point just use python or something". I needed it with curl.

If succesful - prints nothing.
If not - prints "error_code - error_description".

@tylersonn
Copy link

Is it possible to send a message to a telegram bot without the bot token? maybe by using username, since username is unique anyway.

@7OH
Copy link

7OH commented Dec 19, 2024

Created a group, switching on themes\topics.
Got link for one topic (like this https://t.me/c/1234567890/1).
How to send message to this topic?

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