官网:微信对话开放平台
搭建机器人基本大家都会自己弄自己的API接口,所以一定需要公网IP才能访问,想当然就用腾讯云函数咯,脚本自己写。
这里如要给大家讲些避雷的注意事项:
1.基于微信对话开放平台的机器人调用这个接口,不同于直接请求,你的Body请求体被包装起来了,所以要设立两套处理,既方便机器人调用,也方便自己用其他方式调用
2.API返回信息必须包装在data_list,并且对应的其他json数据要以列表[]封装,必须要转变格式,要不然容易出现很多///符号,虽然本地能用,但机器人识别不了
没处理好就是上面这个样子,一直机器人API返回报错
下面代码你们学习重要部分就好了,一个手机号和验证码的识别API接口样例
def apiReply(reply, code=200,encoding='utf-8'):
print(type(reply))
reply = json.dumps({'data_list':[eval(json.dumps(reply,ensure_ascii=False,separators=(',',':')))]},ensure_ascii=False,separators=(',',':'))
print(type(reply))
return {
"isBase64Encoded": False,
"statusCode": code,
"headers": {'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*"},
"body": json.dumps(json.loads(reply))
}
def main_handler(event, context):
print("="*30)
print(event)
print("="*30)
try:
body = event.get("body")
print(body)
dic = json.loads(body)
if dic.get("phone_number"):
print("微信对话开放平台触发")
phone_number = dic.get("phone_number")
print(phone_number)
verificationcode = dic.get("verificationcode")
print(verificationcode)
else:
print("非微信对话开放平台触发")
from urllib.parse import parse_qs
Data = event.get("body", None)
print(Data)
params = parse_qs(Data)
result = {key: params[key][0] for key in params}
phone_number = result['phone_number']
verificationcode = result['verificationcode']
#后面不重要
sms = YZ(phone_number,verificationcode)
if sms == "手机号验证码验证成功":
jieguo = DL(phone_number,verificationcode)
return apiReply({
'token': jieguo,
'code': '成功'
})
else:
print("验证码验证失败,程序退出!")
return apiReply({
'token': sms,
'code': '验证码验证失败'
})
except Exception as e:
return apiReply({
'token': str(e),
'code': "程序错误"
})