coze部分接口

This commit is contained in:
Ghost
2025-04-02 10:19:03 +08:00
parent a42bf9e6e6
commit a60dc8d181
12 changed files with 504 additions and 24 deletions

View File

@@ -16,4 +16,15 @@ wechat_url = https://s2.siyuguanli.com:9991/
guid = 5E2C38F5A275450D935F3ECEC076124E
deviceSocketHost = s2.siyuguanli.com:9992
username = kr_xf2
password = kr123456
password = kr123456
[ai]
api_url = https://api.coze.cn
token = pat_C6CknUKceaFJ6xMspz2E4XWIwDsdc4gzDVU4gUCJYM88BC1BhlCHszCEG072q6Er
space_id = 7487098730056515619
bot_id = 7488186374479347731
appid = 1110200424021
client_id = 54663853844532858749326854949287.app.coze
client_secret = wCnZb5d7gfFRLZ5hnijW4aqnxNrTPStQPrO3ZUgNIDUSWI3Q

View File

@@ -47,7 +47,8 @@ class WechatController extends BaseController
'groupId' => $item['groupId'],
'memo' => $item['memo'],
'wechatVersion' => $item['wechatVersion'],
'labels' => $item['labels']
'labels' => !empty($item['labels']) ? json_encode($item['labels']) : json_encode([]),
'updateTime' => time()
];
$account = WechatAccountModel::where('id', $item['id'])->find();
@@ -58,12 +59,16 @@ class WechatController extends BaseController
}
}
public function getlist()
public function getlist($pageIndex = '',$pageSize = '',$authorization = '',$isJob = false)
{
// 获取授权token
$authorization = trim($this->request->header('authorization', ''));
$authorization = !empty($authorization) ? $authorization : trim($this->request->header('authorization', ''));
if (empty($authorization)) {
return errorJson('缺少授权信息');
if($isJob){
return json_encode(['code'=>500,'msg'=>'缺少授权信息']);
}else{
return errorJson('缺少授权信息');
}
}
try {
@@ -76,8 +81,8 @@ class WechatController extends BaseController
'hasDevice' => $this->request->param('hasDevice', ''),
'deviceGroupId' => $this->request->param('deviceGroupId', ''),
'containSubDepartment' => $this->request->param('containSubDepartment', 'false'),
'pageIndex' => $this->request->param('pageIndex', 0),
'pageSize' => $this->request->param('pageSize', 10)
'pageIndex' => !empty($pageIndex) ? $pageIndex : $this->request->param('pageIndex', 0),
'pageSize' => !empty($pageSize) ? $pageSize : $this->request->param('pageSize', 10)
];
// 设置请求头
@@ -94,10 +99,17 @@ class WechatController extends BaseController
$this->saveWechatAccount($item);
}
}
return successJson($response);
if($isJob){
return json_encode(['code'=>200,'msg'=>'获取微信账号列表成功','data'=>$response]);
}else{
return successJson($response);
}
} catch (\Exception $e) {
return errorJson('获取微信账号列表失败:' . $e->getMessage());
if($isJob){
return json_encode(['code'=>500,'msg'=>'获取微信账号列表失败:' . $e->getMessage()]);
}else{
return errorJson('获取微信账号列表失败:' . $e->getMessage());
}
}
}
}

View File

@@ -0,0 +1,16 @@
<?php
use think\facade\Route;
// 定义RESTful风格的API路由
Route::group('v1/cozeai', function () {
// 工作区管理
Route::get('workspaceList', 'cozeai/WorkspaceController/list');
Route::get('botsList', 'cozeai/WorkspaceController/getBotsList');
// 会话管理
Route::group('conversation', function () {
Route::get('list', 'cozeai/ConversationController/list');
Route::post('create', 'cozeai/ConversationController/create');
});
})->middleware(['jwt']);

View File

