Python 京东云无线宝消息推送功能

 更新时间:2021年05月20日 14:30:22   作者:Alex_Mercer  
这篇文章主要介绍了Python 京东云无线宝消息推送功能,发送钉钉消息获取可用积分,详细配置文件通过实例代码给大家讲解的很详细,代码+注释讲解的很详细,需要的朋友可以参考下

配置文件

注释里面有写,懒得用配置文件了

代码

# 京东云无线路由宝推送
import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parse
from datetime import datetime
# 发送钉钉消息
def sendinfo_ding(token,secret,data):
    dic=get_timestamp_and_sign_by_secret(secret)
    timestamp=dic['timestamp']
    sign=dic['sign']
    url = 'https://oapi.dingtalk.com/robot/send?access_token=%s&timestamp=%s&sign=%s' %(token,timestamp,sign)  #你的机器人webhook地址
    headers = {'Content-Type': 'application/json'}
    f = requests.post(url, data=json.dumps(data), headers=headers)
# 获取密签
def get_timestamp_and_sign_by_secret(secret):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return {"timestamp":timestamp,"sign":sign}
# 获取可用积分
def get_jd_total_avail_point(wskey):
    url='https://router-app-api.jdcloud.com/v1/regions/cn-north-1/pinTotalAvailPoint'
    headers = {'Content-Type': 'application/json','wskey':wskey}
    rsp=requests.get(url,headers=headers)
    data=(json.loads(rsp.text)['result']['totalAvailPoint'])
    return {'totalAvailPoint':data}
# 获取积分详情
def get_jd_detail(wskey):
    url='https://router-app-api.jdcloud.com/v1/regions/cn-north-1/todayPointDetail?sortField=today_point&sortDirection=DESC&pageSize=15&currentPage=1'
    headers = {'Content-Type': 'application/json','wskey':wskey}
    rsp=requests.get(url,headers=headers)
    data=(json.loads(rsp.text)['result'])
    items=data['pointInfos']
    total_today_point=0
    total_all_point=0
    dic={}
    dic['todayDate']=data['todayDate']
    dic['items']=[]
    for item in items:
        mac=item['mac']
        today_point=item['todayPointIncome']
        all_point=item['allPointIncome']
        total_today_point+=int(today_point)
        total_all_point+=int(all_point)
        dic['items'].append(item)
    dic['total_today_point']=total_today_point
    dic['total_all_point']=total_all_point
    return dic
# 发送京东路由宝日报
def send_jd_router(wskey):
    dic=get_jd_detail(wskey)
    msg='# 京东路由宝日报\n'
    msg+='## %s \n' %(dic['todayDate'])
    msg+=('> 今日获取总积分为**%d**分,对应金钱为 **%.2f**元\n' %(dic['total_today_point'],float(dic['total_today_point'])/100))
    for item in dic['items']:
        msg+=('>> 设备**%s** \n' %(item['mac']))
        msg+=('>>> 今日获取积分为**%s**分,对应金钱为 **%.2f**元 \n\n' %(item['todayPointIncome'],float(item['todayPointIncome'])/100))
    msg+=('> 累计总积分为 **%s** 分,对应金钱 **%.2f** 元 \n\n' %(dic['total_all_point'],float(dic['total_all_point'])/100))
    dic=get_jd_total_avail_point(wskey)
    msg+=('> 目前可用积分为 **%s** 分,对应金钱 **%.2f** 元' %(dic['totalAvailPoint'],float(dic['totalAvailPoint'])/100))

    # token=""
    # secret=""
    # data = {
    #     "msgtype": "markdown",
    #     "markdown": {
    #         "title":"京东云路由宝日报",
    #         "text": msg
    #         },
    # }
    # sendinfo_ding(token,secret,data)
    
    # 更改server酱发送
    server_send_wechat('京东路由宝日报',msg)

#Server酱发送微信
def server_send_wechat(text,desp=''):
    # Server酱 Key
    key=''
    url=('https://sc.ftqq.com/%s.send' %key)
    params={
        'text':text,
        'desp':desp
    }
    requests.get(url,params)

# 更改为配置文件获取 todo
wskey=''
while True:
    now = datetime.now()
    print("任务执行的时间为:"+datetime.strftime(now,"%Y-%m-%d:%H:%M:%S"))
    if now.hour==8 and now.minute==0:
        send_jd_router(wskey)
    time.sleep(60)

知识点扩展:Python编程之微信推送模板消息功能示例

本文实例讲述了Python微信推送模板消息功能。分享给大家供大家参考,具体如下:

具体代码如下:

#!/usr/bin/env python

#-*- coding: utf-8 -*-

