BTC 实时报价脚本-python

  • 转载请注明出处

需要调用的库:

import sys
import smtplib
from email.mime.text  import  MIMEText
from  email.header import  Header

这里使用的是QQ邮件:smtp.qq.com

QQ邮箱需要注册一段时间才可以使用smtp服务

需要准备的变量:

receiver = 收件人
From = 发送者 #下文为fm
To = 收件人姓名 #下文未加此变量
subject = 标题

完整代码:

import requests
import smtplib
import time
from email.mime.text  import  MIMEText
from  email.header import  Header



def config(sender,receiver, data, fm, smb):
    
    times = time.strftime("%Y-%m-%d %H:%M:%S\n", time.localtime())

    msg = MIMEText(
        '%s%s%s%s'%(times, data[0], data[1], data[2])
    )
    msg['From'] = Header('%s'%fm, 'utf-8')
#    msg['To'] = Header('%s'%To, 'utf-8')
    msg['Subject'] = Header('%s'%smb, 'utf-8')
    sendm(sender,receiver, msg)


def sendm(sender,receiver, msg):
    try:
        smtp = smtplib.SMTP()
        smtp.connect('smtp.qq.com')
        smtp.login('邮箱', '授权码')
        for i in receiver:
            print(i)
            smtp.sendmail(sender, i, msg.as_string())
        smtp.quit()
        print('邮件发送成功!\n%s'%sender)
    except:
        print('发送失败!\n%s'%sender)


def get_html(url):
    content = requests.get(url)
    html = content.json()
    return html

def handle_data(html, bz):
    arg = []
    for i in bz:
        each = html[i]
        da = ('\t%s \n \t价格:%s$\n \t成交量:%s \n \t24小时波动:%s%% \n'
              %(each['symbol'],
                each['price_usd'],
                each['24h_volume_usd'],
                each['percent_change_24h']
                ))
        arg.append(da)
    return arg

if __name__ == '__main__':
    url = 'https://api.coinmarketcap.com/v1/ticker/'
    bz = [0, 1, 7] #BTC, ETH, EOS
    sender = ''
    fm = ''
    receiver = ['']
    data = handle_data(get_html(url), bz)
    smb = 'BTC实时价格'

    while True:
        config(sender,receiver, data, fm, smb)
        time.sleep(300) #五分钟一次

smtp.login(‘xxxxxx@qq.com’, ‘SMTP授权码’) #第二个变量为QQ邮箱的授权码

调用脚本

发表评论

电子邮件地址不会被公开。 必填项已用*标注