【问题标题】:Uptime in Telegram bot in PythonPython 中 Telegram 机器人的正常运行时间
【发布时间】:2023-03-08 12:10:01
【问题描述】:

我在我的 Raspberry Pi 上玩 Telegram 机器人,一切正常,但我试图用命令 /uptime 显示 rpi 的正常运行时间,但没有成功,我尝试了:

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)

【问题讨论】:

  • 也试过:elif command == '/uptime': uptime = subprocess.check_output(['uptime']) print '', uptime bot.sendMessage(chat_id, str(uptime))跨度>

标签: python-2.7 telegram-bot python-telegram-bot


【解决方案1】:

您需要从subprocess 获取输出。这是因为在其他情况下,Python 会转换 stdout 的第一个值。 获取正常运行时间的代码应该是这样的:

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

这将为您提供direct_output 变量中的正常运行时间。

【讨论】:

    【解决方案2】:

    试试……

    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
    

    【讨论】:

    • 不幸的是什么都没有,这里我是如何修改的: 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)
    • @fdicarlo 您的发送消息功能或机器人对象是什么样的?
    猜你喜欢
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多