Advertisement
TringaliLuca

RaspberryPi domotic Telegram bot

Jan 4th, 2017
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.14 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Run this code with python2.7
  5. #
  6.  
  7. import time
  8. import random
  9. import datetime
  10. import telepot
  11. import os
  12. import sys
  13. import RPi.GPIO as GPIO
  14. from w1thermsensor import W1ThermSensor
  15.  
  16.  
  17.  
  18. telegramtoken = '267001271:EAH6Km-3MR61c9PGlGrwDQ3JJS_5f17YlTZ' #telegram bot token from BotFather
  19. checkuserid = 1 #enable users whitelist, so only certain people can talk with this bot
  20. usersfile = '/root/botusers.csv' #the file where we store the list of users who can talk with bot
  21. attemptsfile = '/root/attempts.log' #the file where we log denied accesses
  22. relay = 18 #GPIO pin where we put the relay or the LED
  23. button = 17 #GPIO pin where we put the button
  24. active = 1 #if set to 0 the bot will stop
  25.  
  26.    
  27. def listusers():
  28.     if not os.path.isfile(usersfile):
  29.         return ''
  30.     text_file = open(usersfile, "r")
  31.     lines = text_file.read().split(',')
  32.     text_file.close()
  33.     del lines[-1] #remove last element since it is blank
  34.     return lines
  35.  
  36. def adduser(name):
  37.     csv = ""
  38.     users = listusers()
  39.     if users != "":
  40.         for usr in users:
  41.             csv = csv+usr+","
  42.     csv = csv+name+","
  43.     text_file = open(usersfile, "w")
  44.     text_file.write(csv)
  45.     text_file.close()
  46.    
  47. def deluser(name):
  48.     csv = ""
  49.     users = listusers()
  50.     if users != "":
  51.         for usr in users:
  52.             if usr != name:
  53.                 csv = csv+usr+","
  54.     text_file = open(usersfile, "w")
  55.     text_file.write(csv)
  56.     text_file.close()
  57.  
  58. def handle(msg):
  59.     chat_id = msg['chat']['id']
  60.     command = msg['text']
  61.     sender = msg['from']['id']
  62.  
  63.     users = listusers()
  64.  
  65.     print 'Got command: ' + command
  66.  
  67.     if checkuserid == 1:
  68.         verified = 0
  69.         if users != "":
  70.             for usr in users:
  71.                 if str(sender) == usr:
  72.                     verified = 1
  73.         if verified == 0:
  74.             bot.sendMessage(chat_id, "I don't talk with strangers, dear "+str(sender))
  75.             #write this user in the list of attempted accesses
  76.             if attemptsfile != '':
  77.                 lines = ''
  78.                 if os.path.isfile(attemptsfile):
  79.                     text_file = open(attemptsfile, "r")
  80.                     lines = text_file.read()
  81.                     text_file.close()
  82.                 lines = lines + str(datetime.datetime.now()) + " --- UserdID: " + str(sender) + " DENIED \n"
  83.                 text_file = open(attemptsfile, "w")
  84.                 text_file.write(lines)
  85.                 text_file.close()
  86.             return
  87.  
  88.  
  89.     if command == '/time':
  90.         bot.sendMessage(chat_id, str(datetime.datetime.now()))
  91.     elif '/adduser' in command:
  92.         if len(command.split(' ')) > 1:
  93.             usrname = command.split(' ')[1]
  94.             adduser(usrname)
  95.             bot.sendMessage(chat_id, "User "+usrname+" added")
  96.     elif '/deluser' in command:
  97.         if len(command.split(' ')) > 1:
  98.             usrname = command.split(' ')[1]
  99.             deluser(usrname)
  100.             bot.sendMessage(chat_id, "User "+usrname+" deleted")
  101.     elif 'webcam' in command:
  102.         tmpfile = '/tmp/'+str(datetime.datetime.now())+str(sender)+'.jpeg'
  103.         tmpfile = tmpfile.replace(" ","_")
  104.         tmpfile = tmpfile.replace(":","_")
  105.         os.system("streamer -s 1280x720 -f jpeg -o "+tmpfile)
  106.         bot.sendPhoto(chat_id, open(tmpfile, "rb"), caption = tmpfile)
  107.         os.remove(tmpfile)
  108.     elif '/pinon' in command:
  109.         pin = relay
  110.         if len(command.split(' ')) > 1:
  111.             pin = command.split(' ')[1]
  112.         GPIO.setup(int(pin), GPIO.OUT)
  113.         GPIO.output(int(pin), GPIO.HIGH)
  114.         bot.sendMessage(chat_id, "Set "+str(pin)+" HIGH")
  115.     elif '/pinoff' in command:
  116.         pin = relay
  117.         if len(command.split(' ')) > 1:
  118.             pin = command.split(' ')[1]
  119.         GPIO.setup(int(pin), GPIO.OUT)
  120.         GPIO.output(int(pin), GPIO.LOW)
  121.         bot.sendMessage(chat_id, "Set "+str(pin)+" LOW")
  122.     elif '/temperature' in command:
  123.         sensor = W1ThermSensor()
  124.         temperature_in_celsius = sensor.get_temperature()
  125.         bot.sendMessage(chat_id, "Temperature is "+str(temperature_in_celsius)+"° Celsius")
  126.     elif command == '/exit':
  127.         global active
  128.         active = False
  129.         bot.sendMessage(chat_id, "The bot will shutdown in 10 seconds")
  130.     else:
  131.         bot.sendMessage(chat_id, 'echo: ' + command + ' from: '+str(sender))
  132.  
  133. def my_callback(pin):
  134.     input_value = GPIO.input(pin)
  135.     print "The GPIO pin input "+str(pin)+" has value: "+str(input_value)
  136.     users = listusers()
  137.     if users != "":
  138.         for usr in users:
  139.             bot.sendMessage(usr, "The button on GPIO pin "+str(pin)+" changed value: "+str(input_value))
  140.  
  141.  
  142. print "Connecting to Telegram..."
  143. bot = telepot.Bot(telegramtoken)
  144. print bot.getMe()
  145.  
  146. os.system('modprobe w1-gpio')
  147. os.system('modprobe w1-therm')
  148.  
  149. GPIO.setmode(GPIO.BCM)
  150. GPIO.setwarnings(False)
  151.  
  152. GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
  153. GPIO.add_event_detect(button, GPIO.BOTH)
  154. GPIO.add_event_callback(button, my_callback)
  155.  
  156. bot.message_loop(handle)
  157. print 'I am listening ...'
  158.  
  159. while active:
  160.     time.sleep(10)
  161. print "Exiting"
  162. sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement