如何用python通过飞书机器人给群里发送图片
def setup_logger(log_name):
"""打印和记录日志文件"""
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(formatter)
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))
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}
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)
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)
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():
"""创建定时任务线程池"""
executors = {
'default': ThreadPoolExecutor(max_workers=20)
}
scheduler = BlockingScheduler(executors=executors, misfire_grace_time=300)
return scheduler