使用IFTTT制作比特币提醒

  • Lanceloft
  • 6 Minutes
  • November 1, 2018

开头介绍

  最近对python爬虫和数据分析挺有兴趣的, 看到一个小项目, 利用python调取比特币接口, 然后利用IFTTT设置实时更新和阈值警告, 比较简单适合新手, 自己写了下.

项目开始

  首先我们理清思路, 要实现在手机app上接受实时更新和阈值警告, 首先就是要调取比特币接口, 拿到数据, 然后利用IFTTT接口发送到手机app上, 得到实时更新, 阈值警告则是利用拿到的数据与自己设定的阈值相比, 然后再利用IFTTT接口发送到手机上, 所以第一步我们还是利用python获取数据接口.
  这里 https://api.coinmarketcap.com/v1/ticker/bitcoin/ 就有比特币及其他相关币种的接口数据,
关于调用接口这里使用requess库.
  首先新建一个bitcoin.py项目

1
2
3
4
5
6
7
import requests

BITCOIN_API_URL = 'https://api.coinmarketcap.com/v1/ticker/bitcoin/'

response = requests.get(BITCOIN_API_URL)
response_json = response.json()
print(response_json)

目录执行python3 bitcoin.py, 然后在控制台即可看到输出的数据.
数据

配置IFTTT

下载IFTTT手机app后, 进入IFTTT网站(https://ifttt.com/join)
网站
点击右上角的New Applet, 会出现这个页面,

  1. 然后点击屏幕中间的this, 选择webhooks
  2. 选择receive a web request
  3. Event Name 填写test_event
  4. 然后选择点击that
  5. 搜索notification, 选择send a notification from the IFTTT app
  6. 点击 create action
  7. 点击 Finish
  8. 进入首页,点击Documentation
  9. 复制自己的key

文档

接着我们在刚才的bitcoin上面进行修改

1
2
3
4
import requests

IFTTT_WEBHOOKS_URL = 'https://maker.ifttt.com/trigger/test_event/with/key/{key}'
requests.post(IFTTT_WEBHOOKS_URL)

此时手机应该就已经能接收到信息
接着直接去完成一个比特币更新然后进行发送信息就好了.我们重新新建一个IFTTT应用

  1. 继续选择选择webhooks
  2. 选择receive a web request
  3. Event Name 填写bitcoin_price_update
  4. 同样选择notofication, 但是这里选择 Send a rich notification from the IFTTT App
  5. 继续完成创建

然后我们选择实时更新的信息代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import requests
import time

BITCOIN_API_URL = 'https://api.coinmarketcap.com/v1/ticker/bitcoin/'
IFTTT_WEBHOOKS_URL = 'https://maker.ifttt.com/trigger/bitcoin_price_update/with/key/{key}'

def get_latest_bitcoin_price():
response = requests.get(BITCOIN_API_URL)
response_json = response.json()
return response_json[0]['price_usd']

def post_ifttt_webhook(value):
requests.post(IFTTT_WEBHOOKS_URL, data={'value1': value})

def main():
while True:
price = get_latest_bitcoin_price()
post_ifttt_webhook(price)
time.sleep(30)

if __name__ == '__main__':
main()