@@ -0,0 +1,74 @@
<?php
namespace app\cozeai\controller;
use think\Controller;
use think\facade\Config;
use think\facade\Env;
/**
* Coze AI 基础控制器
*/
class BaseController extends Controller
{
protected $apiUrl;
protected $accessToken;
protected $headers;
public function __construct()
{
parent::__construct();
// 从环境变量获取配置
$this->apiUrl = Env::get('ai.api_url');
$this->accessToken = Env::get('ai.token');
// 设置请求头
$this->headers = [
'Authorization:Bearer '. $this->accessToken,
'Content-Type:application/json'
];
}
/**
* 发送GET请求
* @param string $url 请求地址
* @param array $params 请求参数
* @return array
*/
protected function get($url, $params = [])
{
try {
$client = new \GuzzleHttp\Client();
$response = $client->get($this->apiUrl . $url, [
'headers' => $this->headers,
'query' => $params
]);
return json_decode($response->getBody()->getContents(), true);
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
/**
* 发送POST请求
* @param string $url 请求地址
* @param array $data 请求数据
* @return array
*/
protected function post($url, $data = [])
{
try {
$client = new \GuzzleHttp\Client();
$response = $client->post($this->apiUrl . $url, [
'headers' => $this->headers,
'json' => $data
]);
return json_decode($response->getBody()->getContents(), true);
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
}

View File

@@ -0,0 +1,177 @@
<?php
namespace app\cozeai\controller;
use app\cozeai\model\Conversation as ConversationModel;
/**
* Coze AI 对话控制器
*/
class ConversationController extends BaseController
{
/**
* 获取会话列表
*/
public function list()
{
try {
$bot_id = input('bot_id','');
if(empty($bot_id)){
return errorJson('智能体ID不能为空');
}
$page = input('page',1);
$limit = input('limit',20);
$params = [
'bot_id' => $bot_id,
'page_num' => $page,
'page_size' => $limit,
'sort_order' => 'desc'
];
$result = requestCurl($this->apiUrl . "/v1/conversations", $params, 'GET', $this->headers);
$result = json_decode($result, true);
if ($result['code'] != 0) {
return errorJson($result['msg'], $result['code']);
}
// 处理返回的数据并存入数据库
if (!empty($result['data']['conversations'])) {
foreach ($result['data']['conversations'] as $item) {
// 检查是否已存在
$exists = ConversationModel::where('conversation_id', $item['id'])->find();
if (!$exists) {
// 不存在则插入
ConversationModel::create([
'conversation_id' => $item['id'],
'bot_id' => $bot_id,
'created_at' => $item['created_at'],
'meta_data' => json_encode($item['meta_data'] ?? []),
'create_time' => time(),
'update_time' => time()
]);
} else {
// 存在则更新
$exists->save([
'meta_data' => json_encode($item['meta_data'] ?? []),
'update_time' => time()
]);
}
}
}
return successJson($result['data'], '创建成功');
} catch (\Exception $e) {
return errorJson('获取对话列表失败:' . $e->getMessage());
}
}
/**
* 创建对话
*/
public function create()
{
try {
$bot_id = input('bot_id','');
$userInfo = request()->userInfo;
$uid = $userInfo['id'];
$companyId = $userInfo['companyId'];
if(empty($bot_id)){
return errorJson('智能体ID不能为空');
}
$meta_data = [
'uid' => $uid,
'companyId' => $companyId,
];
$messages = [
'role' => 'assistant',
'content' => '欢迎使用美业AI助手我可以帮您管理客户关系、自动回复消息、创建朋友圈内容自动点赞开发客户。请问有什么可以帮你的',
'type' => 'answer',
'content_type' => 'text',
];
$params = [
'bot_id' => $bot_id,
'meta_data' => json_encode($meta_data),
'messages' => json_encode($messages),
];
$result = requestCurl($this->apiUrl . '/v1/conversation/create', $params, 'POST', $this->headers);
$result = json_decode($result, true);
if ($result['code'] != 0) {
return errorJson($result['msg'], $result['code']);
}
return successJson($result['data'], '创建成功');
} catch (\Exception $e) {
return errorJson('创建对话失败:' . $e->getMessage());
}
}
/**
* 获取对话详情
*/
public function detail()
{
try {
$conversationId = $this->request->param('conversationId');
if (empty($conversationId)) {
return errorJson('对话ID不能为空');
}
$result = requestCurl($this->apiUrl . "/v1/conversations/{$conversationId}", [], 'GET', $this->headers);
$result = json_decode($result, true);
if ($result['code'] != 0) {
return errorJson($result['msg'], $result['code']);
}
return successJson($result['data'], '获取成功');
} catch (\Exception $e) {
return errorJson('获取对话详情失败:' . $e->getMessage());
}
}
/**
* 删除对话
*/
public function delete()
{
try {
$conversationId = $this->request->param('conversationId');
if (empty($conversationId)) {
return errorJson('对话ID不能为空');
}
$result = requestCurl($this->apiUrl . "/v1/conversations/{$conversationId}/delete", [], 'POST', $this->headers);
$result = json_decode($result, true);
if ($result['code'] != 0) {
return errorJson($result['msg'], $result['code']);
}
return successJson($result['data'], '删除成功');
} catch (\Exception $e) {
return errorJson('删除对话失败:' . $e->getMessage());
}
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace app\cozeai\controller;
/**
* Coze AI 工作区控制器
*/
class WorkspaceController extends BaseController
{
/**
* 获取工作区列表
*/
public function list()
{
try {
$page = input('page',1);
$limit = input('limit',20);
$params = [
'page_num' => $page,
'page_size' => $limit
];
$result =requestCurl($this->apiUrl . '/v1/workspaces', $params, 'GET', $this->headers);
$result = json_decode($result, true);
if ($result['code'] != 0) {
return errorJson($result['msg'],$result['code']);
}
return successJson($result['data'], '获取成功');
} catch (\Exception $e) {
return errorJson('获取工作区列表失败:' . $e->getMessage());
}
}
/**
* 获取智能体列表
*/
public function getBotsList()
{
try {
$space_id = input('space_id','');
if(empty($space_id)){
return errorJson('Space ID不能为空');
}
$page = input('page',1);
$limit = input('limit',20);
$params = [
'space_id' => $space_id,
'page_index' => $page,
'page_size' => $limit
];
$result = requestCurl($this->apiUrl . '/v1/space/published_bots_list', $params, 'GET', $this->headers);
$result = json_decode($result, true);
if ($result['code'] != 0) {
return errorJson($result['msg'],$result['code']);
}
return successJson($result['data'], '获取成功');
} catch (\Exception $e) {
return errorJson('获取智能体列表失败:'.$e->getMessage());
}
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace app\cozeai\model;
use think\Model;
/**
* Coze AI 对话模型
*/
class Conversation extends Model
{
// 设置表名
protected $name = 'coze_conversation';
// 设置主键
protected $pk = 'id';
// 设置字段
protected $schema = [
'id' => 'int',
'conversation_id' => 'string',
'workspace_id' => 'string',
'bot_id' => 'string',
'title' => 'string',
'create_time' => 'datetime',
'update_time' => 'datetime'
];
// 自动写入时间戳
protected $autoWriteTimestamp = true;
/**
* 根据对话ID获取对话信息
*/
public function getByConversationId($conversationId)
{
return $this->where('conversation_id', $conversationId)->find();
}
/**
* 保存对话信息
*/
public function saveConversation($data)
{
$conversation = $this->getByConversationId($data['conversation_id']);
if ($conversation) {
return $this->where('conversation_id', $data['conversation_id'])->update($data);
} else {
return $this->save($data);
}
}
/**
* 删除对话
*/
public function deleteConversation($conversationId)
{
return $this->where('conversation_id', $conversationId)->delete();
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace app\cozeai\model;
use think\Model;
/**
* Coze AI 工作区模型
*/
class Workspace extends Model
{
// 设置当前模型对应的完整数据表名称
protected $name = 'coze_workspace';
// 设置主键
protected $pk = 'id';
// 设置字段信息
protected $schema = [
'id' => 'int',
'workspace_id' => 'string',
'name' => 'string',
'description' => 'string',
'create_time' => 'datetime',
'update_time' => 'datetime'
];
// 自动写入时间戳
protected $autoWriteTimestamp = true;
protected $createTime = 'create_time';
protected $updateTime = 'update_time';
/**
* 根据工作区ID获取工作区信息
*/
public function getByWorkspaceId($workspaceId)
{
return $this->where('workspace_id', $workspaceId)->find();
}
/**
* 保存工作区信息
*/
public function saveWorkspace($data)
{
$workspace = $this->getByWorkspaceId($data['workspace_id']);
if ($workspace) {
// 更新
return $this->where('workspace_id', $data['workspace_id'])->update($data);
} else {
// 新增
return $this->save($data);
}
}
/**
* 删除工作区
*/
public function deleteWorkspace($workspaceId)
{
return $this->where('workspace_id', $workspaceId)->delete();
}
}

View File

@@ -81,9 +81,10 @@ class WechatListJob
}
// 调用设备列表获取方法
$result = $wechatController->getlist($pageIndex,$pageSize,$authorization);
$result = $wechatController->getlist($pageIndex,$pageSize,$authorization,true);
$response = json_decode($result,true);
// 判断是否成功
if ($response['code'] == 200) {

View File

@@ -33,7 +33,6 @@ class BaseController extends Api
// 尝试从缓存获取设备信息
$device = Cache::get($cacheKey);
$device = '';
// 如果缓存不存在,则从数据库获取
if (!$device) {
$device = Db::name('device_user')
@@ -61,6 +60,6 @@ class BaseController extends Api
protected function clearDeviceCache()
{
$cacheKey = 'device_info_' . $this->userInfo['id'] . '_' . $this->userInfo['companyId'];
Cache::delete($cacheKey);
Cache::rm($cacheKey);
}
}

View File

@@ -30,16 +30,11 @@ class SystemConfigController extends BaseController
}
// 获取已解析的配置
$config = $this->device['taskConfig'] ?? [];
$config = json_decode($this->device['taskConfig'], true);
// 返回开关状态
return $this->success('获取成功', [
'autoLike' => $config['autoLike'] ?? false,
'momentsSync' => $config['momentsSync'] ?? false,
'autoCustomerDev' => $config['autoCustomerDev'] ?? false,
'groupMessageDeliver' => $config['groupMessageDeliver'] ?? false,
'autoGroup' => $config['autoGroup'] ?? false
]);
return successJson($config);
} catch (\Exception $e) {
Log::error('获取开关状态异常:' . $e->getMessage());
@@ -79,8 +74,9 @@ class SystemConfigController extends BaseController
// 更新指定开关状态
$taskConfig[$switchName] = !$taskConfig[$switchName];
$taskConfig = json_encode($taskConfig);
// 更新数据库
$result = Db::name('device')
->where('id', $deviceId)
@@ -89,14 +85,13 @@ class SystemConfigController extends BaseController
'updateTime' => time()
]);
if ($result === false) {
Log::error("更新设备{$switchName}开关状态失败设备ID{$deviceId}");
return errorJson('更新失败');
}
// 清除缓存
// $this->clearDeviceCache();
$this->clearDeviceCache();
return successJson([], '更新成功');

View File

@@ -23,4 +23,8 @@ include __DIR__ . '/../application/devices/config/route.php';
// 加载Store模块路由配置
include __DIR__ . '/../application/store/config/route.php';
// 加载CozeAI模块路由配置
include __DIR__ . '/../application/cozeai/config/route.php';
return [];