message_coinmarketcap.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. # -*- coding: utf-8 -*-
  2. '''
  3. 获取 coinmarketcap 数字货币实时价格
  4. '''
  5. import sys
  6. import os
  7. from datetime import datetime
  8. sys.path.append(os.path.join(os.path.abspath(__file__).split('auto')[0] + 'auto'))
  9. from utils.utils_load_config import load_config, get_base_path
  10. config_json = load_config()
  11. base_project = get_base_path()
  12. DB_USER = config_json.get('DB_USER')
  13. DB_PASSWORD = config_json.get('DB_PASSWORD')
  14. DB_IP = config_json.get('DB_IP')
  15. DB_PORT = config_json.get('DB_PORT')
  16. MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'
  17. from utils.utils_mongo_handle import MongoHandle
  18. from message_check_base import *
  19. from utils.utils_send_gotify import *
  20. from utils.utils_send_serverchan import *
  21. class CheckCoinmarketcap:
  22. def __init__(self):
  23. self.db = 'Message'
  24. self.collection = 'coin_price'
  25. self.client = MongoHandle(self.db, self.collection)
  26. self.currency = '¥'
  27. self.url_list = [
  28. {'BTC': 'https://www.coinmarketcap.com/zh/currencies/bitcoin/'},
  29. {'ETH': 'https://www.coinmarketcap.com/zh/currencies/ethereum/'},
  30. {'DOGE': 'https://coinmarketcap.com/zh/currencies/dogecoin/'},
  31. {'ARB': 'https://coinmarketcap.com/zh/currencies/arbitrum/'},
  32. {'ATH': 'https://coinmarketcap.com/zh/currencies/aethir/'},
  33. ]
  34. self.selectors = ['#section-coin-overview > div.sc-65e7f566-0.czwNaM.flexStart.alignBaseline > span']
  35. def processed_data(self, all_data):
  36. # TODO 写入并读取当前数据和上次数据作对比
  37. ts = str(int(time.time()))
  38. data = {ts: {}}
  39. for i in all_data:
  40. for key, value in i[0].items():
  41. data[ts].update({key: float(value.replace(self.currency, '').replace(',', ''))})
  42. self.client.write_data(data)
  43. load_data = self.client.load_data()
  44. if len(load_data) < 2:
  45. return {}
  46. current_data = [value for value in load_data[-1].values()][0]
  47. last_data = [value for value in load_data[-2].values()][0]
  48. result_data = {}
  49. for current_key, current_value in current_data.items():
  50. for last_key, last_value in last_data.items():
  51. if current_key == last_key:
  52. change = ((current_value - last_value) / last_value) * 100
  53. if change != 0:
  54. change = round(change, 3)
  55. else:
  56. change = 0
  57. result_data[current_key] = [f'{self.currency}{current_value}', f'{change}%']
  58. return result_data
  59. def main(self):
  60. # 运行异步函数
  61. all_data = None
  62. crawler = CryptoCrawler(self.url_list, self.selectors, headless=True)
  63. all_data = crawler.main() # 返回的数据格式: [[{'BTC': '¥411,060.52'}], [{'ETH': '¥16,829.59'}], [{'DOGE': '¥0.726'}], [{'ARB': '¥3.69'}], [{'ATH': '¥0.3642'}]])
  64. if not all_data:
  65. print('获取数据失败')
  66. return
  67. # TODO 加一个 mongo 存取历史数据, 并且对比上次检测时的增减
  68. processed_data = self.processed_data(all_data)
  69. # 打印结果,只包含货币名称和价格
  70. context = ''
  71. for key, value in processed_data.items():
  72. context += f'{key}: {value[0]} {value[1]}\n'
  73. if context:
  74. context += '\n{}'.format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  75. # 推送到 message
  76. GotifyNotifier('实时coin价格', context).send_message()
  77. # 推送到 serverchan
  78. ServerChanNotifier('实时coin价格', context.replace('\n', '\n\n')).send_message()
  79. else:
  80. print('no data!')
  81. if __name__ == '__main__':
  82. CheckCoinmarketcap().main()