2016-12-14 4 views
0

Я играю с бот телеграммой, сидящей на моей малине Pi, все работает хорошо, но я стараюсь показать время безотказной работы с командой/временем безотказной работы, я пробовал:Uptime in Telegram bot in Python

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

или

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

Это теперь моя последняя, ​​неудачная, попытка:

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

Где ошибка?

Вот полный код:

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) 
+0

Пробовал также: команды Элифа == '/ Провел': Провел = subprocess.check_output ([ 'Провел']) печати '', время непрерывной работы bot.sendMessage (chat_id, ул (Провел)) – fdicarlo

ответ

0

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 
+0

К сожалению ничего, здесь, как я изменил: elif command == '/ uptime': с открытым ('/ proc/uptime', 'r') как f: usec = float (f.readline(). split() [0]) usec_str = str (timedelta (seconds = usec)) bot.sendMessage (chat_id, '% s'% usec_str) – fdicarlo

+0

@fdicarlo Как выглядит ваша функция отправки сообщений или объект бота? – moogle

+0

Привет @moogle Я добавил код – fdicarlo

0

Вам нужно, чтобы получить выход из subprocess. Это связано с тем, что в других случаях Python отличает первое значение stdout. код, чтобы получить время безотказной работы должно быть так:

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

Это даст вам время безотказной работы в переменной direct_output.

Смежные вопросы