[Python] 纯文本查看 复制代码
import re
import base64
import hashlib
import requests
import json
import hmac
from flask import request
from flask import Flask
import mi # 小米运动刷步py文件
app = Flask(__name__)
'''
@app.route('/home')
def index():
return '<h1>Hello World</h1>'
验证服务是否开启,默认为get
'''
@app.route('/home', methods=['POST'])
def get_data():
# 第一步验证:是否是post请求
if request.method == "POST":
# 签名验证 获取headers中的Timestamp和Sign
timestamp = request.headers.get('Timestamp')
sign = request.headers.get('Sign')
# 第二步验证:签名是否有效
if check_sig(timestamp) == sign:
text_info = json.loads(str(request.data, 'utf-8'))
handle_info(text_info)
else:
print('签名验证失败')
else:
print('收到get请求')
# get_data()必须要有返回
return request.method
# 钉钉sign计算
def check_sig(timestamp):
app_secret = '机器人的[color=rgba(17, 31, 44, 0.4)][font=PingFangSC-Regular, PingFangSC-Medium, "][size=12px]AppSecret[/size][/font][/color]'
app_secret_enc = app_secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, app_secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(app_secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = base64.b64encode(hmac_code).decode('utf-8')
return sign
# mod用于记录当前对话模式
mod = 0
def handle_info(req_data):
# 声明mod是全局变量
global mod
# 解析用户发送消息 通讯webhook_url 用户名称
text_info = req_data['text']['content'].strip()
webhook_url = req_data['sessionWebhook']
senderNick = req_data['senderNick'] + ' 发送:{}'.format(text_info)
# 记录发送人与发送的消息
print(senderNick)
# if判断用户消息触发的关键词,然后返回对应内容
if mod == 0:
if len(text_info) >= 10: # 判断消息长度
text = '我还不理解你的意思,请参照说明回复:\n---------\n刷步\n小爱同学\n成语接龙\n看小姐姐\n地名+天气\n回复前需@我哦'
send_md_msg(text, webhook_url)
elif text_info[-2:] == '天气': # 判断倒数两个字
if len(text_info) <= 2: # 长度小于2未提供地区,默认地区北京,API默认地区
text = weather(text_info[:-2]) + '\n---------\n你没有指定地名哦默认显示北京,发送格式:地名+天气'
send_md_msg(text, webhook_url)
else:
text = weather(text_info[:-2])
send_md_msg(text, webhook_url)
elif text_info[-3:] == '小姐姐':
text = mm()
send_md_msg(text, webhook_url)
elif text_info[-4:] == '小爱同学':
mod = 1 # 设置模式,以便于后续消息直接到指定模式下
text = ai(text_info)
send_md_msg(text, webhook_url)
elif text_info[-4:] == '成语接龙':
# mod = 1
text = '还在研究哦,请先使用其他功能'
send_md_msg(text, webhook_url)
elif text_info[-2:] == '刷步':
mod = 3
text = '请私聊回复小米运动账号#密码#步数。步数不填默认为随机(30000-40000)'
send_md_msg(text, webhook_url)
else:
text = '我还不理解你的意思,请参照说明回复:\n---------\n刷步\n小爱同学\n成语接龙\n看小姐姐\n地名+天气\n回复前需@我哦'
send_md_msg(text, webhook_url)
elif mod == 1:
if '退出' in text_info: # 退出
text = '小爱先退下啦,期待与你下次相遇'
send_md_msg(text, webhook_url)
mod = 0 # 模式恢复
else:
text = ai(text_info)
send_md_msg(text, webhook_url)
elif mod == 3:
try:
# 按#拆分
account = text_info.split('#')
if len(account) != 3: # 长度小于3 则格式异常
text = '输入格式有误,请重新输入\n---------\n小米运动账号#密码#步数。步数不填默认为随机(30000-40000)'
send_md_msg(text, webhook_url)
else:
# 执行外部刷步函数,推送执行结果
text = mi.update(account[0], account[1], account[2])
send_md_msg(text, webhook_url)
mod = 0
except Exception as e:
print(e)
print('回复消息')
# 天气api
def weather(city):
url = 'https://api.vvhan.com/api/weather?city={}'.format(city)
response = requests.request("POST", url)
res = response.json()
weather_today = '城市:{0}\n日期:{1} {2}\n天气:{3} {4} {5} {6} {7}\ntip:{8}'.format(res['city'],
res['info']['date'],
res['info']['week'],
res['info']['type'],
res['info']['high'],
res['info']['low'],
res['info']['fengxiang'],
res['info']['fengli'],
res['info']['tip'])
return weather_today
# 随机小姐姐api
def mm():
url = "http://tucdn.wpon.cn/api-girl/index.php"
payload = {}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0'
}
response = requests.request("GET", url, headers=headers, data=payload)
video = 'http:' + re.findall(r'"(.*?)"', response.text)[0] + '\n---------\n妹妹虽好,身体固然重要噢!'
return video
# 小爱同学api
def ai(words):
url = "http://api.weijieyue.cn/api/xiaoai/api.php?msg={}".format(words)
payload = {}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0'
}
response = requests.request("GET", url, headers=headers, data=payload)
text = response.json()['text'] + '\n---------\n当前已进入持续对话模式,需退出回复【退出】'
return text
# 钉钉消息推送
def send_md_msg(message, webhook_url):
data = {
"msgtype": "text",
"text": {
"content": message
}
}
# 利用requests发送post请求
req = requests.post(webhook_url, json=data)
return req
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)