telegram-notify/telegram-notify.py
2017-12-26 11:59:09 +01:00

98 lines
3.0 KiB
Python

#!/usr/bin/python
import time
import random
import datetime
import re
import ConfigParser
import telepot
from telepot.loop import MessageLoop
def writeconfig():
global configParser
with open('telegram-notify.conf', 'wb') as configfile:
configParser.write(configfile)
def handle(msg):
global configParser
# {u'date': 1495655440, u'text': u'asd',
# u'from': {u'username': u'pasperti', u'first_name': u'Paolo', u'last_name': u'Asperti', u'id': 173226581, u'language_code': u'it'},
# u'message_id': 64,
# u'chat': {u'username': u'pasperti', u'first_name': u'Paolo', u'last_name': u'Asperti', u'type': u'private', u'id': 173226581}}
pair_pin = configParser.get('general', 'pair_pin')
chat_ids = configParser.get('general', 'chat_ids')
print "pair pin"
print pair_pin
print "chat ids"
print chat_ids
chat_id = msg['chat']['id']
command = msg['text']
param = ''
# sta roba non funziona
paired_user = [x for x in chat_ids if x['id'] == chat_ids]
is_paired = len(paired_user) > 0
if re.match('/',msg['text']):
# e' un comando
command = re.sub(r"\s.*",'',msg['text'])
param = re.sub(r"^([^\s]+)\s","",msg['text'])
print 'Got command: %s (%s)' % (command, param)
if command == '/pair':
if is_paired:
bot.sendMessage(chat_id, 'You\'re already paired.')
elif param == pair_pin:
chat_ids.append(msg['chat'])
configParser.set('general', 'chat_ids', chat_ids)
writeconfig()
bot.sendMessage(chat_id, 'Pairing ok.')
else:
bot.sendMessage(chat_id, 'Pairing failed: wrong pin.')
elif command == '/newpin':
if not is_paired:
bot.sendMessage(chat_id, 'You\'re not allowed to do that. You have to pair first.')
elif param != '':
pair_pin = param
configParser.set('general', 'pair_pin', pair_pin)
writeconfig()
bot.sendMessage(chat_id, 'The new pin is: %s' % pair_pin)
else:
bot.sendMessage(chat_id, 'Please specify the new pin.')
elif command == '/unpair':
if not is_paired:
bot.sendMessage(chat_id, 'You\'re not allowed to do that. You have to pair first.')
else:
# rimuovere dalla lista
bot.sendMessage(chat_id, 'Bye.')
elif command == '/users':
users = [x['username'] + ' (' + x['first_name'] + ' ' + x['last_name'] + ')\n' for x in chat_ids]
print users
bot.sendMessage(chat_id, 'Paired users:\n' + "".join([str(i) for i in users]) )
configParser = ConfigParser.RawConfigParser()
configParser.read(r'telegram-notify.conf')
chat_ids = configParser.get('general', 'chat_ids')
print "type: "
print type(chat_ids)
print chat_ids
if type(chat_ids) is str:
chat_ids=[]
configParser.set('general', 'chat_ids', chat_ids)
writeconfig()
token = configParser.get('general', 'token')
bot = telepot.Bot(token)
MessageLoop(bot, handle).run_as_thread()
print 'I am listening ...'
while 1:
time.sleep(10)