configurable address monitoring

From Chocolate Owl, 8 Years ago, written in Python, viewed 4 times.
URL https://paste.blessuren.de/view/8a85158f Embed
Download Paste or View Raw
  1. from subprocess import check_output
  2. import requests
  3. import json
  4. import os
  5. import time
  6. import random
  7. import datetime
  8. import telepot
  9. from telepot.loop import MessageLoop
  10. import telepot.api
  11. import urllib3
  12. import logging
  13.  
  14. '''
  15. This script is based on the tutorial:
  16. http://www.instructables.com/id/Set-up-Telegram-Bot-on-Raspberry-Pi/
  17. '''
  18.  
  19. ### configure gloabls here
  20. MONITOR_TX_ADDR     = True                  # enable tx address monitoring on cryptoid.info
  21. main_loop_cycle     = 120                   # time in seconds
  22. bot_api_key         = "524648907:AAFYnphAtSQelw5u22ejsKvt2PiE5x5zBUw"
  23. access_ids          = [ 310989044, ]        # array of user ids that can communicate with the bot
  24. master_chat_id      = 310989044             # the chat id of the master that gets security notifications
  25. pivx_cli_dir        = "/home/pivx"          # location of pivx-cli
  26. check_staking_dir   = "/home/pivx"          # location of check_staking.sh
  27. logfile             = "bot.err"             # name of the logfile
  28. if MONITOR_TX_ADDR:
  29.     cryptoid_id     = 353908                # magic?! id to get all transactions from cryptoid.info for the adress below
  30.     tx_address      = "DDyN3knkxb6U7dwmnqvhhAyt4AwRjsbASJ"
  31.  
  32. # set up logger
  33. logging.basicConfig(filename=logfile,level=logging.INFO)
  34.  
  35. # enable retry mechanism in connection pool
  36. telepot.api._pools = {
  37.     'default': urllib3.PoolManager(num_pools=3, maxsize=10, retries=3, timeout=30),
  38. }
  39.  
  40. def sendMessageRetry(chat_id, msg, retry_limit = 3, parse_mode=""):
  41.     # the ugly retry mechanism should not be necessary, but time will tell...
  42.     for x in range(0, retry_limit):
  43.         try:
  44.             bot.sendMessage(chat_id, msg, parse_mode=parse_mode)
  45.             return
  46.         except Exception as e:
  47.             logging.warning("Error sending message (%s)" % str(e))
  48.             time.sleep(2)
  49.     logging.error("Couldn't send message, tried %d times" % retry_limit)
  50.  
  51. def pivxGetLastTransaction(id):
  52.     url = "https://chainz.cryptoid.info/explorer/address.tx.dws?coin=pivx&id=%d" % id
  53.     response = requests.post(url)
  54.     if response.ok:
  55.         transactions = str(response.content)[2:-4].split("],[")
  56.         t = transactions[0].split(",")    # grab last transaction
  57.         tx_hash = t[1].replace("\"", "")
  58.         amount = t[4]
  59.         return (tx_hash, float(amount))
  60.     else:
  61.         raise Exception("Error in pivxGetLastTransaction occured: %s" % str(response))
  62.  
  63. def pivxGetAccountBalance():
  64.     j = json.loads(pivxGetInfo())
  65.     return j["balance"]
  66.  
  67. def pivxGetInfo():
  68.     try:
  69.         os.chdir(pivx_cli_dir)
  70.         return str(check_output(["./pivx-cli", "getinfo"]))
  71.     except CalledProcessError:
  72.         raise Exception("Error while executing `%s/pivx-cli getinfo` occured" % pivx_cli_dir)
  73.  
  74. def pivxCheckStaking():
  75.     try:
  76.         os.chdir(check_staking_dir)
  77.         return str(check_output(["./check_staking.sh", ""]))
  78.     except CalledProcessError:
  79.         raise Exception("Error while executing `%s/check_staking.sh` occured" % check_staking_dir)
  80.  
  81. def printHelp(chat_id):
  82.     msg = "";
  83.     msg += "/help - display this help.\r\n"
  84.     msg += "/pivxinfo - reply with output of `pivx-cli getinfo`.\r\n"
  85.     msg += "/pivxstaking - reply with output of `check_staking.sh`.\r\n"
  86.     msg += "/roll - reply with a random integer between 1 and 6, like rolling a dice.\r\n"
  87.     msg += "/time - reply with the current time, like a clock.\r\n"
  88.     sendMessageRetry(chat_id, msg, parse_mode='Markdown')
  89.  
  90. def handle(msg):
  91.     chat_id = msg['chat']['id']
  92.     command = msg['text']
  93.  
  94.     print 'Got command: %s' % command
  95.  
  96.     if msg['from']['id'] not in access_ids:
  97.         sendMessageRetry(chat_id, "Access denied")
  98.         sendMessageRetry(master_chat_id, "Access violation detected: %s" % str(msg))
  99.         return
  100.  
  101.     try:
  102.         if command == '/help':
  103.             printHelp(chat_id)
  104.         elif command == '/pivxinfo':
  105.             sendMessageRetry(chat_id, pivxGetInfo())
  106.         elif command == '/pivxstaking':
  107.             sendMessageRetry(chat_id, pivxCheckStaking())
  108.         elif command == '/roll':
  109.             sendMessageRetry(chat_id, random.randint(1,6))
  110.         elif command == '/time':
  111.             sendMessageRetry(chat_id, str(datetime.datetime.now()))
  112.         else:
  113.             sendMessageRetry(chat_id, "I did not understand you. Type /help for a list of supported commands.")
  114.     except Exception as e:
  115.         msg = "Error in handle() occurred: %s" % str(e)
  116.         logging.error(msg)
  117.         sendMessageRetry(chat_id, msg)
  118.  
  119. bot = telepot.Bot(bot_api_key)
  120.  
  121. MessageLoop(bot, handle).run_as_thread()
  122. print 'I am listening ...'
  123.  
  124. old_balance = None
  125. if MONITOR_TX_ADDR is True:
  126.     old_tx_hash = None
  127.  
  128. while 1:
  129.     try:
  130.         # initialization - do this only once at the beginning
  131.         # NB: we do it inside the loop in case it fails at the first time
  132.         if old_balance is None:
  133.             old_balance = pivxGetAccountBalance()
  134.             logging.info("Initial balance is: %f" % old_balance)
  135.         if MONITOR_TX_ADDR is True and old_tx_hash is None:
  136.             old_tx_hash, old_tx_amount = pivxGetLastTransaction(cryptoid_id)
  137.             logging.info("Initial transaction is: %s %f" % (old_tx_hash, old_tx_amount))
  138.  
  139.         time.sleep(main_loop_cycle)
  140.  
  141.         # do this only if initialization above was successful
  142.         if old_balance is not None:
  143.             # handle (changed) account balance
  144.             new_balance = pivxGetAccountBalance()
  145.             diff = new_balance - old_balance
  146.             if diff != 0:
  147.                 msg = "*Account balance changed* by %f piv" % diff
  148.                 logging.info(msg)
  149.                 sendMessageRetry(master_chat_id, msg, parse_mode='Markdown')
  150.                 old_balance = new_balance
  151.  
  152.         # do this only if initialization above was successful
  153.         if MONITOR_TX_ADDR is True and old_tx_hash is not None:
  154.             # handle (new) transactions
  155.             new_tx_hash, new_tx_amount = pivxGetLastTransaction(cryptoid_id)
  156.             if new_tx_hash != old_tx_hash:
  157.                 msg = "*New transaction* on [address](http://www.presstab.pw/phpexplorer/PIVX/address.php?address=%s) detected. Tx amount = %f piv" % (tx_address, new_tx_amount)
  158.                 logging.info(msg)
  159.                 sendMessageRetry(master_chat_id, msg, parse_mode='Markdown')
  160.                 old_tx_hash = new_tx_hash
  161.  
  162.     except Exception as e:
  163.         msg = "Error in main loop occurred: %s" % str(e)
  164.         logging.error(msg)
  165.         sendMessageRetry(chat_id, msg)
  166.  

Reply to "configurable address monitoring"

Here you can reply to the paste above