1. 很弱的机器人,只能向群里主动推送消息,没法根据用户的指令进行其他操作
核心代码如下:
import time
import hmac
import hashlib
import base64
import urllib.parse
# 钉钉机器人生成时间戳和签名验证
def get_sign(secret="SEC9f46e354d4834add3b755f72d61f32e09c464115971344442e3497193bb2621e"):
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))
# print(timestamp)
# print(sign)
return timestamp,sign
#核心代码,机器人主动推送一条消息。机器人所在群都能收到
def sendinfo_ding(data):
timestamp,sign = get_sign()
url = 'https://oapi.dingtalk.com/robot/send?access_token=83c158e61b7b366257c7a68c05a7218b7a5dd9f24e62e407b535e3ebe5a20128' #你的机器人webhook地址
url = f"{url}×tamp={timestamp}&sign={sign}"
program = {
"msgtype": "text",
"text": {"content": data},
}
headers = {'Content-Type': 'application/json'}
f = requests.post(url, data=json.dumps(program), headers=headers)
print(f.text)
#测试
if __name__ == '__main__':
sendinfo_ding('机器人测试!')
2.最好的机器人,企业内部机器人。可以主动推送消息,同上面那款机器人一样。更厉害的是支持用户交互。接受用户消息,然后执行对应的操作,需要企业才能添加。
核心代码如下(基于flask做的接口):
utils.py文件:
import hmac
import hashlib
import base64
import time
#获取签名算法
def get_sign(app_secret = 'L52njkY-ekQa4BRp1JKHX_iVHHilOGG8s3_To0X-onjkFVUwyGf2yS2SBbhBscyB',timestamp=str(round(time.time()*1000))):
mtimestamp = str(round(time.time()*1000))
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,mtimestamp
api.py文件:
from flask import Flask, request,render_template_string,Response
from flask_cors import CORS
from utils import get_sign
app = Flask(__name__)
CORS(app, resources=r'/*') #允许跨域
#钉钉机器人测试接口
@app.route("/ding/test/",methods=["GET","POST"])
def ding_test():
headers = request.headers
sign = headers.get("sign")
timestamp = headers.get("timestamp")
if not sign or not timestamp:
return_dict = {'code': '205', 'msg': '错误的请求,缺少sign', 'result': False}
return json.dumps(return_dict, ensure_ascii=False)
mysign,mytime = get_sign(timestamp=timestamp)
if mysign!=sign or int(mytime) - int(timestamp) > 60*60000:
return_dict = {'code': '400', 'msg': '非法的请求', 'result': False}
return json.dumps(return_dict, ensure_ascii=False)
# print(headers)
# print(mysign,mytime)
# print(sign,timestamp)
ret = {
"msgtype": "text",
"text": {
"content": "我就是我, @150XXXXXXXX 是不一样的烟火"
},
"at": {
"atMobiles": [
# "13183893293"
],
"isAtAll": False
}
}
data = request.get_data().decode("utf-8")
data_dict = json.loads(data)
content = data_dict['text']['content']
senderNick = data_dict["senderNick"]
try:
ret['text']['content'] = f"To:{senderNick}\n{eval(content)}"
except Exception as e:
ret['text']['content'] = f"你的输入有误:{content}\n{e}"
return_dict = ret
return json.dumps(return_dict, ensure_ascii=False)
if __name__ == "__main__":
app.run(host='0.0.0.0',port=8000)