当前位置:   article > 正文

飞书群聊机器人每日自动推送语录及风景照片python版_python发送飞书文字和图

python发送飞书文字和图

使用场景

最近使用飞书聊天,觉得蛮好用的,刚好这段时间在备考,就想着每天推送一些励志语录 和风景图片什么的,提一下动力

推送机制

飞书群机器人会有对应的webhook,顾名思义就是网络钩子,通过对钩子发送网络请求,即可将消息推送至群内,本文使用的python完成

代码目录

#获取有效token以便进行图片上传
def getttoken():

#在飞书中使用图片需要先将图片上传到飞书中,随后得到Image_Key便可发送图片
def uploadImage():

#因为我想每天都发送新的图片,所以每次都许愿去网络上获取新的照片
def getpic():
main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

代码详解

获取图片

在网上找到了一个图片API,更新序号即可获得不通过的图片,我以日期作为参考,每天获取一张新的照片,代码如下

def getpic():
    current_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    start_date = '2022-2-17'
    end_date = current_time
    start_sec = time.mktime(time.strptime(start_date, '%Y-%m-%d'))
    end_sec = time.mktime(time.strptime(end_date, '%Y-%m-%d'))
    distance_days = int((end_sec - start_sec)/(24*60*60))
    days = 121+distance_days
    days = str(days)
    url = "https://cdn.jsdelivr.net/gh/flipped-1121/APIPIC@master/scenery/"+days+".jpg"
    name = "1.jpg"
    # 保存文件时候注意类型要匹配,如要保存的图片为jpg,则打开的文件的名称必须是jpg格式,否则会产生无效图片
    conn = urllib.request.urlopen(url)
    f = open(name, 'wb')
    f.write(conn.read())
    f.close()
    print('Pic Saved!')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

获取有效token

因为飞书中使用图片需要先将图片上传至飞书中,上传过程中需要获取tenant_access_token(企业自建应用)

图片功能需要机器人获得上传图片的权限,具体步骤点击这里

代码如下

def gettoken():
    url='https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal?app_id=YOUR_ID&app_secret=YOUR_KEY'
    res = requests.get(url=url)
    token=res.json()
    token_text=token['tenant_access_token']
    return token_text
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

上传图片并得到Image_Key

上传图片文档请参考飞书官方文档
代码如下

def uploadImage(token):
    url = "https://open.feishu.cn/open-apis/im/v1/images"
    form = {'image_type': 'message',
            'image': (open('./1.jpg', 'rb'))}  # 需要替换具体的path
    multi_form = MultipartEncoder(form)
    headers = {
        # 获取tenant_access_token, 需要替换为实际的token
        'Authorization': 'Bearer '+token,
    }
    headers['Content-Type'] = multi_form.content_type
    response = requests.request("POST", url, headers=headers, data=multi_form)
    # print(response.headers['X-Tt-Logid'])  # for debug or oncall
    res=bytes.decode(response.content)
    res=eval(res)
    print(res['data']['image_key']) # Print Response
    return res['data']['image_key']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

使用

上传至服务器定时调用.py文件即可

完整代码

import time
import requests
import urllib.request
from requests_toolbelt import MultipartEncoder

# 获取当日token
def gettoken():
    url='https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal?app_id=YOUR_ID&app_secret=YOUR_KEY'
    res = requests.get(url=url)
    token=res.json()
    token_text=token['tenant_access_token']
    return token_text
    # print(token_text)
# 更新当日的风景照以及image_key

def uploadImage(token):
    url = "https://open.feishu.cn/open-apis/im/v1/images"
    form = {'image_type': 'message',
            'image': (open('./1.jpg', 'rb'))}  # 需要替换具体的path
    multi_form = MultipartEncoder(form)
    headers = {
        # 获取tenant_access_token, 需要替换为实际的token
        'Authorization': 'Bearer '+token,
    }
    headers['Content-Type'] = multi_form.content_type
    response = requests.request("POST", url, headers=headers, data=multi_form)
    # print(response.headers['X-Tt-Logid'])  # for debug or oncall
    res=bytes.decode(response.content)
    res=eval(res)
    print(res['data']['image_key']) # Print Response
    return res['data']['image_key']


def getpic():
    current_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    start_date = '2022-2-17'
    end_date = current_time
    start_sec = time.mktime(time.strptime(start_date, '%Y-%m-%d'))
    end_sec = time.mktime(time.strptime(end_date, '%Y-%m-%d'))
    distance_days = int((end_sec - start_sec)/(24*60*60))
    days = 121+distance_days
    days = str(days)
    url = "https://cdn.jsdelivr.net/gh/flipped-1121/APIPIC@master/scenery/"+days+".jpg"
    name = "1.jpg"
    # 保存文件时候注意类型要匹配,如要保存的图片为jpg,则打开的文件的名称必须是jpg格式,否则会产生无效图片
    conn = urllib.request.urlopen(url)
    f = open(name, 'wb')
    f.write(conn.read())
    f.close()
    print('Pic Saved!')

if __name__ == '__main__':
    token=gettoken()
    getpic()
    image_key=uploadImage(token)

    # webhook
    url = "YOUR_WEBHOOK"
    # 每日语录
    url_soup = 'https://apis.juhe.cn/fapig/soup/query?key=YOUR_KEY'
    res_soup = requests.get(url=url_soup)
    soup = res_soup.json()
    soup_text = soup['result']['text']

    # 显示当前时间及距目标天数
    current_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    start_date = current_time
    end_date = '2022-12-25'
    start_sec = time.mktime(time.strptime(start_date, '%Y-%m-%d'))
    end_sec = time.mktime(time.strptime(end_date, '%Y-%m-%d'))
    distance_days = int((end_sec - start_sec)/(24*60*60))
    distance_days = str(distance_days)

    data = {
        "msg_type": "interactive",
        "card": {
            "config": {
                # "wide_screen_mode": true
            },
            "header": {
                "template": "orange",
                "title": {
                    "content": " YOUR_CONTENT",
                    "tag": "plain_text"
                }
            },
            "i18n_elements": {
                "zh_cn": [
                    {
                        "tag": "div",
                        "text": {
                            "content":"YOUR_CONTENT",
                            "tag": "lark_md"
                        }
                    },
                    {
                        "tag": "div",
                        "text": {
                            "content": "\""+soup_text+"\"",
                            "tag": "lark_md"
                        }
                    },
                    {
                        "alt": {
                            "content": "",
                            "tag": "plain_text"
                        },
                        "img_key": image_key,
                        "tag": "img"
                    }
                ]
            }
        }
    }
    # 字符串格式
    res = requests.post(url=url, json=data)
    print(res.text)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/385785?site
推荐阅读
相关标签
  

闽ICP备14008679号