Creato da l30n1d4 il 12/11/2013

Raspberry Pi Tank

Appunti di codice per l'utilizzo del Raspberry Pi

 

« RPi-MonitorStorj Share con Raspberry Pi »

Telegram Bot with Raspberry Pi

Post n°16 pubblicato il 28 Luglio 2017 da l30n1d4
 

sudo apt-get install python-pip
sudo pip install telepot

sudo nano bot.py
_________________________________________________________
import commands
import subprocess
from datetime import timedelta
import sys
import os
import telepot
import datetime
import time
#--------import per la request di json
import requests
#--------import per il parser dei caratteri speciali
try:
    from HTMLParser import HTMLParser # Python 2.6-2.7
except ImportError:
    from html.parser import HTMLParser # Python 3

"""
Ctrl-C per uscire.
"""

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

def get_cpuload():
    cpuload = subprocess.check_output('top -bn1 | grep "Cpu(s)" | sed "s/.*, *([0-9.]*)%* id.*/1/" | awk "{print 100 - $1'%'}"')
    return cpuload

def get_api(child):
    r = requests.get('http://meteoxxxxxxxxxxxxxxxxx.altervista.org/api.json')
    value = r.json()['stats']['current'][child]
    h = HTMLParser()
    value = h.unescape(value)
    return value

def get_ram():
    san = subprocess.check_output(['free','-m'])
    lines = san.split('n')
    return ( int(lines[1].split()[3]) )

def entities(frase):
    h = HTMLParser()
    return h.unescape(frase)

def get_cpu_temp():
    tempFile = open( "/sys/class/thermal/thermal_zone0/temp" )
    cpu_temp = tempFile.read()
    tempFile.close()
    temperatura = float(cpu_temp)/1000
    temperatura = str(temperatura) + "°C"
    h = HTMLParser()
    ritorno = h.unescape(temperatura)
    return ritorno

def get_gpu_temp():
    gpu_temp = commands.getoutput( '/opt/vc/bin/vcgencmd measure_temp' ).replace('temp=','').replace(''C','')
    return float(gpu_temp)

def get_connections():
    san = subprocess.check_output(['netstat','-tun'])
    return len([x for x in san.split() if x == 'ESTABLISHED'])

def get_ipaddress_ext():
    out = commands.getoutput( 'curl ipv4.icanhazip.com' )
    return out.split('n')[-1]

def get_ipaddress_int():
    arg='ip route list'
    ip=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
    data = ip.communicate()
    split_data = data[0].split()
    ipaddr = split_data[split_data.index('src')+1]
    return ipaddr

def get_uptime():
    with open('/proc/uptime', 'r') as f:
        uptime_seconds = float(f.readline().split()[0])
        uptime = (timedelta(seconds = uptime_seconds))
    return str(uptime).split('.')[0]

def handle(msg):
    chat_id = msg['chat']['id']
    command = msg['text']
    sender = msg['from']['id']
    print 'comando: %s' % command
   
    #if sender in id_a:
    if sender:
        if command == '/ciao':
            bot.sendMessage(chat_id, 'Hei, ciao!')
        elif command == '/status':
            #bot.sendMessage(chat_id, 'CPU ' + str(get_cpuload()) + '%')
            bot.sendMessage(chat_id, 'Temp.CPU ' + get_cpu_temp())
            bot.sendMessage(chat_id, 'Free RAM ' + str(get_ram()) + ' MB')
            bot.sendMessage(chat_id, 'IP int ' + str(get_ipaddress_int()))
            bot.sendMessage(chat_id, 'IP ext ' + str(get_ipaddress_ext()))
            bot.sendMessage(chat_id, 'Uptime ' + get_uptime())
        elif command == '/meteo':
            bot.sendMessage(chat_id, 'OutTemp: ' + get_api('outTemp'))
            bot.sendMessage(chat_id, 'Humidity: ' + get_api('humidity'))
            bot.sendMessage(chat_id, 'WindSpeed: ' + get_api('windSpeed'))
        elif command == '/reboot':
            if sender in id_a:
                bot.sendMessage(chat_id, 'Riavvio in corso...')
                os.system("sudo reboot")
            else:
                bot.sendMessage(chat_id, 'Not auth for the reboot ' + str(sender))
        else:
            bot.sendMessage(chat_id, 'Not auth ' + str(sender))
bot = telepot.Bot('000000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
bot.message_loop(handle)
print 'listening...'
while 1:
    time.sleep(100)
__________________________________________________________________

salvare lo script

provare lo script con
sudo python bot.py


sudo crontab -e
___________________________
aggiungere in fondo la riga

@reboot python /home/pi/bot.py &

Commenti al Post:
Nessun commento
 

AREA PERSONALE

 

TAG

 

ARCHIVIO MESSAGGI

 
 << Aprile 2024 >> 
 
LuMaMeGiVeSaDo
 
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          
 
 

CERCA IN QUESTO BLOG

  Trova
 
 
 
 

© Italiaonline S.p.A. 2024Direzione e coordinamento di Libero Acquisition S.á r.l.P. IVA 03970540963