这篇文章主要介绍如何利用python结合钉钉文档实现钉钉机器人的只能回复功能,所谓的只能回复是指,@机器人并发消息后,机器人会给出答复。
老规矩,直接上抄来的关键代码:
def handle_client(client_socket):
# 获取socket
request_data = client_socket.recv(20000)
post_userid, post_sign, post_timestamp, post_mes = getPost(request_data)
# 回应socket
initKey(post_userid, post_sign, post_timestamp, post_mes)
# 关闭socket
client_socket.close()
def getPost(request_data):
# 格式化socket数据
request_data = str(request_data, encoding="utf8").split('\r\n')
items = []
for item in request_data[1:-2]:
items.append(item.split(':'))
post_useful = dict(items)
post_mes = json.loads(request_data[-1])
post_sign = post_useful.get('sign').strip()
post_timestamp = post_useful.get('timestamp').strip()
post_userid = post_mes.get('senderId').strip()
post_mes = post_mes.get('text').get('content').strip()
return post_userid, post_sign, post_timestamp, post_mes
def initKey(post_userid, post_sign, post_timestamp, post_mes):
# 配置token
whtoken="机器人的webhook token"
# 得到当前时间戳
timestamp = str(round(time.time() * 1000))
# 计算签名
app_secret = '机器人的AppSecret'
app_secret_enc = app_secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(post_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')
if (abs(int(post_timestamp) - int(timestamp)) < 3600000 and post_sign == sign):
webhook = "https://oapi.dingtalk.com/robot/send?access_token={}×tamp={}&sign=".format(whtoken,timestamp,sign)
header = {
"Content-Type": "application/json",
"Charset": "UTF-8"
}
# 发送消息
message_json = json.dumps(selectMes(post_userid, post_mes))
# 返回发送状态
info = requests.post(url=webhook, data=message_json, headers=header)
print(info.text)
else:
print("Warning:Not DingDing's post")
def selectMes(post_userid, post_mes):
if (post_mes == '1'):
send_mes = 'This is 1'
return sendText(post_userid, send_mes)
else:
return sendText(post_userid, 'Not understand')
def sendText(post_userid, send_mes):
# 发送文本形式
message = {
"msgtype": "text",
"text": {
"content": send_mes
},
"at": {
"atDingtalkIds": [post_userid],
"isAtAll": False
}
}
return message
if __name__ == "__main__":
# 启动服务,端口9000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 8080))
server_socket.listen(120)
while True:
client_socket, client_address = server_socket.accept()
print("[%s, %s]用户连接上了" % client_address)
handle_client_process = Process(target=handle_client, args=(client_socket,))
handle_client_process.start()
client_socket.close()
这段代码想要生效,大概需要准备以下几点:
1、在钉钉官方获取机器人的AppSecret
2、获取机器人所在群组的webhook token
3、按照钉钉官方说的方式搞定内网穿透这一块
做完上述操作后即可使用智能机器人了
存在的问题:
钉钉机器人的webhook是固定的,无法实现不同的群组使用不同的机器人,也就是会串群,不够灵活,后续解决后会贴出相关代码。