Untitled

From Speedy Guinea Pig, 8 Years ago, written in Python, viewed 4 times.
URL https://paste.blessuren.de/view/a8e9423a 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         = "123:aaaaa"
  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 retry 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.         raise Exception("Error in pivxGetLastTransaction occured: %s" % str(response))
  59.  
  60. def pivxGetAccountBalance():
  61.     j = json.loads(pivxGetInfo())
  62.     return j["balance"]
  63.  
  64. def pivxGetInfo():
  65.     try:
  66.         os.chdir(pivx_cli_dir)
  67.         return str(check_output(["./pivx-cli", "getinfo"]))
  68.     except CalledProcessError:
  69.         raise Exception("Error while executing `%s/pivx-cli getinfo` occured" % pivx_cli_dir)
  70.  
  71. def pivxCheckStaking():
  72.     try:
  73.         os.chdir(check_staking_dir)
  74.         return str(check_output(["./check_staking.sh", ""]))
  75.     except CalledProcessError:
  76.         raise Exception("Error while executing `%s/check_staking.sh` occured" % check_staking_dir)
  77.  
  78. def printHelp(chat_id):
  79.     msg = "";
  80.     msg += "/help - display this help.\r\n"
  81.     msg += "/pivxinfo - reply with output of `pivx-cli getinfo`.\r\n"
  82.     msg += "/pivxstaking - reply with output of `check_staking.sh`.\r\n"
  83.     msg += "/roll - reply with a random integer between 1 and 6, like rolling a dice.\r\n"
  84.     msg += "/time - reply with the current time, like a clock.\r\n"
  85.     sendMessageRetry(chat_id, msg, parse_mode='Markdown')
  86.  
  87. def handle(msg):
  88.     chat_id = msg['chat']['id']
  89.     command = msg['text']
  90.  
  91.     print 'Got command: %s' % command
  92.  
  93.     if msg['from']['id'] not in access_ids:
  94.         sendMessageRetry(chat_id, "Access denied")
  95.         sendMessageRetry(master_chat_id, "Access violation detected: %s" % str(msg))
  96.         return
  97.  
  98.     try:
  99.         if command == '/help':
  100.             printHelp(chat_id)
  101.         elif command == '/pivxinfo':
  102.             sendMessageRetry(chat_id, pivxGetInfo())
  103.         elif command == '/pivxstaking':
  104.             sendMessageRetry(chat_id, pivxCheckStaking())
  105.         elif command == '/roll':
  106.             sendMessageRetry(chat_id, random.randint(1,6))
  107.         elif command == '/time':
  108.             sendMessageRetry(chat_id, str(datetime.datetime.now()))
  109.         else:
  110.             sendMessageRetry(chat_id, "I did not understand you. Type /help for a list of supported commands.")
  111.     except Exception as e:
  112.         msg = "Error in handle() occurred: %s" % str(e)
  113.         logging.error(msg)
  114.         sendMessageRetry(chat_id, msg)
  115.  
  116. bot = telepot.Bot(bot_api_key)
  117.  
  118. MessageLoop(bot, handle).run_as_thread()
  119. print 'I am listening ...'
  120.  
  121. old_balance = None
  122. old_tx_hash = None
  123.  
  124. while 1:
  125.     try:
  126.         # do this only once at the beginning
  127.         # NB: we do it inside the loop in case it fails at the first time
  128.         #if old_balance is None or old_tx_hash is None:
  129.         if old_balance is None:
  130.             old_balance = pivxGetAccountBalance()
  131.             logging.info("Initial balance is: %f" % old_balance)
  132.             #old_tx_hash, old_tx_amount = pivxGetLastTransaction(cryptoid_id)
  133.             #logging.info("Initial transaction is: %s %f" % (old_tx_hash, old_tx_amount))
  134.  
  135.         time.sleep(120)
  136.  
  137.         # do this only if initialization above was successful
  138.         #if old_balance is not None and old_tx_hash is not None:
  139.         if old_balance is not None:
  140.             # handle (changed) account balance
  141.             new_balance = pivxGetAccountBalance()
  142.             diff = new_balance - old_balance
  143.             if diff != 0:
  144.                 msg = "*Account balance changed* by %f piv" % diff
  145.                 logging.info(msg)
  146.                 sendMessageRetry(master_chat_id, msg, parse_mode='Markdown')
  147.                 old_balance = new_balance
  148.     except Exception as e:
  149.         msg = "Error in main loop occurred: %s" % str(e)
  150.         logging.error(msg)
  151.         sendMessageRetry(master_chat_id, msg)

Reply to "Untitled"

Here you can reply to the paste above