需求:
想通过飞书,定时发送自定义消息给指定的人员或者所有人员.自定义消息可以是文字,图片或音视频.
解决思路:
在飞书创建一个类似微信公众号一样的群发工具
在这个群发工具后台配置功能,获取相关的秘钥
编写代码, 封装好发送消息的相关函数
设置好消息,调用发送消息函数,完成发消息的需求
准备工作:
拥有飞书管理后台的相关权限(我是超级管理员-全部权限)
会一种开发语言PHP,Java或Python等(我是PHP开发).
详细步骤:
在飞书管理后台创建应用,
飞书管理后台->工作台->应用管理->创建应用(这里会跳转到开放平台)->创建企业自建应用->填写相关信息
在开放平台给新建的应用添加应用能力-机器人
飞书开放平台->应用能力->添加应用能力->按能力添加->机器人
配置权限
应用人员权限,根据需求配置,我这里是所有人
发送消息权限,这里我全选了:1.通讯录 2.消息与群组 批量开通
发布版本
发布版本之后, 管理员会收到消息, 审核通过就创建完成了,接下来就是编写代码了.
记住应用的应用凭证
通过文档:https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message/create,编写相关接口
php的代码如下
<?php
/**
* Created by PhpStorm.
* User: YJQ
* Date: 2022/10/12
* Time: 15:28
*/namespace yh\common\services;use yh\common\constant\ServerDataConst;
use yh\common\utils\Helpers;
use yii\httpclient\Client;
use yii\httpclient\Exception;/**
* 飞书开发文档
* 接口文档:https://open.feishu.cn/document/ukTMukTMukTM/ukDNz4SO0MjL5QzM/auth-v3/auth/tenant_access_token_internal
*
*/
class FeiShuService
{ /** 需要发送消息的用户 */
const MOBILE = [
'+86158723525**',//张**
'+86136702248**',//刘** ]; /**
* 群发消息
* @param string $text
* @return bool
* @throws Exception
* @throws \yii\base\InvalidConfigException
*/
public function sendMsgAll(string $text): bool
{
$userList = $this->getFeiShuUserList(); $tenantAccessToken = $this->getTenantAccessToken();
$token = !empty($tenantAccessToken) ? $tenantAccessToken : (!empty($user_access_token) ? $user_access_token : '');
if (empty($token)) return false; /** 发送消息 sendMsgAll 群发消息 */
if (!empty($userList)) { $user_ids = [];
$open_ids = [];
$department_ids = [];
foreach ($userList as $v) {
if (in_array($v['mobile'], self::MOBILE)) {
$user_ids[] = $v['user_id'];
$open_ids[] = $v['open_id'];
$department_ids[] = $v['department_ids'][0];
}
} if (!empty($department_ids) && is_array($department_ids)) {
$department_ids = array_unique($department_ids);
} $url = 'https://open.feishu.cn/open-apis/message/v4/batch_send/'; $headers = [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json; charset=utf-8',
]; $data = [
'msg_type' => 'text',
'content' => [
'text' => $text,
],
'user_ids' => $user_ids,
//'department_ids' => $department_ids,
//'open_ids' => $open_ids,
]; $res = (new Client())->post($url, $data, $headers)->send(); if (!empty($res->data) && $res->data['code'] === 0) {
return true;
}
} return false;
} /**
* 获取用户列表
*
* @return array|mixed
* @throws Exception
* @throws \yii\base\InvalidConfigException
*/
public function getFeiShuUserList(): array
{
$userList = []; $tenantAccessToken = $this->getTenantAccessToken();
$url = 'https://open.feishu.cn/open-apis/contact/v3/users/find_by_department';
$token = !empty($tenantAccessToken) ? $tenantAccessToken : (!empty($user_access_token) ? $user_access_token : ''); if (empty($token)) return $userList; $headers = [
'Authorization' => 'Bearer ' . $token,
]; $body = [
'user_id_type' => 'user_id',
'department_id' => '0',
'page_size' => 50,
]; $res = (new Client())->get($url, $body, $headers)->send(); if (!empty($res->data) && $res->data['code'] === 0 && !empty($res->data['data'])) {
$userList = $res->data['data']['items'];
} return $userList;
} /**
* 获取tenant_access_token
* @return string
* @throws Exception
* @throws \yii\base\InvalidConfigException
*/
public function getTenantAccessToken(): string
{
$config = \Yii::$app->params['feiShu']; $url = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal';
$headers = [
'Content-Type' => 'application/json; charset=utf-8',
]; $body = [
'app_id' => $config['app_id'],
'app_secret' => $config['app_secret'],
]; /** 获取tenant_access_token */
$tenant_access_token = \Yii::$app->redis->get(ServerDataConst::FEI_SHU_TENANT_ACCESS_TOKEN);
if (empty($tenant_access_token)) {
$res = (new Client())->post($url, $body, $headers)->send(); if (!empty($res->data) && $res->data['code'] === 0) {
$tenant_access_token = $res->data['tenant_access_token'];
/** 有效期为2小时 */
\Yii::$app->redis->set(ServerDataConst::FEI_SHU_TENANT_ACCESS_TOKEN, $tenant_access_token);
\Yii::$app->redis->expire(ServerDataConst::FEI_SHU_TENANT_ACCESS_TOKEN, 3600 * 2 - 10);
}
} return $tenant_access_token;
} /**
* 发送单发消息
* @param string $text
* @return array|false
* @throws Exception
* @throws \yii\base\InvalidConfigException
*/
public function sendMsgOne(string $text): array
{
$userList = $this->getFeiShuUserList();
//var_dump(json_encode($userList,256));die; $tenantAccessToken = $this->getTenantAccessToken();
$token = !empty($tenantAccessToken) ? $tenantAccessToken : (!empty($user_access_token) ? $user_access_token : '');
if (empty($token)) return false; /** 发送消息成功的用户 */
$successUser = []; /** 发送消息 sendMsgOne 单发消息 */
if (!empty($userList)) {
$receive_id_type = 'open_id';
$receive_id_type = 'user_id';
$url = 'https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=' . $receive_id_type; $headers = [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json; charset=utf-8',
]; foreach ($userList as $v) {
if (in_array($v['mobile'], self::MOBILE)) {
$data = [
'receive_id' => $v[$receive_id_type],
'msg_type' => 'text',
'content' => json_encode([
'text' => $text,
], 256),
'uuid' => Helpers::quickRandom(10) . '-' . Helpers::quickRandom(10) . '-' . Helpers::quickRandom(10),
];
$res = (new Client())->post($url, $data, $headers)->send(); if (!empty($res->data) && $res->data['code'] === 0) {
$successUser[] = $v['name']; } else {
//var_dump($res);die;
/** 写入日志 - 使用组件 */
\Yii::$app->logger->_logger(
\Yii::$app->logger::_LL_INFO, //日志类型
basename(__FILE__) . '->' . __FUNCTION__ . '()--第' . __LINE__ . '行--' //文件名 - 函数 - 行数
. '--发送消息失败--$v:' . json_encode($v, 256)
);
}
}
}
} return $successUser;
}
}
使用时调用方法
(new FeiShuService)->sendMsgOne('收到消息请回复~');
以上就是我几天慢慢摸索的过程, 如有疑问或建议请留言,大家共同学习探讨进步
发表评论 取消回复