需求,钉钉消息通知不能发到群里,需要发送到个人。
一、钉钉企业后台创建应用
1、进入钉钉管理后台,创建应用
2、记住ID等应用的信息,在后面需要用到
3、设置允许对接的IP,需要公网IP
4、设置权限,通讯录权限全选申请
二、编写代码,通过手机号发送信息
import requests
import tkinter as tk
# 第一步:获取 access_token
def get_access_token(app_key, app_secret):
url = f"https://oapi.dingtalk.com/gettoken?appkey={app_key}&appsecret={app_secret}"
response = requests.get(url)
response_data = response.json()
if response_data['errcode'] == 0:
return response_data['access_token']
else:
print(f"获取 access_token 失败: {response_data['errmsg']}")
return None
# 第二步:通过手机号获取用户ID
def get_userid_by_mobile(access_token, mobile):
url = f"https://oapi.dingtalk.com/topapi/v2/user/getbymobile?access_token={access_token}"
headers = {'Content-Type': 'application/json'}
data = {"mobile": mobile}
response = requests.post(url, json=data, headers=headers)
response_data = response.json()
if response_data['errcode'] == 0:
return response_data['result']['userid']
else:
print(f"获取用户ID失败: {response_data['errmsg']}")
return None
# 第三步:发送钉钉消息
def send_message_to_user():
access_token = get_access_token(app_key, app_secret)
mobile_number = mobile_entry.get() # 从输入框获取手机号
user_id = get_userid_by_mobile(access_token, mobile_number)
if not user_id:
print("用户ID获取失败,无法发送消息。")
return
url = f"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={access_token}"
headers = {'Content-Type': 'application/json'}
data = {
"agent_id": "xxx", # 替换为你的AgentID
"userid_list": user_id,
"msg": {
"msgtype": "markdown",
"markdown": {
"title": "钉钉通知",
"text": "# 这是标题\n" +
"这是内容,点击[这里](http://xxxx)访问链接。\n" +
"![图片](http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024)"
}
}
}
response = requests.post(url, json=data, headers=headers)
result = response.json()
if result['errcode'] == 0:
print("消息发送成功")
else:
print(f"消息发送失败: {result['errmsg']}")
if __name__ == "__main__":
app_key = "xxxx" # 替换为你的AppKey
app_secret = "xxxxx" # 替换为你的AppSecret
# 创建主窗口
root = tk.Tk()
root.title("发送钉钉消息")
root.geometry("400x200")
tk.Label(root, text="手机号:").grid(row=0, column=0, padx=10, pady=10)
mobile_entry = tk.Entry(root)
mobile_entry.grid(row=0, column=1, padx=10, pady=10)
login_button = tk.Button(root, text="发送", command=send_message_to_user)
login_button.grid(row=3, columnspan=2, pady=10)
root.mainloop()