A simple bash script bot to send status message to telegram.

The telegram bot script

Here is a simple telegram bot script I have used to send out OpenStack deployment status message to my telegram.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/bin/bash

token="bot[telegram-bot-api-token]"
chat_id= # Send a chat to bot from telegram and hit https://api.telegram.org/bot[telegram-bot-api-token]/getUpdates to see chat_id

if [ -f ~/.bot-stat]; then
    source ~/.bot-stat
else
  lstatus="OK"
  sdate=$(date +%s)
fi

send_message(){
    tmpfile=$(mktemp /tmp/telebot.XXXXXXX)
    mstatus=$(echo $status|sed -e 's/_/ /g')
    cat > $tmpfile <<EOF
{"chat_id":"$chat_id", "parse_mode":"markdown", "text":"*Deployment*\nStatus: *$mstatus*\nTime: $date \nDuration: $duration"}
EOF
    curl -k --header 'Content-Type: application/json' \
        --data-binary @${tmpfile} \
        --request POST https://api.telegram.org/$token/sendMessage
    rm -f $tmpfile
}

while : ; do
    status=$(source ~/stackrc && openstack stack list -c "Stack Status" -f value)
    if [ "$status" != "$lstatus" ]; then
       cdate=$(date +%s)
       date="$(date +%D-%H:%M:%S)"
       duration=$(($cdate-$sdate))
       send_message
       lstatus=$status
       sdate=$cdate
       echo -e "lstatus=$status\nsdate=$cdate" > ~/.bot-stat
    fi
    sleep 5
done

links

social