from subprocess import check_output
import json
import os
import time
import random
import datetime
import telepot
from telepot.loop import MessageLoop
'''
This script is based on the tutorial:
http://www.instructables.com/id/Set-up-Telegram-Bot-on-Raspberry-Pi/
'''
access_ids = [ 310989044, ] # array of user ids that can communicate with the bot
master_chat_id = 310989044 # the chat id of the master that gets security notifications
def pivxGetAccountBalance():
try:
j = json.loads(pivxGetInfo())
return j["balance"]
except Exception as e:
bot.sendMessage(master_chat_id, "Error in pivxGetAccountBalance occured: %s" % str(e))
return -1.
def pivxGetInfo():
try:
os.chdir("/home/pivx")
return str(check_output(["./pivx-cli", "getinfo"]))
except CalledProcessError:
raise Exception("Error while executing `/home/pivx/pivx-cli getinfo` occured")
def pivxCheckStaking():
try:
os.chdir("/home/pivx")
return str(check_output(["./check_staking.sh", ""]))
except CalledProcessError:
raise Exception("Error while executing `/home/pivx/check_staking.sh` occured")
def printHelp(chat_id):
msg = "";
msg += "/help - display this help.\r\n"
msg += "/pivxinfo - reply with output of `pivx-cli getinfo`.\r\n"
msg += "/pivxstaking - reply with output of `check_staking.sh`.\r\n"
msg += "/roll - reply with a random integer between 1 and 6, like rolling a dice.\r\n"
msg += "/time - reply with the current time, like a clock.\r\n"
bot.sendMessage(chat_id, msg)
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
user_id = msg['from']['id']
print 'Got command: %s' % command
if user_id not in access_ids:
bot.sendMessage(chat_id, "Access denied")
bot.sendMessage(master_chat_id, "Access violation detected: %s" % str(msg))
return
try:
if command == '/help':
printHelp(chat_id)
elif command == '/pivxinfo':
bot.sendMessage(chat_id, pivxGetInfo())
elif command == '/pivxstaking':
bot.sendMessage(chat_id, pivxCheckStaking())
elif command == '/roll':
bot.sendMessage(chat_id, random.randint(1,6))
elif command == '/time':
bot.sendMessage(chat_id, str(datetime.datetime.now()))
except Exception as e:
bot.sendMessage(chat_id, str(e))
bot = telepot.Bot('123:XXX')
MessageLoop(bot, handle).run_as_thread()
print 'I am listening ...'
old_balance = pivxGetAccountBalance()
while 1:
time.sleep(120)
new_balance = pivxGetAccountBalance()
diff = new_balance - old_balance
if diff != 0:
bot.sendMessage(master_chat_id, "Staking reward received: %f piv" % diff)
old_balance = new_balance