Uptime in Telegram bot in Python

1.2k views Asked by At

I'm playing with a Telegram bot sitting on my Raspberry Pi, all works good but I'm trying to show the uptime of the rpi with the command /uptime without success, I tried with:

elif command == '/uptime':
   bot.sendMessage(chat_id, os.system("uptime"))

or with

elif command == '/uptime':
  uptime = os.system("uptime")
  bot.sendMessage(chat_id,'%s' % uptime )

This is now my last, unsuccessful, attempt:

elif command == '/uptime':
   uptime = os.popen("awk '{print $1}' /proc/uptime").readline()
   bot.sendMessage(chat_id, ('uptime(sec) = '+uptime))

Where is the mistake?

Here is the complete code:

import sys
import os
import telepot
import datetime
import time
from datetime import timedelta

id_a = [111111,2222222,3333333,4444444,5555555]

def handle(msg):
    chat_id = msg['chat']['id']
    command = msg['text']
    sender = msg['from']['id']


    print 'Got command: %s' % command

    if sender in id_a:
     if command == '/ciao':
            bot.sendMessage(chat_id, 'Hei, ciao!')
     elif command == '/apri':
         os.system("sudo python /home/pi/tg/xyz.py")
         bot.sendMessage(chat_id, 'Ti ho aperto!')
    elif command == '/uptime':
       with open('/proc/uptime', 'r') as f:
        usec = float(f.readline().split()[0])
        usec_str = str(timedelta(seconds = usec))
        bot.sendMessage(chat_id, '%s' % usec_str)
    elif command == '/riavvia':
            bot.sendMessage(chat_id, 'Rebooting...')
            os.system("sudo reboot")
    else:
       bot.sendMessage(chat_id, 'Forbidden access!')
       bot.sendMessage(chat_id, sender)

bot = telepot.Bot('myToken')
bot.message_loop(handle)
print 'I am listening ...'

while 1:
    time.sleep(10)
2

There are 2 answers

0
pierluigi riti On

You need to get the output from the subprocess. This is because in other cases Python casts the first value of the stdout. The code to get the uptime should be like this:

import subprocess    
direct_output = subprocess.check_output('uptime', shell=True)

This will give you the uptime in the direct_output variable.

2
moogle On

Try...

from datetime import timedelta

with open('/proc/uptime', 'r') as f:
    usec = float(f.readline().split()[0])
    usec_str = str(timedelta(seconds = usec))
    # and send message usec_str