sending Telegram messages from bash scripts

this project is based on the
python-telegram-bot on github.

i additionally had to install python3-yaml by running:

sudo apt-get update
sudo apt-get install python3-yaml

the script i wrote is based on various other examples available on their examples wiki page.

the script also uses pico2wave / svox text-to-speech to read ‘/talk’ messages aloud.
pico2wave can be obtained from
see this github issue for more information on how to install pico2wave command line usage:

usage: <option> [<argument>]
-r|--receiver    run as receiver
-h|--help        show this help message
-u|--update      send a status message to masterID
-m <msg>|--message=<msg>  send <msg> to masterID

pisagraf telegram commands/usage:

This is server_bot
available commands:
/help : show this message
/status : get server status
/talk <text> : be chatty source code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Server Bot to send custom and requested status Telegram messages
This Bot uses the Updater class to handle the bot and the JobQueue to send
timed messages.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.

import sys, getopt
import psutil
import os
import subprocess
from telegram.ext import Updater, CommandHandler, Job
import logging

#the master chat_id to send messages to.
#use @myidbot to get yours or send /status to this bot.
masterID = '<master chat id>'

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',

logger = logging.getLogger(__name__)

def help(bot, update):
    chat_id = update.message.chat_id
    msg = ('This is server_bot\n'
    'available commands:\n'
    '/help : show this message\n'
    '/status : get server status')
    if str(chat_id) == masterID:
      msg = msg+'\n/talk <text> : be chatty'
    bot.send_message(chat_id, text=msg)

def talk(bot, update):
    chat_id = update.message.chat_id
    if str(chat_id) == masterID:
      talkmsg = update.message.text
      if ' ' in talkmsg:
        talkmsg = talkmsg.split(' ', 1)[1]
        if talkmsg:
          temp = subprocess.check_output('pico2wave -w /tmp/picotts.wav -l en-GB "'+talkmsg+'"; aplay -q /tmp/picotts.wav', shell=True)
          if temp:
            bot.send_message(chat_id, text=temp)
            bot.send_message(chat_id, text="spoken like a true warrior!")

def sta(bot, update):
    status(bot, update.message.chat_id)

def status(bot, chat_id):
    stat0 = os.statvfs('/')
    stat1 = os.statvfs('/home')
    temp = subprocess.check_output('expr "$(sensors | grep "Core 0:")" : ".*\(+....°C*\)"', shell=True)
    msg = ('server_bot status\n'
    'This Chat ID is: '+str(chat_id)+'\n'
    'CPU load: '+str(psutil.cpu_percent())+' %\n'
    'RAM usage: '+str(psutil.virtual_memory().percent)+' %\n'
    'df on root: '+str((stat0.f_frsize * stat0.f_bavail)/1048576)+' MB\n'
    'df on home: '+str((stat1.f_frsize * stat1.f_bavail)/1073741824)+' GB\n'
    'TCore: '+str(temp))
    bot.send_message(chat_id, text=msg)

def error(bot, update, error):
    logger.warning('Update "%s" caused error "%s"' % (update, error))

def main(argv):
    updater = Updater("<telegram bot token>")
    # Get the dispatcher to register handlers
    dp = updater.dispatcher

        opts, args = getopt.getopt(argv,"rhum:",["receiver","help","update","message="])
    except getopt.GetoptError:
        print 'invalid arguments'

    for opt, arg in opts:
        if opt == '-h' or opt == '--help':
            usage = ('usage: <option> [<argument>]\n'\
            '-r|--receiver\t\t\trun as receiver\n'\
            '-h|--help\t\t\tshow this help message\n'\
            '-u|--update\t\t\tsend a status message to masterID\n'\
            '-m <msg>|--message=<msg>\tsend <msg> to masterID')
            print usage
        if opt == '-m' or opt == '--message':
            # log all errors

  , text=arg)
            print 'message sent'
        if opt == '-u' or opt == '--update':
            # log all errors
            status(, masterID)
            print 'message sent'
        if opt == '-r' or opt == '--receiver':
            # on different commands - answer in Telegram
            dp.add_handler(CommandHandler("start", help))
            dp.add_handler(CommandHandler("help", help))
            dp.add_handler(CommandHandler("status", sta))
            dp.add_handler(CommandHandler("talk", talk))
            # log all errors
            # Start the Bot
            # Block until you press Ctrl-C or the process receives SIGINT, SIGTERM or
            # SIGABRT. This should be used most of the time, since start_polling() is
            # non-blocking and will stop the bot gracefully.

if __name__ == '__main__':

Posted in IT

Leave a Reply

Your email address will not be published.