代码
import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parsedef 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_urldef 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,signdef send_text_message(content):headers = {'Content-Type': 'application/json;charset=utf-8'}data = {"msgtype": "text","text": {"content": content}}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__':content = 'lol'send_text_message(content)
注意:这只是个单向推送的机器人,只能用来向群里推送(定时)消息,不能回复。
参考文档
- 自定义机器人安全设置