需求:
**在钉钉群发图片,需要以图片的形式展示,如图所示:**
但是目前影刀里面没有符合条件的指令
解决方法:
1、在钉钉开发者后台新建一个自建应用,发版,然后获取里面的appkey和appsecret,根据这两个参数调用API生成access_token,以提供给上传文件的接口试用。获取企业内部应用的access_token
2、调用上传临时素材的API,将本地图片上传,生成media_id。上传媒体文件
3、在内部群随便新建一个自定义的机器人。调用自定义机器人发送钉钉群通知的API,在请求路径里面需要有时间和签名,签名根据自定义机器人中的加签编码生成。请求体里面填markdown的形式,然后将图片的media_id写进去。自定义机器人发送群消息
# 使用提醒:
# 1. xbot包提供软件自动化、数据表格、Excel、日志、AI等功能
# 2. package包提供访问当前应用数据的功能,如获取元素、访问全局变量、获取资源文件等功能
# 3. 当此模块作为流程独立运行时执行main函数
# 4. 可视化流程中可以通过"调用模块"的指令使用此模块import xbot
from xbot import print, sleep
from .import package
from .package import variables as glvdef main(args):passimport requests
import json
import base64
import time
import hmac
import hashlibdef get_temporary_material_access_token(appkey, appsecret):get_access_token_url = "https://oapi.dingtalk.com/gettoken"params = {'appkey': appkey,'appsecret': appsecret}response = requests.get(get_access_token_url, params=params)if response.status_code == 200:data = response.json()if 'access_token' in data:return data['access_token']else:print("获取临时素材access_token失败,响应数据格式错误")return Noneelse:print(f"获取临时素材access_token失败,状态码:{response.status_code}")return Nonedef generate_sign(secret, timestamp):"""生成加签"""string_to_sign = f'{timestamp}\n{secret}'hmac_code = hmac.new(secret.encode("utf-8"), string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()sign = base64.b64encode(hmac_code).decode("utf-8")return signdef send_image_to_dingtalk(appkey,appsecret,webhook_url,secret,image_path):# 获取上传临时素材所需的access_tokenupload_access_token = get_temporary_material_access_token(appkey, appsecret)if upload_access_token is None:print("获取access_token失败,无法继续执行")returntimestamp = str(round(time.time() * 1000))sign = generate_sign(secret, timestamp)try:# 使用获取到的upload_access_token替换为实际的上传临时素材链接upload_media_url = f'https://oapi.dingtalk.com/media/upload?access_token={upload_access_token}&type=image'with open(image_path, 'rb') as f:files = {'media': ('image.jpg', f.read())}upload_response = requests.post(upload_media_url, files=files)if upload_response.status_code == 200:media_response = json.loads(upload_response.text)if 'media_id' in media_response:media_id = media_response['media_id']post_url = '{}×tamp={}&sign={}'.format(webhook_url, timestamp, sign)# 构造加签请求头headers = {'Content-Type': 'application/json'}payload = {"msgtype": "markdown","markdown": {"title": "图片","text": f"![图片]({media_id})"},}send_response = requests.post(post_url, headers=headers, data=json.dumps(payload))if send_response.status_code == 200:print("图片已成功发送至钉钉群聊")else:print(f"发送失败,错误信息:{send_response.text}")else:print("上传图片失败,响应数据格式错误")else:print(f"上传图片失败,状态码:{upload_response.status_code}")except FileNotFoundError:print(f"无法找到指定的图片文件:{image_path}")except Exception as e:print(f"发送过程中出现错误:{str(e)}")
参考文章:
1、钉钉群聊机器人发送本地图片解决方案–不用图床版(附源码)
2、怎么调用钉钉机器人发本地图片到钉钉群中