Python发送文本到钉钉群
def get_url(access_token, secret):
t,s = get_sign(secret)
webhook_url = f'https://oapi.dingtalk.com/robot/send?access_token={access_token}×tamp={t}&sign={s}'
return webhook_url
def get_sign(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,sign
def send_text_message(content):
headers = {'Content-Type': 'application/json;charset=utf-8'}
data = {
"msgtype": "text",
"text": {
"content": content
}
}
ACCESS_TOKEN = f'{You_DingGroup_Robot_Webhook}'
SECRET = rf'{You_DingGroup_Robot_Webhook_Secret}'
webhook_url = get_url(ACCESS_TOKEN, SECRET)
response = requests.post(webhook_url, headers=headers, data=json.dumps(data))
result = json.loads(response.text)
if result['errcode'] == 0:
print('消息发送成功')
else:
print('消息发送失败:', result['errmsg'])
if __name__ == '__main__':
send_text_message(message)
You_DingGroup_Robot_Webhook 获取方法
- 钉钉添加群机器人
- 打开钉钉设置
- Webhoot中‘token=’后半部分就是所需要的
You_DingGroup_Robot_Webhook_Secret 获取方法