• lark 发送图片消息


    1. 需求

    2. 实现

    2.1 获取数据源

    1. # -*- coding: utf-8 -*-
    2. import os
    3. import json
    4. import requests
    5. import pandas as pd
    6. from pathlib import PurePath, Path
    7. import plotly.express as px
    8. from requests_toolbelt import MultipartEncoder
    9. def get_data():
    10. dt = ['2023-10-01', '2023-10-02', '2023-10-03', '2023-10-04', '2023-10-05', '2023-10-06', '2023-10-07', '2023-10-08']
    11. y1 = [0.701923, 0.653595, 0.683258, 0.647059, 0.670659, 0.637615, 0.736586, 0.685000]
    12. y2 = [i+0.1 for i in y1]
    13. data = {
    14. 'dt': dt,
    15. 'y1': y1,
    16. 'y2': y2
    17. }
    18. df = pd.DataFrame(data)
    19. return df

    或从hive中读数据

    1. conn = BaseHook.get_connection('hive_cli_default')
    2. conn_hive = connect(host=conn.host, port=conn.port, timeout=3600, auth_mechanism='PLAIN',user=conn.login, password=conn.password)
    3. cursor = conn_hive.cursor()
    4. cursor.execute('SET mapreduce.job.queuename=root.bigdata')
    5. cursor.execute('set mapred.job.name={table}'.format(table=dag_name))
    6. cursor.execute('set hive.vectorized.execution.enabled = false')
    7. sql = '''
    8. select dt, y1, y2
    9. from table;
    10. '''
    11. cursor.execute(sql)
    12. data = cursor.fetchall()
    13. cursor.close()
    14. df = pd.DataFrame(data, columns=['dt'] + ['y1', 'y2'])
    15. return df
    16. # 或
    17. # df = pd.read_sql(sql, con)

    2.2 绘制图片

    1. # 绘制折线图
    2. def draw_img(df):
    3. fig = px.line(df, x='dt', y='y1')
    4. # fig = px.line(df, x='dt', y='y1', markers=True, line_shape='linear')
    5. fig.add_scatter(x=df['dt'], y=df['y1'], name='y1')
    6. fig.add_scatter(x=df['dt'], y=df['y2'], name='y2')
    7. fig.update_traces(textfont_size=8)
    8. fig.layout.yaxis.title = "uv_ratio"
    9. # fig.show()
    10. return fig

    如下:

    2.3 存储图片

    1. def save_img(fig, img_name):
    2. try:
    3. root_dir = os.path.dirname(__file__)
    4. except Exception as e:
    5. print(e)
    6. root_dir = PurePath(Path.cwd())
    7. root_dir = os.path.abspath(root_dir)
    8. print(root_dir)
    9. # 在该项目目录下创建images文件夹
    10. if not os.path.exists("images"):
    11. os.mkdir("images")
    12. img_path = f"{root_dir}/images/{img_name}"
    13. fig.write_image(img_path)
    14. return img_path

    2.4 上传图片并获得图片ID

    1. def upload_image(img_path):
    2. # 1. 获得token
    3. url_1 = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
    4. req_body = {
    5. "app_id": "cli_a23XXXX",
    6. "app_secret": "4w8XXX"
    7. }
    8. data = bytes(json.dumps(req_body), encoding='utf8')
    9. result = requests.request("POST", url_1, headers={'Content-Type': 'application/json; charset=utf-8'}, data=data)
    10. # print(result.content)
    11. token = result.json()["tenant_access_token"]
    12. print(token)
    13. # 2. 上传图片
    14. url = "https://open.feishu.cn/open-apis/im/v1/images"
    15. multi_form = MultipartEncoder({'image_type': 'message', 'image': (open(f'{img_path}', 'rb'))})
    16. headers = {
    17. 'Authorization': f'Bearer {token}', # tenant_access_token
    18. 'Content-Type': multi_form.content_type
    19. }
    20. response = requests.request("POST", url, headers=headers, data=multi_form)
    21. # print(response.headers['X-Tt-Logid']) # for debug or oncall
    22. # print(response.content) # Print Response
    23. img_id = eval(response.content.decode("utf-8"))["data"]["image_key"]
    24. return img_id

    2.5 发送飞书图片消息

    1. def send_markdown(title, token, dt, img_id_1, img_id_2):
    2. http_headers = {'content-type': 'application/json'}
    3. request_url = f'https://open.feishu.cn/open-apis/bot/v2/hook/{token}'
    4. request_data = {
    5. "msg_type": "interactive",
    6. "card": {
    7. "config": {
    8. "wide_screen_mode": True,
    9. "enable_forward": True
    10. },
    11. "header": {
    12. "title": {
    13. "tag": "plain_text",
    14. "content": f"{title}"
    15. },
    16. "template": "blue"
    17. },
    18. "elements": [
    19. {
    20. "tag": "div",
    21. "fields": [
    22. {
    23. "is_short": True,
    24. "text": {
    25. "tag": "lark_md",
    26. "content": f"**日期:** {dt}"
    27. }
    28. },
    29. ]
    30. },
    31. {
    32. "tag": "img",
    33. "img_key": f"{img_id_1}",
    34. "alt": {
    35. "tag": "plain_text",
    36. "content": "图片"
    37. }
    38. },
    39. {
    40. "tag": "img",
    41. "img_key": f"{img_id_2}",
    42. "alt": {
    43. "tag": "plain_text",
    44. "content": "图片"
    45. }
    46. },
    47. ]
    48. }
    49. }
    50. response = requests.post(request_url, json=request_data, headers=http_headers)
    51. print(response)
    52. if response.status_code != 200:
    53. print('飞书消息发送失败,http_code={},http_message={}'.format(response.status_code, response.reason))
    54. else:
    55. print('飞书消息发送成功')

    2.6 调用

    1. 发单张图片

    1. dt = '2023-10-18'
    2. df = get_data()
    3. fig = draw_img(df)
    4. fig.show()
    5. img_path = save_img(fig, img_name='pv_ratio.png')
    6. img_id = upload_image(img_path)
    7. send_markdown('XX服务日报-近14日指标趋势图', token, dt, img_id)

    2. 发多张图片

    1. # ------- 画PV相关指标 ----------
    2. df.columns = ['dt', 'y1_pv', 'y1_uv', 'y2_pv', 'y2_uv']
    3. fig_pv = px.line(df, x='dt', y='y1_pv', markers=True, line_shape='linear')
    4. fig_pv.add_scatter(x=df['dt'], y=df['y1_pv'], name='y1_pv')
    5. fig_pv.add_scatter(x=df['dt'], y=df['y2_pv'], name='y2_pv')
    6. fig_pv.update_traces(textfont_size=8)
    7. fig_pv.layout.yaxis.title = "pv_ratio"
    8. img_path_pv = save_img(fig_pv, img_name='pv_ratio.png')
    9. img_id_pv = upload_image(img_path_pv)
    10. # ------- 画UV相关指标 ----------
    11. fig_uv = px.line(df, x='dt', y='y1_uv', markers=True, line_shape='linear')
    12. fig_uv.add_scatter(x=df['dt'], y=df['y1_uv'], name='y1_uv')
    13. fig_uv.add_scatter(x=df['dt'], y=df['y2_uv'], name='y2_uv')
    14. fig_uv.update_traces(textfont_size=8)
    15. fig_uv.layout.yaxis.title = "uv_ratio"
    16. img_path_uv = save_img(fig_uv, img_name='uv_ratio.png')
    17. img_id_uv = upload_image(img_path_uv)
    18. send_markdown('XX服务日报-近14日指标趋势图', token, dt, img_id_pv, img_id_uv)

  • 相关阅读:
    吴恩达《机器学习》6-4->6-7:代价函数、简化代价函数与梯度下降、高级优化、多元分类:一对多
    Http改为Https后该如何测试
    2022,TO B投资不相信「故事」
    开发工程师必备————【Day05】UDP协议;进程的并发与并行
    23种设计模式之命令模式(Command Pattern)
    SpringBoot项目@Async默认线程池导致OOM问题?
    MyBatis递归查询
    [ 云计算 华为云 ] 解决办法:如何更换华为云云耀云服务器L实例的镜像 | 文末送书
    【c++设计模式之中介者模式】分析及示例
    Web自动化成长之路:selenium中三种等待方式/三大切换操作
  • 原文地址:https://blog.csdn.net/MusicDancing/article/details/133920507