import httplib

import json

import MySQLdb

#从数据库中获取access_token

access_token=""

try:

conn=MySQLdb.connect(host='192.168.1.1',user='root',passwd='root',db='db_weixin',port=3306)

cur=conn.cursor()

cur.execute('select access_token from weixin_public')

result=cur.fetchone()

#print result

#print result[0]

access_token=result[0]

cur.close()

conn.close()

except MySQLdb.Error,e:

print "Mysql Error %d: %s" % (e.args[0], e.args[1])

#根据接口推送消息

if not access_token is None:

conn = httplib.HTTPConnection("api.weixin.qq.com:80")#微信接口链接

headers = {"Content-type":"application/json"} #application/x-www-form-urlencoded

params = ({'touser' : "oEGZ4johnKOtayJbnEVeuaZr6zQ0",#用户openid

'template_id' : 'AtFuydv8k_15UGZuFntaBzJRCsHCkjNm1dcWD3A-11Y',#模板消息ID

'url' : 'https://www.jb51.net',#跳转链接

"topcolor" : "#667F00",#颜色

"data" : {#模板内容

"first" : {"value" : "尊敬的710.so : 您的网站https://www.jb51.net (192.168.1.1) 有异常访问", "color" : "#173177"},

"keyword1" : {"value" : "访问时间 2015-04-05 15:30:59 访问IP 192.168.1.2", "color" : "#173177"},

"keyword2" : {"value" : "访问链接 https://www.jb51.net", "color" : "#173177"},

"remark" : {"value" : "访问频率 10/s", "color" : "#173177"}

}

}

)

conn.request("POST", "/cgi-bin/message/template/send?access_token="+access_token, json.JSONEncoder().encode(params), headers)#推送消息请求

response = conn.getresponse()

data = response.read()#推送返回数据

if response.status == 200:

print 'success'

print data

else:

print 'fail'

conn.close()

希望本文所述对大家Python程序设计有所帮助。

以上就是Python 京东云无线宝消息推送的详细内容,更多关于Python 京东云无线宝推送的资料请关注脚本之家其它相关文章!

相关文章

  • Python中切片操作的示例详解

    Python中切片操作的示例详解

    在刚学python时候,我们都知道字符串(String)、列表(list)和元组(tuple)序列化数据类型支持切片操作。本文我们将对熟悉的切片操作进行系统学习,感兴趣的可以了解一下
    2022-11-11
  • 用python自动生成日历

    用python自动生成日历

    这篇文章主要介绍了如何用python自动生成日历,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
    2021-04-04
  • Python计算当前日期是一年中的第几天的方法详解

    Python计算当前日期是一年中的第几天的方法详解

    在Python中,计算当前日期是一年中的第几天可以通过内置的datetime模块来实现,本文将详细介绍如何使用Python编写代码来完成这个任务,需要的可以参考下
    2023-12-12
  • Python3利用scapy局域网实现自动多线程arp扫描功能

    Python3利用scapy局域网实现自动多线程arp扫描功能

    这篇文章主要介绍了Python3利用scapy局域网实现自动多线程arp扫描功能,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • Python批量将csv文件编码方式转换为UTF-8的实战记录

    Python批量将csv文件编码方式转换为UTF-8的实战记录

    近日在处理数据的时候发现有的文件为csv文件,Xiam 这篇文章主要给大家介绍了关于利用Python批量将csv文件编码方式转换为UTF-8的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2022-07-07
  • pytorch 如何使用amp进行混合精度训练

    pytorch 如何使用amp进行混合精度训练

    这篇文章主要介绍了pytorch 使用amp进行混合精度训练的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-05-05
  • python输出带有颜色字体的三种方法

    python输出带有颜色字体的三种方法

    在使用python运维与开发的过程中,经常需要打印显示各种信息,海量的信息堆砌在控制台中,就会导致各种信息都显示在一起,降低了重要信息的可读性,这时候如果能给重要的信息加上差异的字体颜色,那么就会更加显眼,所以本文给大家介绍了python输出带有颜色文字的三种方法
    2024-05-05
  • 解读卷积神经网络的人脸识别

    解读卷积神经网络的人脸识别

    这篇文章主要介绍了解读卷积神经网络的人脸识别问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • python 基于Appium控制多设备并行执行

    python 基于Appium控制多设备并行执行

    这篇文章主要介绍了python 如何基于Appium控制多设备并行执行,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
    2021-03-03
  • python实现txt文件格式转换为arff格式

    python实现txt文件格式转换为arff格式

    这篇文章主要为大家详细介绍了python实现txt文件格式转换为arff格式的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-05-05

最新评论