MCPcopy
hub / github.com/LLOneBot/LuckyLilliaBot / callWs

Method callWs

test/onebot11-api-test/core/ApiClient.ts:324–366  ·  view source on GitHub ↗

* WebSocket 方式调用接口 * @param action 接口名称 * @param params 接口参数 * @returns API 响应 * @throws {NetworkError} 网络请求失败 * @throws {TimeoutError} 请求超时

(action: ActionName, params: any = {})

Source from the content-addressed store, hash-verified

322 * @throws {TimeoutError} 请求超时
323 */
324 async callWs(action: ActionName, params: any = {}): Promise<ApiResponse> {
325 // 确保 WebSocket 已连接
326 await this.connectWs();
327
328 if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
329 throw new NetworkError('WebSocket is not connected');
330 }
331
332 // 生成唯一的 echo 标识
333 const echo = `${action}_${Date.now()}_${Math.random().toString(36).substring(7)}`;
334
335 // 创建请求对象
336 const request: WsRequest = {
337 action,
338 params,
339 echo,
340 };
341
342 // 发送请求并等待响应
343 return new Promise((resolve, reject) => {
344 // 设置超时
345 const timeout = setTimeout(() => {
346 this.pendingRequests.delete(echo);
347 reject(new TimeoutError(`WebSocket request timeout: ${action}`, 30000));
348 }, 30000);
349
350 // 保存待处理的请求
351 this.pendingRequests.set(echo, {
352 resolve,
353 reject,
354 timeout,
355 });
356
357 // 发送请求
358 try {
359 this.ws!.send(JSON.stringify(request));
360 } catch (error) {
361 clearTimeout(timeout);
362 this.pendingRequests.delete(echo);
363 reject(new NetworkError(`Failed to send WebSocket request: ${action}`, error as Error));
364 }
365 });
366 }
367
368 /**
369 * 统一调用接口(根据配置的协议自动选择)

Callers 1

callMethod · 0.95

Calls 4

connectWsMethod · 0.95
toStringMethod · 0.80
sendMethod · 0.80
setMethod · 0.45

Tested by

no test coverage detected