Untitled

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

Reply to "Untitled"

Here you can reply to the paste above