python对接飞书机器人

如何用python通过飞书机器人给群里发送图片

def setup_logger(log_name):
    """打印和记录日志文件"""
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

    # 创建一个StreamHandler将日志输出到控制台
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.INFO)
    stream_handler.setFormatter(formatter)

    # 创建一个FileHandler将日志写入文件
    file_handler = logging.FileHandler(log_name)
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)

    logger.addHandler(stream_handler)
    logger.addHandler(file_handler)

    return logger

# 创建日志
feishu_logger = setup_logger("robot_feishu.log")


def get_token():
    """获取飞书上传图片 tenant_access_token """
    url_token = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
    # 替换成自己的 
    data = {"app_id": "", "app_secret": ""}
    response = requests.post(url_token, data=data)
    token = json.loads(response.content)["tenant_access_token"]
    return token

def send_image(image_key, robot_url):
    """发送图片至飞书群"""
    dict_image = {
        "msg_type": "image",
        "content": {
            "image_key": image_key
        }
    }
    image_res = requests.post(robot_url, data=json.dumps(dict_image))
    if image_res.status_code == 200:
        try:
            content = json.loads(image_res.content)
            logging.info(f"content====={content}")
        except Exception as e:
            logging.error(repr(e))
        # if content.get("code") == 11232:
        #     logging.info(f"限流再次发送{image_key}")
        #     send_image(dict_image, robot_url)
        logging.info(f"成功发送图片至飞书:{image_res.content}")

def upload_image(image, robot_url):
    """上传图片至飞书服务器 并发送至对应的群"""
    url = "https://open.feishu.cn/open-apis/im/v1/images"
    form = {'image_type': 'message',
            'image': image}  # 需要替换具体的path
    multi_form = MultipartEncoder(form)
    tenant_access_token = get_token()
    headers = {'Authorization': 'Bearer {}'.format(tenant_access_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
    # print(response.content)  # Print Response
    # print(json.loads(response.content)["data"]["image_key"])
    image_key = json.loads(response.content)["data"]["image_key"]
    send_image(image_key, robot_url)

def wait_element(driver, job_name):
    st = time.time()
    wait = WebDriverWait(driver, 50)
    max_retries = 2  # 最多重试次数
    retry_count = 0
    while retry_count < max_retries:
        try:
            element = wait.until(EC.presence_of_element_located((By.ID, "dom-done")))
            if element is not None:
                feishu_logger.info(f"{job_name}===获取到element元素")
                break  # 元素出现,跳出循环
            continue
        except Exception as e:
            retry_count += 1
            feishu_logger.warning(f"{job_name}===Element not found. Retrying... ({retry_count}/{max_retries})")
            driver.refresh()  # 刷新页面
    et = time.time()
    diff_time = et - st
    feishu_logger.info(f"{job_name}===页面加载完成耗时:{diff_time}")


def iphone_hour_one_func(dashboard_url, robot_url, job_name):
    """1小时截1张图
    dashboard_url: 看板url
    robot_url: 机器人url
    """
    max_retries = 2  # 最多重试次数
    driver = None
    screenshot_first = None
    for retry_count in range(max_retries):
        try:
            mobile_emulation = {"deviceName": "iPhone 6 Plus"}
            chrome_options = webdriver.ChromeOptions()
            chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
            chrome_options.add_argument('--headless')
            feishu_logger.info("已经进入无头浏览器模式,正在进行截图")
            driver = webdriver.Chrome(options=chrome_options, executable_path=ChromeDriverManager().install())
            driver.set_window_size(414, 896)  # 设置宽度为414,高度为896
            # 打开网页
            driver.get(dashboard_url)
            # 等待页面加载完成
            wait_element(driver, job_name)
            time.sleep(1)
            # 获取网页截图
            screenshot_first = driver.get_screenshot_as_png()
            break
        except Exception as e:
            feishu_logger.error(repr(e))
            feishu_logger.error("可能出现网络波动,程序休息五秒再运行")
            time.sleep(5)
            if driver:
                driver.quit()
    # 关闭浏览器
    if driver:
        driver.quit()
    upload_image(screenshot_first, robot_url)

def pool_func():
    """创建定时任务线程池"""
    # job_defaults = {
    #     'coalesce': True,
    #     'max_instances': 1,
    #     'misfire_grace_time': 600000  # 600秒的任务超时容错
    # }
    executors = {
        'default': ThreadPoolExecutor(max_workers=20)
    }
    scheduler = BlockingScheduler(executors=executors, misfire_grace_time=300)
    return scheduler

你可能感兴趣的:(python,飞书,机器人)