file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
agent/tools/scheduler/integration.py
Python
""" Integration module for scheduler with AgentBridge """ import os from typing import Optional from config import conf from common.log import logger from common.utils import expand_path from bridge.context import Context, ContextType from bridge.reply import Reply, ReplyType # Global scheduler service instance _scheduler_service = None _task_store = None def init_scheduler(agent_bridge) -> bool: """ Initialize scheduler service Args: agent_bridge: AgentBridge instance Returns: True if initialized successfully """ global _scheduler_service, _task_store try: from agent.tools.scheduler.task_store import TaskStore from agent.tools.scheduler.scheduler_service import SchedulerService # Get workspace from config workspace_root = expand_path(conf().get("agent_workspace", "~/cow")) store_path = os.path.join(workspace_root, "scheduler", "tasks.json") # Create task store _task_store = TaskStore(store_path) logger.debug(f"[Scheduler] Task store initialized: {store_path}") # Create execute callback def execute_task_callback(task: dict): """Callback to execute a scheduled task""" try: action = task.get("action", {}) action_type = action.get("type") if action_type == "agent_task": _execute_agent_task(task, agent_bridge) elif action_type == "send_message": # Legacy support for old tasks _execute_send_message(task, agent_bridge) elif action_type == "tool_call": # Legacy support for old tasks _execute_tool_call(task, agent_bridge) elif action_type == "skill_call": # Legacy support for old tasks _execute_skill_call(task, agent_bridge) else: logger.warning(f"[Scheduler] Unknown action type: {action_type}") except Exception as e: logger.error(f"[Scheduler] Error executing task {task.get('id')}: {e}") # Create scheduler service _scheduler_service = SchedulerService(_task_store, execute_task_callback) _scheduler_service.start() logger.debug("[Scheduler] Scheduler service initialized and started") return True except Exception as e: logger.error(f"[Scheduler] Failed to initialize scheduler: {e}") return False def get_task_store(): """Get the global task store instance""" return _task_store def get_scheduler_service(): """Get the global scheduler service instance""" return _scheduler_service def _execute_agent_task(task: dict, agent_bridge): """ Execute an agent_task action - let Agent handle the task Args: task: Task dictionary agent_bridge: AgentBridge instance """ try: action = task.get("action", {}) task_description = action.get("task_description") receiver = action.get("receiver") is_group = action.get("is_group", False) channel_type = action.get("channel_type", "unknown") if not task_description: logger.error(f"[Scheduler] Task {task['id']}: No task_description specified") return if not receiver: logger.error(f"[Scheduler] Task {task['id']}: No receiver specified") return # Check for unsupported channels if channel_type == "dingtalk": logger.warning(f"[Scheduler] Task {task['id']}: DingTalk channel does not support scheduled messages (Stream mode limitation). Task will execute but message cannot be sent.") logger.info(f"[Scheduler] Task {task['id']}: Executing agent task '{task_description}'") # Create a unique session_id for this scheduled task to avoid polluting user's conversation # Format: scheduler_<receiver>_<task_id> to ensure isolation scheduler_session_id = f"scheduler_{receiver}_{task['id']}" # Create context for Agent context = Context(ContextType.TEXT, task_description) context["receiver"] = receiver context["isgroup"] = is_group context["session_id"] = scheduler_session_id # Channel-specific setup if channel_type == "web": import uuid request_id = f"scheduler_{task['id']}_{uuid.uuid4().hex[:8]}" context["request_id"] = request_id elif channel_type == "feishu": context["receive_id_type"] = "chat_id" if is_group else "open_id" context["msg"] = None elif channel_type == "dingtalk": # DingTalk requires msg object, set to None for scheduled tasks context["msg"] = None # 如果是单聊,需要传递 sender_staff_id if not is_group: sender_staff_id = action.get("dingtalk_sender_staff_id") if sender_staff_id: context["dingtalk_sender_staff_id"] = sender_staff_id # Use Agent to execute the task # Mark this as a scheduled task execution to prevent recursive task creation context["is_scheduled_task"] = True try: # Don't clear history - scheduler tasks use isolated session_id so they won't pollute user conversations reply = agent_bridge.agent_reply(task_description, context=context, on_event=None, clear_history=False) if reply and reply.content: # Send the reply via channel from channel.channel_factory import create_channel try: channel = create_channel(channel_type) if channel: # For web channel, register request_id if channel_type == "web" and hasattr(channel, 'request_to_session'): request_id = context.get("request_id") if request_id: channel.request_to_session[request_id] = receiver logger.debug(f"[Scheduler] Registered request_id {request_id} -> session {receiver}") # Send the reply channel.send(reply, context) logger.info(f"[Scheduler] Task {task['id']} executed successfully, result sent to {receiver}") else: logger.error(f"[Scheduler] Failed to create channel: {channel_type}") except Exception as e: logger.error(f"[Scheduler] Failed to send result: {e}") else: logger.error(f"[Scheduler] Task {task['id']}: No result from agent execution") except Exception as e: logger.error(f"[Scheduler] Failed to execute task via Agent: {e}") import traceback logger.error(f"[Scheduler] Traceback: {traceback.format_exc()}") except Exception as e: logger.error(f"[Scheduler] Error in _execute_agent_task: {e}") import traceback logger.error(f"[Scheduler] Traceback: {traceback.format_exc()}") def _execute_send_message(task: dict, agent_bridge): """ Execute a send_message action Args: task: Task dictionary agent_bridge: AgentBridge instance """ try: action = task.get("action", {}) content = action.get("content", "") receiver = action.get("receiver") is_group = action.get("is_group", False) channel_type = action.get("channel_type", "unknown") if not receiver: logger.error(f"[Scheduler] Task {task['id']}: No receiver specified") return # Create context for sending message context = Context(ContextType.TEXT, content) context["receiver"] = receiver context["isgroup"] = is_group context["session_id"] = receiver # Channel-specific context setup if channel_type == "web": # Web channel needs request_id import uuid request_id = f"scheduler_{task['id']}_{uuid.uuid4().hex[:8]}" context["request_id"] = request_id logger.debug(f"[Scheduler] Generated request_id for web channel: {request_id}") elif channel_type == "feishu": # Feishu channel: for scheduled tasks, send as new message (no msg_id to reply to) # Use chat_id for groups, open_id for private chats context["receive_id_type"] = "chat_id" if is_group else "open_id" # Keep isgroup as is, but set msg to None (no original message to reply to) # Feishu channel will detect this and send as new message instead of reply context["msg"] = None logger.debug(f"[Scheduler] Feishu: receive_id_type={context['receive_id_type']}, is_group={is_group}, receiver={receiver}") elif channel_type == "dingtalk": # DingTalk channel setup context["msg"] = None # 如果是单聊,需要传递 sender_staff_id if not is_group: sender_staff_id = action.get("dingtalk_sender_staff_id") if sender_staff_id: context["dingtalk_sender_staff_id"] = sender_staff_id logger.debug(f"[Scheduler] DingTalk single chat: sender_staff_id={sender_staff_id}") else: logger.warning(f"[Scheduler] Task {task['id']}: DingTalk single chat message missing sender_staff_id") # Create reply reply = Reply(ReplyType.TEXT, content) # Get channel and send from channel.channel_factory import create_channel try: channel = create_channel(channel_type) if channel: # For web channel, register the request_id to session mapping if channel_type == "web" and hasattr(channel, 'request_to_session'): channel.request_to_session[request_id] = receiver logger.debug(f"[Scheduler] Registered request_id {request_id} -> session {receiver}") channel.send(reply, context) logger.info(f"[Scheduler] Task {task['id']} executed: sent message to {receiver}") else: logger.error(f"[Scheduler] Failed to create channel: {channel_type}") except Exception as e: logger.error(f"[Scheduler] Failed to send message: {e}") import traceback logger.error(f"[Scheduler] Traceback: {traceback.format_exc()}") except Exception as e: logger.error(f"[Scheduler] Error in _execute_send_message: {e}") import traceback logger.error(f"[Scheduler] Traceback: {traceback.format_exc()}") def _execute_tool_call(task: dict, agent_bridge): """ Execute a tool_call action Args: task: Task dictionary agent_bridge: AgentBridge instance """ try: action = task.get("action", {}) # Support both old and new field names tool_name = action.get("call_name") or action.get("tool_name") tool_params = action.get("call_params") or action.get("tool_params", {}) result_prefix = action.get("result_prefix", "") receiver = action.get("receiver") is_group = action.get("is_group", False) channel_type = action.get("channel_type", "unknown") if not tool_name: logger.error(f"[Scheduler] Task {task['id']}: No tool_name specified") return if not receiver: logger.error(f"[Scheduler] Task {task['id']}: No receiver specified") return # Get tool manager and create tool instance from agent.tools.tool_manager import ToolManager tool_manager = ToolManager() tool = tool_manager.create_tool(tool_name) if not tool: logger.error(f"[Scheduler] Task {task['id']}: Tool '{tool_name}' not found") return # Execute tool logger.info(f"[Scheduler] Task {task['id']}: Executing tool '{tool_name}' with params {tool_params}") result = tool.execute(tool_params) # Get result content if hasattr(result, 'result'): content = result.result else: content = str(result) # Add prefix if specified if result_prefix: content = f"{result_prefix}\n\n{content}" # Send result as message context = Context(ContextType.TEXT, content) context["receiver"] = receiver context["isgroup"] = is_group context["session_id"] = receiver # Channel-specific context setup if channel_type == "web": # Web channel needs request_id import uuid request_id = f"scheduler_{task['id']}_{uuid.uuid4().hex[:8]}" context["request_id"] = request_id logger.debug(f"[Scheduler] Generated request_id for web channel: {request_id}") elif channel_type == "feishu": # Feishu channel: for scheduled tasks, send as new message (no msg_id to reply to) context["receive_id_type"] = "chat_id" if is_group else "open_id" context["msg"] = None logger.debug(f"[Scheduler] Feishu: receive_id_type={context['receive_id_type']}, is_group={is_group}, receiver={receiver}") reply = Reply(ReplyType.TEXT, content) # Get channel and send from channel.channel_factory import create_channel try: channel = create_channel(channel_type) if channel: # For web channel, register the request_id to session mapping if channel_type == "web" and hasattr(channel, 'request_to_session'): channel.request_to_session[request_id] = receiver logger.debug(f"[Scheduler] Registered request_id {request_id} -> session {receiver}") channel.send(reply, context) logger.info(f"[Scheduler] Task {task['id']} executed: sent tool result to {receiver}") else: logger.error(f"[Scheduler] Failed to create channel: {channel_type}") except Exception as e: logger.error(f"[Scheduler] Failed to send tool result: {e}") except Exception as e: logger.error(f"[Scheduler] Error in _execute_tool_call: {e}") def _execute_skill_call(task: dict, agent_bridge): """ Execute a skill_call action by asking Agent to run the skill Args: task: Task dictionary agent_bridge: AgentBridge instance """ try: action = task.get("action", {}) # Support both old and new field names skill_name = action.get("call_name") or action.get("skill_name") skill_params = action.get("call_params") or action.get("skill_params", {}) result_prefix = action.get("result_prefix", "") receiver = action.get("receiver") is_group = action.get("isgroup", False) channel_type = action.get("channel_type", "unknown") if not skill_name: logger.error(f"[Scheduler] Task {task['id']}: No skill_name specified") return if not receiver: logger.error(f"[Scheduler] Task {task['id']}: No receiver specified") return logger.info(f"[Scheduler] Task {task['id']}: Executing skill '{skill_name}' with params {skill_params}") # Create a unique session_id for this scheduled task to avoid polluting user's conversation # Format: scheduler_<receiver>_<task_id> to ensure isolation scheduler_session_id = f"scheduler_{receiver}_{task['id']}" # Build a natural language query for the Agent to execute the skill # Format: "Use skill-name to do something with params" param_str = ", ".join([f"{k}={v}" for k, v in skill_params.items()]) query = f"Use {skill_name} skill" if param_str: query += f" with {param_str}" # Create context for Agent context = Context(ContextType.TEXT, query) context["receiver"] = receiver context["isgroup"] = is_group context["session_id"] = scheduler_session_id # Channel-specific setup if channel_type == "web": import uuid request_id = f"scheduler_{task['id']}_{uuid.uuid4().hex[:8]}" context["request_id"] = request_id elif channel_type == "feishu": context["receive_id_type"] = "chat_id" if is_group else "open_id" context["msg"] = None # Use Agent to execute the skill try: # Don't clear history - scheduler tasks use isolated session_id so they won't pollute user conversations reply = agent_bridge.agent_reply(query, context=context, on_event=None, clear_history=False) if reply and reply.content: content = reply.content # Add prefix if specified if result_prefix: content = f"{result_prefix}\n\n{content}" logger.info(f"[Scheduler] Task {task['id']} executed: skill result sent to {receiver}") else: logger.error(f"[Scheduler] Task {task['id']}: No result from skill execution") except Exception as e: logger.error(f"[Scheduler] Failed to execute skill via Agent: {e}") import traceback logger.error(f"[Scheduler] Traceback: {traceback.format_exc()}") except Exception as e: logger.error(f"[Scheduler] Error in _execute_skill_call: {e}") import traceback logger.error(f"[Scheduler] Traceback: {traceback.format_exc()}") def attach_scheduler_to_tool(tool, context: Context = None): """ Attach scheduler components to a SchedulerTool instance Args: tool: SchedulerTool instance context: Current context (optional) """ if _task_store: tool.task_store = _task_store if context: tool.current_context = context # Also set channel_type from config channel_type = conf().get("channel_type", "unknown") if not tool.config: tool.config = {} tool.config["channel_type"] = channel_type
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/scheduler/scheduler_service.py
Python
""" Background scheduler service for executing scheduled tasks """ import time import threading from datetime import datetime, timedelta from typing import Callable, Optional from croniter import croniter from common.log import logger class SchedulerService: """ Background service that executes scheduled tasks """ def __init__(self, task_store, execute_callback: Callable): """ Initialize scheduler service Args: task_store: TaskStore instance execute_callback: Function to call when executing a task """ self.task_store = task_store self.execute_callback = execute_callback self.running = False self.thread = None self._lock = threading.Lock() def start(self): """Start the scheduler service""" with self._lock: if self.running: logger.warning("[Scheduler] Service already running") return self.running = True self.thread = threading.Thread(target=self._run_loop, daemon=True) self.thread.start() logger.debug("[Scheduler] Service started") def stop(self): """Stop the scheduler service""" with self._lock: if not self.running: return self.running = False if self.thread: self.thread.join(timeout=5) logger.info("[Scheduler] Service stopped") def _run_loop(self): """Main scheduler loop""" logger.debug("[Scheduler] Scheduler loop started") while self.running: try: self._check_and_execute_tasks() except Exception as e: logger.error(f"[Scheduler] Error in scheduler loop: {e}") # Sleep for 30 seconds between checks time.sleep(30) def _check_and_execute_tasks(self): """Check for due tasks and execute them""" now = datetime.now() tasks = self.task_store.list_tasks(enabled_only=True) for task in tasks: try: # Check if task is due if self._is_task_due(task, now): logger.info(f"[Scheduler] Executing task: {task['id']} - {task['name']}") self._execute_task(task) # Update next run time next_run = self._calculate_next_run(task, now) if next_run: self.task_store.update_task(task['id'], { "next_run_at": next_run.isoformat(), "last_run_at": now.isoformat() }) else: # One-time task, disable it self.task_store.update_task(task['id'], { "enabled": False, "last_run_at": now.isoformat() }) logger.info(f"[Scheduler] One-time task completed and disabled: {task['id']}") except Exception as e: logger.error(f"[Scheduler] Error processing task {task.get('id')}: {e}") def _is_task_due(self, task: dict, now: datetime) -> bool: """ Check if a task is due to run Args: task: Task dictionary now: Current datetime Returns: True if task should run now """ next_run_str = task.get("next_run_at") if not next_run_str: # Calculate initial next_run_at next_run = self._calculate_next_run(task, now) if next_run: self.task_store.update_task(task['id'], { "next_run_at": next_run.isoformat() }) return False return False try: next_run = datetime.fromisoformat(next_run_str) # Check if task is overdue (e.g., service restart) if next_run < now: time_diff = (now - next_run).total_seconds() # If overdue by more than 5 minutes, skip this run and schedule next if time_diff > 300: # 5 minutes logger.warning(f"[Scheduler] Task {task['id']} is overdue by {int(time_diff)}s, skipping and scheduling next run") # For one-time tasks, disable them schedule = task.get("schedule", {}) if schedule.get("type") == "once": self.task_store.update_task(task['id'], { "enabled": False, "last_run_at": now.isoformat() }) logger.info(f"[Scheduler] One-time task {task['id']} expired, disabled") return False # For recurring tasks, calculate next run from now next_next_run = self._calculate_next_run(task, now) if next_next_run: self.task_store.update_task(task['id'], { "next_run_at": next_next_run.isoformat() }) logger.info(f"[Scheduler] Rescheduled task {task['id']} to {next_next_run}") return False return now >= next_run except: return False def _calculate_next_run(self, task: dict, from_time: datetime) -> Optional[datetime]: """ Calculate next run time for a task Args: task: Task dictionary from_time: Calculate from this time Returns: Next run datetime or None for one-time tasks """ schedule = task.get("schedule", {}) schedule_type = schedule.get("type") if schedule_type == "cron": # Cron expression expression = schedule.get("expression") if not expression: return None try: cron = croniter(expression, from_time) return cron.get_next(datetime) except Exception as e: logger.error(f"[Scheduler] Invalid cron expression '{expression}': {e}") return None elif schedule_type == "interval": # Interval in seconds seconds = schedule.get("seconds", 0) if seconds <= 0: return None return from_time + timedelta(seconds=seconds) elif schedule_type == "once": # One-time task at specific time run_at_str = schedule.get("run_at") if not run_at_str: return None try: run_at = datetime.fromisoformat(run_at_str) # Only return if in the future if run_at > from_time: return run_at except: pass return None return None def _execute_task(self, task: dict): """ Execute a task Args: task: Task dictionary """ try: # Call the execute callback self.execute_callback(task) except Exception as e: logger.error(f"[Scheduler] Error executing task {task['id']}: {e}") # Update task with error self.task_store.update_task(task['id'], { "last_error": str(e), "last_error_at": datetime.now().isoformat() })
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/scheduler/scheduler_tool.py
Python
""" Scheduler tool for creating and managing scheduled tasks """ import uuid from datetime import datetime from typing import Any, Dict, Optional from croniter import croniter from agent.tools.base_tool import BaseTool, ToolResult from bridge.context import Context, ContextType from bridge.reply import Reply, ReplyType from common.log import logger class SchedulerTool(BaseTool): """ Tool for managing scheduled tasks (reminders, notifications, etc.) """ name: str = "scheduler" description: str = ( "创建、查询和管理定时任务(提醒、周期性任务等)。\n\n" "⚠️ 重要:仅当需要「定时/提醒/每天/每周/X分钟后/X点」等延迟或周期执行时才使用此工具。" "使用方法:\n" "- 创建:action='create', name='任务名', message/ai_task='内容', schedule_type='once/interval/cron', schedule_value='...'\n" "- 查询:action='list' / action='get', task_id='任务ID'\n" "- 管理:action='delete/enable/disable', task_id='任务ID'\n\n" "调度类型:\n" "- once: 一次性任务,支持相对时间(+5s,+10m,+1h,+1d)或ISO时间\n" "- interval: 固定间隔(秒),如3600表示每小时\n" "- cron: cron表达式,如'0 8 * * *'表示每天8点\n\n" "注意:'X秒后'用once+相对时间,'每X秒'用interval" ) params: dict = { "type": "object", "properties": { "action": { "type": "string", "enum": ["create", "list", "get", "delete", "enable", "disable"], "description": "操作类型: create(创建), list(列表), get(查询), delete(删除), enable(启用), disable(禁用)" }, "task_id": { "type": "string", "description": "任务ID (用于 get/delete/enable/disable 操作)" }, "name": { "type": "string", "description": "任务名称 (用于 create 操作)" }, "message": { "type": "string", "description": "固定消息内容 (与ai_task二选一)" }, "ai_task": { "type": "string", "description": "AI任务描述 (与message二选一),用于定时让AI执行的任务" }, "schedule_type": { "type": "string", "enum": ["cron", "interval", "once"], "description": "调度类型 (用于 create 操作): cron(cron表达式), interval(固定间隔秒数), once(一次性)" }, "schedule_value": { "type": "string", "description": "调度值: cron表达式/间隔秒数/时间(+5s,+10m,+1h或ISO格式)" } }, "required": ["action"] } def __init__(self, config: dict = None): super().__init__() self.config = config or {} # Will be set by agent bridge self.task_store = None self.current_context = None def execute(self, params: dict) -> ToolResult: """ Execute scheduler operations Args: params: Dictionary containing: - action: Operation type (create/list/get/delete/enable/disable) - Other parameters depending on action Returns: ToolResult object """ # Extract parameters action = params.get("action") kwargs = params if not self.task_store: return ToolResult.fail("错误: 定时任务系统未初始化") try: if action == "create": result = self._create_task(**kwargs) return ToolResult.success(result) elif action == "list": result = self._list_tasks(**kwargs) return ToolResult.success(result) elif action == "get": result = self._get_task(**kwargs) return ToolResult.success(result) elif action == "delete": result = self._delete_task(**kwargs) return ToolResult.success(result) elif action == "enable": result = self._enable_task(**kwargs) return ToolResult.success(result) elif action == "disable": result = self._disable_task(**kwargs) return ToolResult.success(result) else: return ToolResult.fail(f"未知操作: {action}") except Exception as e: logger.error(f"[SchedulerTool] Error: {e}") return ToolResult.fail(f"操作失败: {str(e)}") def _create_task(self, **kwargs) -> str: """Create a new scheduled task""" name = kwargs.get("name") message = kwargs.get("message") ai_task = kwargs.get("ai_task") schedule_type = kwargs.get("schedule_type") schedule_value = kwargs.get("schedule_value") # Validate required fields if not name: return "错误: 缺少任务名称 (name)" # Check that exactly one of message/ai_task is provided if not message and not ai_task: return "错误: 必须提供 message(固定消息)或 ai_task(AI任务)之一" if message and ai_task: return "错误: message 和 ai_task 只能提供其中一个" if not schedule_type: return "错误: 缺少调度类型 (schedule_type)" if not schedule_value: return "错误: 缺少调度值 (schedule_value)" # Validate schedule schedule = self._parse_schedule(schedule_type, schedule_value) if not schedule: return f"错误: 无效的调度配置 - type: {schedule_type}, value: {schedule_value}" # Get context info for receiver if not self.current_context: return "错误: 无法获取当前对话上下文" context = self.current_context # Create task task_id = str(uuid.uuid4())[:8] # Build action based on message or ai_task if message: action = { "type": "send_message", "content": message, "receiver": context.get("receiver"), "receiver_name": self._get_receiver_name(context), "is_group": context.get("isgroup", False), "channel_type": self.config.get("channel_type", "unknown") } else: # ai_task action = { "type": "agent_task", "task_description": ai_task, "receiver": context.get("receiver"), "receiver_name": self._get_receiver_name(context), "is_group": context.get("isgroup", False), "channel_type": self.config.get("channel_type", "unknown") } # 针对钉钉单聊,额外存储 sender_staff_id msg = context.kwargs.get("msg") if msg and hasattr(msg, 'sender_staff_id') and not context.get("isgroup", False): action["dingtalk_sender_staff_id"] = msg.sender_staff_id task_data = { "id": task_id, "name": name, "enabled": True, "created_at": datetime.now().isoformat(), "updated_at": datetime.now().isoformat(), "schedule": schedule, "action": action } # Calculate initial next_run_at next_run = self._calculate_next_run(task_data) if next_run: task_data["next_run_at"] = next_run.isoformat() # Save task self.task_store.add_task(task_data) # Format response schedule_desc = self._format_schedule_description(schedule) receiver_desc = task_data["action"]["receiver_name"] or task_data["action"]["receiver"] if message: content_desc = f"💬 固定消息: {message}" else: content_desc = f"🤖 AI任务: {ai_task}" return ( f"✅ 定时任务创建成功\n\n" f"📋 任务ID: {task_id}\n" f"📝 名称: {name}\n" f"⏰ 调度: {schedule_desc}\n" f"👤 接收者: {receiver_desc}\n" f"{content_desc}\n" f"🕐 下次执行: {next_run.strftime('%Y-%m-%d %H:%M:%S') if next_run else '未知'}" ) def _list_tasks(self, **kwargs) -> str: """List all tasks""" tasks = self.task_store.list_tasks() if not tasks: return "📋 暂无定时任务" lines = [f"📋 定时任务列表 (共 {len(tasks)} 个)\n"] for task in tasks: status = "✅" if task.get("enabled", True) else "❌" schedule_desc = self._format_schedule_description(task.get("schedule", {})) next_run = task.get("next_run_at") next_run_str = datetime.fromisoformat(next_run).strftime('%m-%d %H:%M') if next_run else "未知" lines.append( f"{status} [{task['id']}] {task['name']}\n" f" ⏰ {schedule_desc} | 下次: {next_run_str}" ) return "\n".join(lines) def _get_task(self, **kwargs) -> str: """Get task details""" task_id = kwargs.get("task_id") if not task_id: return "错误: 缺少任务ID (task_id)" task = self.task_store.get_task(task_id) if not task: return f"错误: 任务 '{task_id}' 不存在" status = "启用" if task.get("enabled", True) else "禁用" schedule_desc = self._format_schedule_description(task.get("schedule", {})) action = task.get("action", {}) next_run = task.get("next_run_at") next_run_str = datetime.fromisoformat(next_run).strftime('%Y-%m-%d %H:%M:%S') if next_run else "未知" last_run = task.get("last_run_at") last_run_str = datetime.fromisoformat(last_run).strftime('%Y-%m-%d %H:%M:%S') if last_run else "从未执行" return ( f"📋 任务详情\n\n" f"ID: {task['id']}\n" f"名称: {task['name']}\n" f"状态: {status}\n" f"调度: {schedule_desc}\n" f"接收者: {action.get('receiver_name', action.get('receiver'))}\n" f"消息: {action.get('content')}\n" f"下次执行: {next_run_str}\n" f"上次执行: {last_run_str}\n" f"创建时间: {datetime.fromisoformat(task['created_at']).strftime('%Y-%m-%d %H:%M:%S')}" ) def _delete_task(self, **kwargs) -> str: """Delete a task""" task_id = kwargs.get("task_id") if not task_id: return "错误: 缺少任务ID (task_id)" task = self.task_store.get_task(task_id) if not task: return f"错误: 任务 '{task_id}' 不存在" self.task_store.delete_task(task_id) return f"✅ 任务 '{task['name']}' ({task_id}) 已删除" def _enable_task(self, **kwargs) -> str: """Enable a task""" task_id = kwargs.get("task_id") if not task_id: return "错误: 缺少任务ID (task_id)" task = self.task_store.get_task(task_id) if not task: return f"错误: 任务 '{task_id}' 不存在" self.task_store.enable_task(task_id, True) return f"✅ 任务 '{task['name']}' ({task_id}) 已启用" def _disable_task(self, **kwargs) -> str: """Disable a task""" task_id = kwargs.get("task_id") if not task_id: return "错误: 缺少任务ID (task_id)" task = self.task_store.get_task(task_id) if not task: return f"错误: 任务 '{task_id}' 不存在" self.task_store.enable_task(task_id, False) return f"✅ 任务 '{task['name']}' ({task_id}) 已禁用" def _parse_schedule(self, schedule_type: str, schedule_value: str) -> Optional[dict]: """Parse and validate schedule configuration""" try: if schedule_type == "cron": # Validate cron expression croniter(schedule_value) return {"type": "cron", "expression": schedule_value} elif schedule_type == "interval": # Parse interval in seconds seconds = int(schedule_value) if seconds <= 0: return None return {"type": "interval", "seconds": seconds} elif schedule_type == "once": # Parse datetime - support both relative and absolute time # Check if it's relative time (e.g., "+5s", "+10m", "+1h", "+1d") if schedule_value.startswith("+"): import re match = re.match(r'\+(\d+)([smhd])', schedule_value) if match: amount = int(match.group(1)) unit = match.group(2) from datetime import timedelta now = datetime.now() if unit == 's': # seconds target_time = now + timedelta(seconds=amount) elif unit == 'm': # minutes target_time = now + timedelta(minutes=amount) elif unit == 'h': # hours target_time = now + timedelta(hours=amount) elif unit == 'd': # days target_time = now + timedelta(days=amount) else: return None return {"type": "once", "run_at": target_time.isoformat()} else: logger.error(f"[SchedulerTool] Invalid relative time format: {schedule_value}") return None else: # Absolute time in ISO format datetime.fromisoformat(schedule_value) return {"type": "once", "run_at": schedule_value} except Exception as e: logger.error(f"[SchedulerTool] Invalid schedule: {e}") return None return None def _calculate_next_run(self, task: dict) -> Optional[datetime]: """Calculate next run time for a task""" schedule = task.get("schedule", {}) schedule_type = schedule.get("type") now = datetime.now() if schedule_type == "cron": expression = schedule.get("expression") cron = croniter(expression, now) return cron.get_next(datetime) elif schedule_type == "interval": seconds = schedule.get("seconds", 0) from datetime import timedelta return now + timedelta(seconds=seconds) elif schedule_type == "once": run_at_str = schedule.get("run_at") return datetime.fromisoformat(run_at_str) return None def _format_schedule_description(self, schedule: dict) -> str: """Format schedule as human-readable description""" schedule_type = schedule.get("type") if schedule_type == "cron": expr = schedule.get("expression", "") # Try to provide friendly description if expr == "0 9 * * *": return "每天 9:00" elif expr == "0 */1 * * *": return "每小时" elif expr == "*/30 * * * *": return "每30分钟" else: return f"Cron: {expr}" elif schedule_type == "interval": seconds = schedule.get("seconds", 0) if seconds >= 86400: days = seconds // 86400 return f"每 {days} 天" elif seconds >= 3600: hours = seconds // 3600 return f"每 {hours} 小时" elif seconds >= 60: minutes = seconds // 60 return f"每 {minutes} 分钟" else: return f"每 {seconds} 秒" elif schedule_type == "once": run_at = schedule.get("run_at", "") try: dt = datetime.fromisoformat(run_at) return f"一次性 ({dt.strftime('%Y-%m-%d %H:%M')})" except: return "一次性" return "未知" def _get_receiver_name(self, context: Context) -> str: """Get receiver name from context""" try: msg = context.get("msg") if msg: if context.get("isgroup"): return msg.other_user_nickname or "群聊" else: return msg.from_user_nickname or "用户" except: pass return "未知"
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/scheduler/task_store.py
Python
""" Task storage management for scheduler """ import json import os import threading from datetime import datetime from typing import Dict, List, Optional from pathlib import Path from common.utils import expand_path class TaskStore: """ Manages persistent storage of scheduled tasks """ def __init__(self, store_path: str = None): """ Initialize task store Args: store_path: Path to tasks.json file. Defaults to ~/cow/scheduler/tasks.json """ if store_path is None: # Default to ~/cow/scheduler/tasks.json home = expand_path("~") store_path = os.path.join(home, "cow", "scheduler", "tasks.json") self.store_path = store_path self.lock = threading.Lock() self._ensure_store_dir() def _ensure_store_dir(self): """Ensure the storage directory exists""" store_dir = os.path.dirname(self.store_path) os.makedirs(store_dir, exist_ok=True) def load_tasks(self) -> Dict[str, dict]: """ Load all tasks from storage Returns: Dictionary of task_id -> task_data """ with self.lock: if not os.path.exists(self.store_path): return {} try: with open(self.store_path, 'r', encoding='utf-8') as f: data = json.load(f) return data.get("tasks", {}) except Exception as e: print(f"Error loading tasks: {e}") return {} def save_tasks(self, tasks: Dict[str, dict]): """ Save all tasks to storage Args: tasks: Dictionary of task_id -> task_data """ with self.lock: try: # Create backup if os.path.exists(self.store_path): backup_path = f"{self.store_path}.bak" try: with open(self.store_path, 'r') as src: with open(backup_path, 'w') as dst: dst.write(src.read()) except: pass # Save tasks data = { "version": 1, "updated_at": datetime.now().isoformat(), "tasks": tasks } with open(self.store_path, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) except Exception as e: print(f"Error saving tasks: {e}") raise def add_task(self, task: dict) -> bool: """ Add a new task Args: task: Task data dictionary Returns: True if successful """ tasks = self.load_tasks() task_id = task.get("id") if not task_id: raise ValueError("Task must have an 'id' field") if task_id in tasks: raise ValueError(f"Task with id '{task_id}' already exists") tasks[task_id] = task self.save_tasks(tasks) return True def update_task(self, task_id: str, updates: dict) -> bool: """ Update an existing task Args: task_id: Task ID updates: Dictionary of fields to update Returns: True if successful """ tasks = self.load_tasks() if task_id not in tasks: raise ValueError(f"Task '{task_id}' not found") # Update fields tasks[task_id].update(updates) tasks[task_id]["updated_at"] = datetime.now().isoformat() self.save_tasks(tasks) return True def delete_task(self, task_id: str) -> bool: """ Delete a task Args: task_id: Task ID Returns: True if successful """ tasks = self.load_tasks() if task_id not in tasks: raise ValueError(f"Task '{task_id}' not found") del tasks[task_id] self.save_tasks(tasks) return True def get_task(self, task_id: str) -> Optional[dict]: """ Get a specific task Args: task_id: Task ID Returns: Task data or None if not found """ tasks = self.load_tasks() return tasks.get(task_id) def list_tasks(self, enabled_only: bool = False) -> List[dict]: """ List all tasks Args: enabled_only: If True, only return enabled tasks Returns: List of task dictionaries """ tasks = self.load_tasks() task_list = list(tasks.values()) if enabled_only: task_list = [t for t in task_list if t.get("enabled", True)] # Sort by next_run_at task_list.sort(key=lambda t: t.get("next_run_at", float('inf'))) return task_list def enable_task(self, task_id: str, enabled: bool = True) -> bool: """ Enable or disable a task Args: task_id: Task ID enabled: True to enable, False to disable Returns: True if successful """ return self.update_task(task_id, {"enabled": enabled})
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/send/__init__.py
Python
from .send import Send __all__ = ['Send']
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/send/send.py
Python
""" Send tool - Send files to the user """ import os from typing import Dict, Any from pathlib import Path from agent.tools.base_tool import BaseTool, ToolResult from common.utils import expand_path class Send(BaseTool): """Tool for sending files to the user""" name: str = "send" description: str = "Send a file (image, video, audio, document) to the user. Use this when the user explicitly asks to send/share a file." params: dict = { "type": "object", "properties": { "path": { "type": "string", "description": "Path to the file to send. Can be absolute path or relative to workspace." }, "message": { "type": "string", "description": "Optional message to accompany the file" } }, "required": ["path"] } def __init__(self, config: dict = None): self.config = config or {} self.cwd = self.config.get("cwd", os.getcwd()) # Supported file types self.image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico'} self.video_extensions = {'.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.webm', '.m4v'} self.audio_extensions = {'.mp3', '.wav', '.ogg', '.m4a', '.flac', '.aac', '.wma'} self.document_extensions = {'.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.txt', '.md'} def execute(self, args: Dict[str, Any]) -> ToolResult: """ Execute file send operation :param args: Contains file path and optional message :return: File metadata for channel to send """ path = args.get("path", "").strip() message = args.get("message", "") if not path: return ToolResult.fail("Error: path parameter is required") # Resolve path absolute_path = self._resolve_path(path) # Check if file exists if not os.path.exists(absolute_path): return ToolResult.fail(f"Error: File not found: {path}") # Check if readable if not os.access(absolute_path, os.R_OK): return ToolResult.fail(f"Error: File is not readable: {path}") # Get file info file_ext = Path(absolute_path).suffix.lower() file_size = os.path.getsize(absolute_path) file_name = Path(absolute_path).name # Determine file type if file_ext in self.image_extensions: file_type = "image" mime_type = self._get_image_mime_type(file_ext) elif file_ext in self.video_extensions: file_type = "video" mime_type = self._get_video_mime_type(file_ext) elif file_ext in self.audio_extensions: file_type = "audio" mime_type = self._get_audio_mime_type(file_ext) elif file_ext in self.document_extensions: file_type = "document" mime_type = self._get_document_mime_type(file_ext) else: file_type = "file" mime_type = "application/octet-stream" # Return file_to_send metadata result = { "type": "file_to_send", "file_type": file_type, "path": absolute_path, "file_name": file_name, "mime_type": mime_type, "size": file_size, "size_formatted": self._format_size(file_size), "message": message or f"正在发送 {file_name}" } return ToolResult.success(result) def _resolve_path(self, path: str) -> str: """Resolve path to absolute path""" path = expand_path(path) if os.path.isabs(path): return path return os.path.abspath(os.path.join(self.cwd, path)) def _get_image_mime_type(self, ext: str) -> str: """Get MIME type for image""" mime_map = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp', '.bmp': 'image/bmp', '.svg': 'image/svg+xml', '.ico': 'image/x-icon' } return mime_map.get(ext, 'image/jpeg') def _get_video_mime_type(self, ext: str) -> str: """Get MIME type for video""" mime_map = { '.mp4': 'video/mp4', '.avi': 'video/x-msvideo', '.mov': 'video/quicktime', '.mkv': 'video/x-matroska', '.webm': 'video/webm', '.flv': 'video/x-flv' } return mime_map.get(ext, 'video/mp4') def _get_audio_mime_type(self, ext: str) -> str: """Get MIME type for audio""" mime_map = { '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.ogg': 'audio/ogg', '.m4a': 'audio/mp4', '.flac': 'audio/flac', '.aac': 'audio/aac' } return mime_map.get(ext, 'audio/mpeg') def _get_document_mime_type(self, ext: str) -> str: """Get MIME type for document""" mime_map = { '.pdf': 'application/pdf', '.doc': 'application/msword', '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.xls': 'application/vnd.ms-excel', '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.ppt': 'application/vnd.ms-powerpoint', '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', '.txt': 'text/plain', '.md': 'text/markdown' } return mime_map.get(ext, 'application/octet-stream') def _format_size(self, size_bytes: int) -> str: """Format file size in human-readable format""" for unit in ['B', 'KB', 'MB', 'GB']: if size_bytes < 1024.0: return f"{size_bytes:.1f}{unit}" size_bytes /= 1024.0 return f"{size_bytes:.1f}TB"
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/tool_manager.py
Python
import importlib import importlib.util from pathlib import Path from typing import Dict, Any, Type from agent.tools.base_tool import BaseTool from common.log import logger from config import conf class ToolManager: """ Tool manager for managing tools. """ _instance = None def __new__(cls): """Singleton pattern to ensure only one instance of ToolManager exists.""" if cls._instance is None: cls._instance = super(ToolManager, cls).__new__(cls) cls._instance.tool_classes = {} # Store tool classes instead of instances cls._instance._initialized = False return cls._instance def __init__(self): # Initialize only once if not hasattr(self, 'tool_classes'): self.tool_classes = {} # Dictionary to store tool classes def load_tools(self, tools_dir: str = "", config_dict=None): """ Load tools from both directory and configuration. :param tools_dir: Directory to scan for tool modules """ if tools_dir: self._load_tools_from_directory(tools_dir) self._configure_tools_from_config() else: self._load_tools_from_init() self._configure_tools_from_config(config_dict) def _load_tools_from_init(self) -> bool: """ Load tool classes from tools.__init__.__all__ :return: True if tools were loaded, False otherwise """ try: # Try to import the tools package tools_package = importlib.import_module("agent.tools") # Check if __all__ is defined if hasattr(tools_package, "__all__"): tool_classes = tools_package.__all__ # Import each tool class directly from the tools package for class_name in tool_classes: try: # Skip base classes if class_name in ["BaseTool", "ToolManager"]: continue # Get the class directly from the tools package if hasattr(tools_package, class_name): cls = getattr(tools_package, class_name) if ( isinstance(cls, type) and issubclass(cls, BaseTool) and cls != BaseTool ): try: # Skip memory tools (they need special initialization with memory_manager) if class_name in ["MemorySearchTool", "MemoryGetTool"]: logger.debug(f"Skipped tool {class_name} (requires memory_manager)") continue # Create a temporary instance to get the name temp_instance = cls() tool_name = temp_instance.name # Store the class, not the instance self.tool_classes[tool_name] = cls logger.debug(f"Loaded tool: {tool_name} from class {class_name}") except ImportError as e: # Handle missing dependencies with helpful messages error_msg = str(e) if "browser-use" in error_msg or "browser_use" in error_msg: logger.warning( f"[ToolManager] Browser tool not loaded - missing dependencies.\n" f" To enable browser tool, run:\n" f" pip install browser-use markdownify playwright\n" f" playwright install chromium" ) elif "markdownify" in error_msg: logger.warning( f"[ToolManager] {cls.__name__} not loaded - missing markdownify.\n" f" Install with: pip install markdownify" ) else: logger.warning(f"[ToolManager] {cls.__name__} not loaded due to missing dependency: {error_msg}") except Exception as e: logger.error(f"Error initializing tool class {cls.__name__}: {e}") except Exception as e: logger.error(f"Error importing class {class_name}: {e}") return len(self.tool_classes) > 0 return False except ImportError: logger.warning("Could not import agent.tools package") return False except Exception as e: logger.error(f"Error loading tools from __init__.__all__: {e}") return False def _load_tools_from_directory(self, tools_dir: str): """Dynamically load tool classes from directory""" tools_path = Path(tools_dir) # Traverse all .py files for py_file in tools_path.rglob("*.py"): # Skip initialization files and base tool files if py_file.name in ["__init__.py", "base_tool.py", "tool_manager.py"]: continue # Get module name module_name = py_file.stem try: # Load module directly from file spec = importlib.util.spec_from_file_location(module_name, py_file) if spec and spec.loader: module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) # Find tool classes in the module for attr_name in dir(module): cls = getattr(module, attr_name) if ( isinstance(cls, type) and issubclass(cls, BaseTool) and cls != BaseTool ): try: # Skip memory tools (they need special initialization with memory_manager) if attr_name in ["MemorySearchTool", "MemoryGetTool"]: logger.debug(f"Skipped tool {attr_name} (requires memory_manager)") continue # Create a temporary instance to get the name temp_instance = cls() tool_name = temp_instance.name # Store the class, not the instance self.tool_classes[tool_name] = cls except ImportError as e: # Handle missing dependencies with helpful messages error_msg = str(e) if "browser-use" in error_msg or "browser_use" in error_msg: logger.warning( f"[ToolManager] Browser tool not loaded - missing dependencies.\n" f" To enable browser tool, run:\n" f" pip install browser-use markdownify playwright\n" f" playwright install chromium" ) elif "markdownify" in error_msg: logger.warning( f"[ToolManager] {cls.__name__} not loaded - missing markdownify.\n" f" Install with: pip install markdownify" ) else: logger.warning(f"[ToolManager] {cls.__name__} not loaded due to missing dependency: {error_msg}") except Exception as e: logger.error(f"Error initializing tool class {cls.__name__}: {e}") except Exception as e: print(f"Error importing module {py_file}: {e}") def _configure_tools_from_config(self, config_dict=None): """Configure tool classes based on configuration file""" try: # Get tools configuration tools_config = config_dict or conf().get("tools", {}) # Record tools that are configured but not loaded missing_tools = [] # Store configurations for later use when instantiating self.tool_configs = tools_config # Check which configured tools are missing for tool_name in tools_config: if tool_name not in self.tool_classes: missing_tools.append(tool_name) # If there are missing tools, record warnings if missing_tools: for tool_name in missing_tools: if tool_name == "browser": logger.warning( f"[ToolManager] Browser tool is configured but not loaded.\n" f" To enable browser tool, run:\n" f" pip install browser-use markdownify playwright\n" f" playwright install chromium" ) elif tool_name == "google_search": logger.warning( f"[ToolManager] Google Search tool is configured but may need API key.\n" f" Get API key from: https://serper.dev\n" f" Configure in config.json: tools.google_search.api_key" ) else: logger.warning(f"[ToolManager] Tool '{tool_name}' is configured but could not be loaded.") except Exception as e: logger.error(f"Error configuring tools from config: {e}") def create_tool(self, name: str) -> BaseTool: """ Get a new instance of a tool by name. :param name: The name of the tool to get. :return: A new instance of the tool or None if not found. """ tool_class = self.tool_classes.get(name) if tool_class: # Create a new instance tool_instance = tool_class() # Apply configuration if available if hasattr(self, 'tool_configs') and name in self.tool_configs: tool_instance.config = self.tool_configs[name] return tool_instance return None def list_tools(self) -> dict: """ Get information about all loaded tools. :return: A dictionary with tool information. """ result = {} for name, tool_class in self.tool_classes.items(): # Create a temporary instance to get schema temp_instance = tool_class() result[name] = { "description": temp_instance.description, "parameters": temp_instance.get_json_schema() } return result
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/utils/__init__.py
Python
from .truncate import ( truncate_head, truncate_tail, truncate_line, format_size, TruncationResult, DEFAULT_MAX_LINES, DEFAULT_MAX_BYTES, GREP_MAX_LINE_LENGTH ) from .diff import ( strip_bom, detect_line_ending, normalize_to_lf, restore_line_endings, normalize_for_fuzzy_match, fuzzy_find_text, generate_diff_string, FuzzyMatchResult ) __all__ = [ 'truncate_head', 'truncate_tail', 'truncate_line', 'format_size', 'TruncationResult', 'DEFAULT_MAX_LINES', 'DEFAULT_MAX_BYTES', 'GREP_MAX_LINE_LENGTH', 'strip_bom', 'detect_line_ending', 'normalize_to_lf', 'restore_line_endings', 'normalize_for_fuzzy_match', 'fuzzy_find_text', 'generate_diff_string', 'FuzzyMatchResult' ]
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/utils/diff.py
Python
""" Diff tools for file editing Provides fuzzy matching and diff generation functionality """ import difflib import re from typing import Optional, Tuple def strip_bom(text: str) -> Tuple[str, str]: """ Remove BOM (Byte Order Mark) :param text: Original text :return: (BOM, text after removing BOM) """ if text.startswith('\ufeff'): return '\ufeff', text[1:] return '', text def detect_line_ending(text: str) -> str: """ Detect line ending type :param text: Text content :return: Line ending type ('\r\n' or '\n') """ if '\r\n' in text: return '\r\n' return '\n' def normalize_to_lf(text: str) -> str: """ Normalize all line endings to LF (\n) :param text: Original text :return: Normalized text """ return text.replace('\r\n', '\n').replace('\r', '\n') def restore_line_endings(text: str, original_ending: str) -> str: """ Restore original line endings :param text: LF normalized text :param original_ending: Original line ending :return: Text with restored line endings """ if original_ending == '\r\n': return text.replace('\n', '\r\n') return text def normalize_for_fuzzy_match(text: str) -> str: """ Normalize text for fuzzy matching Remove excess whitespace but preserve basic structure :param text: Original text :return: Normalized text """ # Compress multiple spaces to one text = re.sub(r'[ \t]+', ' ', text) # Remove trailing spaces text = re.sub(r' +\n', '\n', text) # Remove leading spaces (but preserve indentation structure, only remove excess) lines = text.split('\n') normalized_lines = [] for line in lines: # Preserve indentation but normalize to multiples of single spaces stripped = line.lstrip() if stripped: indent_count = len(line) - len(stripped) # Normalize indentation (convert tabs to spaces) normalized_indent = ' ' * indent_count normalized_lines.append(normalized_indent + stripped) else: normalized_lines.append('') return '\n'.join(normalized_lines) class FuzzyMatchResult: """Fuzzy match result""" def __init__(self, found: bool, index: int = -1, match_length: int = 0, content_for_replacement: str = ""): self.found = found self.index = index self.match_length = match_length self.content_for_replacement = content_for_replacement def fuzzy_find_text(content: str, old_text: str) -> FuzzyMatchResult: """ Find text in content, try exact match first, then fuzzy match :param content: Content to search in :param old_text: Text to find :return: Match result """ # First try exact match index = content.find(old_text) if index != -1: return FuzzyMatchResult( found=True, index=index, match_length=len(old_text), content_for_replacement=content ) # Try fuzzy match fuzzy_content = normalize_for_fuzzy_match(content) fuzzy_old_text = normalize_for_fuzzy_match(old_text) index = fuzzy_content.find(fuzzy_old_text) if index != -1: # Fuzzy match successful, use normalized content for replacement return FuzzyMatchResult( found=True, index=index, match_length=len(fuzzy_old_text), content_for_replacement=fuzzy_content ) # Not found return FuzzyMatchResult(found=False) def generate_diff_string(old_content: str, new_content: str) -> dict: """ Generate unified diff string :param old_content: Old content :param new_content: New content :return: Dictionary containing diff and first changed line number """ old_lines = old_content.split('\n') new_lines = new_content.split('\n') # Generate unified diff diff_lines = list(difflib.unified_diff( old_lines, new_lines, lineterm='', fromfile='original', tofile='modified' )) # Find first changed line number first_changed_line = None for line in diff_lines: if line.startswith('@@'): # Parse @@ -1,3 +1,3 @@ format match = re.search(r'@@ -\d+,?\d* \+(\d+)', line) if match: first_changed_line = int(match.group(1)) break diff_string = '\n'.join(diff_lines) return { 'diff': diff_string, 'first_changed_line': first_changed_line }
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/utils/truncate.py
Python
""" Shared truncation utilities for tool outputs. Truncation is based on two independent limits - whichever is hit first wins: - Line limit (default: 2000 lines) - Byte limit (default: 50KB) Never returns partial lines (except bash tail truncation edge case). """ from typing import Dict, Any, Optional, Literal, Tuple DEFAULT_MAX_LINES = 2000 DEFAULT_MAX_BYTES = 50 * 1024 # 50KB GREP_MAX_LINE_LENGTH = 500 # Max chars per grep match line class TruncationResult: """Truncation result""" def __init__( self, content: str, truncated: bool, truncated_by: Optional[Literal["lines", "bytes"]], total_lines: int, total_bytes: int, output_lines: int, output_bytes: int, last_line_partial: bool = False, first_line_exceeds_limit: bool = False, max_lines: int = DEFAULT_MAX_LINES, max_bytes: int = DEFAULT_MAX_BYTES ): self.content = content self.truncated = truncated self.truncated_by = truncated_by self.total_lines = total_lines self.total_bytes = total_bytes self.output_lines = output_lines self.output_bytes = output_bytes self.last_line_partial = last_line_partial self.first_line_exceeds_limit = first_line_exceeds_limit self.max_lines = max_lines self.max_bytes = max_bytes def to_dict(self) -> Dict[str, Any]: """Convert to dictionary""" return { "content": self.content, "truncated": self.truncated, "truncated_by": self.truncated_by, "total_lines": self.total_lines, "total_bytes": self.total_bytes, "output_lines": self.output_lines, "output_bytes": self.output_bytes, "last_line_partial": self.last_line_partial, "first_line_exceeds_limit": self.first_line_exceeds_limit, "max_lines": self.max_lines, "max_bytes": self.max_bytes } def format_size(bytes_count: int) -> str: """Format bytes as human-readable size""" if bytes_count < 1024: return f"{bytes_count}B" elif bytes_count < 1024 * 1024: return f"{bytes_count / 1024:.1f}KB" else: return f"{bytes_count / (1024 * 1024):.1f}MB" def truncate_head(content: str, max_lines: Optional[int] = None, max_bytes: Optional[int] = None) -> TruncationResult: """ Truncate content from the head (keep first N lines/bytes). Suitable for file reads where you want to see the beginning. Never returns partial lines. If first line exceeds byte limit, returns empty content with first_line_exceeds_limit=True. :param content: Content to truncate :param max_lines: Maximum number of lines (default: 2000) :param max_bytes: Maximum number of bytes (default: 50KB) :return: Truncation result """ if max_lines is None: max_lines = DEFAULT_MAX_LINES if max_bytes is None: max_bytes = DEFAULT_MAX_BYTES total_bytes = len(content.encode('utf-8')) lines = content.split('\n') total_lines = len(lines) # Check if no truncation is needed if total_lines <= max_lines and total_bytes <= max_bytes: return TruncationResult( content=content, truncated=False, truncated_by=None, total_lines=total_lines, total_bytes=total_bytes, output_lines=total_lines, output_bytes=total_bytes, last_line_partial=False, first_line_exceeds_limit=False, max_lines=max_lines, max_bytes=max_bytes ) # Check if first line alone exceeds byte limit first_line_bytes = len(lines[0].encode('utf-8')) if first_line_bytes > max_bytes: return TruncationResult( content="", truncated=True, truncated_by="bytes", total_lines=total_lines, total_bytes=total_bytes, output_lines=0, output_bytes=0, last_line_partial=False, first_line_exceeds_limit=True, max_lines=max_lines, max_bytes=max_bytes ) # Collect complete lines that fit output_lines_arr = [] output_bytes_count = 0 truncated_by = "lines" for i, line in enumerate(lines): if i >= max_lines: break # Calculate line bytes (add 1 for newline if not first line) line_bytes = len(line.encode('utf-8')) + (1 if i > 0 else 0) if output_bytes_count + line_bytes > max_bytes: truncated_by = "bytes" break output_lines_arr.append(line) output_bytes_count += line_bytes # If exited due to line limit if len(output_lines_arr) >= max_lines and output_bytes_count <= max_bytes: truncated_by = "lines" output_content = '\n'.join(output_lines_arr) final_output_bytes = len(output_content.encode('utf-8')) return TruncationResult( content=output_content, truncated=True, truncated_by=truncated_by, total_lines=total_lines, total_bytes=total_bytes, output_lines=len(output_lines_arr), output_bytes=final_output_bytes, last_line_partial=False, first_line_exceeds_limit=False, max_lines=max_lines, max_bytes=max_bytes ) def truncate_tail(content: str, max_lines: Optional[int] = None, max_bytes: Optional[int] = None) -> TruncationResult: """ Truncate content from tail (keep last N lines/bytes). Suitable for bash output where you want to see the ending content (errors, final results). If the last line of original content exceeds byte limit, may return partial first line. :param content: Content to truncate :param max_lines: Maximum lines (default: 2000) :param max_bytes: Maximum bytes (default: 50KB) :return: Truncation result """ if max_lines is None: max_lines = DEFAULT_MAX_LINES if max_bytes is None: max_bytes = DEFAULT_MAX_BYTES total_bytes = len(content.encode('utf-8')) lines = content.split('\n') total_lines = len(lines) # Check if no truncation is needed if total_lines <= max_lines and total_bytes <= max_bytes: return TruncationResult( content=content, truncated=False, truncated_by=None, total_lines=total_lines, total_bytes=total_bytes, output_lines=total_lines, output_bytes=total_bytes, last_line_partial=False, first_line_exceeds_limit=False, max_lines=max_lines, max_bytes=max_bytes ) # Work backwards from the end output_lines_arr = [] output_bytes_count = 0 truncated_by = "lines" last_line_partial = False for i in range(len(lines) - 1, -1, -1): if len(output_lines_arr) >= max_lines: break line = lines[i] # Calculate line bytes (add newline if not the first added line) line_bytes = len(line.encode('utf-8')) + (1 if len(output_lines_arr) > 0 else 0) if output_bytes_count + line_bytes > max_bytes: truncated_by = "bytes" # Edge case: if we haven't added any lines yet and this line exceeds maxBytes, # take the end portion of this line if len(output_lines_arr) == 0: truncated_line = _truncate_string_to_bytes_from_end(line, max_bytes) output_lines_arr.insert(0, truncated_line) output_bytes_count = len(truncated_line.encode('utf-8')) last_line_partial = True break output_lines_arr.insert(0, line) output_bytes_count += line_bytes # If exited due to line limit if len(output_lines_arr) >= max_lines and output_bytes_count <= max_bytes: truncated_by = "lines" output_content = '\n'.join(output_lines_arr) final_output_bytes = len(output_content.encode('utf-8')) return TruncationResult( content=output_content, truncated=True, truncated_by=truncated_by, total_lines=total_lines, total_bytes=total_bytes, output_lines=len(output_lines_arr), output_bytes=final_output_bytes, last_line_partial=last_line_partial, first_line_exceeds_limit=False, max_lines=max_lines, max_bytes=max_bytes ) def _truncate_string_to_bytes_from_end(text: str, max_bytes: int) -> str: """ Truncate string to fit byte limit (from end). Properly handles multi-byte UTF-8 characters. :param text: String to truncate :param max_bytes: Maximum bytes :return: Truncated string """ encoded = text.encode('utf-8') if len(encoded) <= max_bytes: return text # Start from end, skip back maxBytes start = len(encoded) - max_bytes # Find valid UTF-8 boundary (character start) while start < len(encoded) and (encoded[start] & 0xC0) == 0x80: start += 1 return encoded[start:].decode('utf-8', errors='ignore') def truncate_line(line: str, max_chars: int = GREP_MAX_LINE_LENGTH) -> Tuple[str, bool]: """ Truncate single line to max characters, add [truncated] suffix. Used for grep match lines. :param line: Line to truncate :param max_chars: Maximum characters :return: (truncated text, whether truncated) """ if len(line) <= max_chars: return line, False return f"{line[:max_chars]}... [truncated]", True
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/web_search/__init__.py
Python
from agent.tools.web_search.web_search import WebSearch __all__ = ["WebSearch"]
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/web_search/web_search.py
Python
""" Web Search tool - Search the web using Bocha or LinkAI search API. Supports two backends with unified response format: 1. Bocha Search (primary, requires BOCHA_API_KEY) 2. LinkAI Search (fallback, requires LINKAI_API_KEY) """ import os import json from typing import Dict, Any, Optional import requests from agent.tools.base_tool import BaseTool, ToolResult from common.log import logger # Default timeout for API requests (seconds) DEFAULT_TIMEOUT = 30 class WebSearch(BaseTool): """Tool for searching the web using Bocha or LinkAI search API""" name: str = "web_search" description: str = ( "Search the web for current information, news, research topics, or any real-time data. " "Returns web page titles, URLs, snippets, and optional summaries. " "Use this when the user asks about recent events, needs fact-checking, or wants up-to-date information." ) params: dict = { "type": "object", "properties": { "query": { "type": "string", "description": "Search query string" }, "count": { "type": "integer", "description": "Number of results to return (1-50, default: 10)" }, "freshness": { "type": "string", "description": ( "Time range filter. Options: " "'noLimit' (default), 'oneDay', 'oneWeek', 'oneMonth', 'oneYear', " "or date range like '2025-01-01..2025-02-01'" ) }, "summary": { "type": "boolean", "description": "Whether to include text summary for each result (default: false)" } }, "required": ["query"] } def __init__(self, config: dict = None): self.config = config or {} self._backend = None # Will be resolved on first execute @staticmethod def is_available() -> bool: """Check if web search is available (at least one API key is configured)""" return bool(os.environ.get("BOCHA_API_KEY") or os.environ.get("LINKAI_API_KEY")) def _resolve_backend(self) -> Optional[str]: """ Determine which search backend to use. Priority: Bocha > LinkAI :return: 'bocha', 'linkai', or None """ if os.environ.get("BOCHA_API_KEY"): return "bocha" if os.environ.get("LINKAI_API_KEY"): return "linkai" return None def execute(self, args: Dict[str, Any]) -> ToolResult: """ Execute web search :param args: Search parameters (query, count, freshness, summary) :return: Search results """ query = args.get("query", "").strip() if not query: return ToolResult.fail("Error: 'query' parameter is required") count = args.get("count", 10) freshness = args.get("freshness", "noLimit") summary = args.get("summary", False) # Validate count if not isinstance(count, int) or count < 1 or count > 50: count = 10 # Resolve backend backend = self._resolve_backend() if not backend: return ToolResult.fail( "Error: No search API key configured. " "Please set BOCHA_API_KEY or LINKAI_API_KEY using env_config tool.\n" " - Bocha Search: https://open.bocha.cn\n" " - LinkAI Search: https://link-ai.tech" ) try: if backend == "bocha": return self._search_bocha(query, count, freshness, summary) else: return self._search_linkai(query, count, freshness) except requests.Timeout: return ToolResult.fail(f"Error: Search request timed out after {DEFAULT_TIMEOUT}s") except requests.ConnectionError: return ToolResult.fail("Error: Failed to connect to search API") except Exception as e: logger.error(f"[WebSearch] Unexpected error: {e}", exc_info=True) return ToolResult.fail(f"Error: Search failed - {str(e)}") def _search_bocha(self, query: str, count: int, freshness: str, summary: bool) -> ToolResult: """ Search using Bocha API :param query: Search query :param count: Number of results :param freshness: Time range filter :param summary: Whether to include summary :return: Formatted search results """ api_key = os.environ.get("BOCHA_API_KEY", "") url = "https://api.bocha.cn/v1/web-search" headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", "Accept": "application/json" } payload = { "query": query, "count": count, "freshness": freshness, "summary": summary } logger.debug(f"[WebSearch] Bocha search: query='{query}', count={count}") response = requests.post(url, headers=headers, json=payload, timeout=DEFAULT_TIMEOUT) if response.status_code == 401: return ToolResult.fail("Error: Invalid BOCHA_API_KEY. Please check your API key.") if response.status_code == 403: return ToolResult.fail("Error: Bocha API - insufficient balance. Please top up at https://open.bocha.cn") if response.status_code == 429: return ToolResult.fail("Error: Bocha API rate limit reached. Please try again later.") if response.status_code != 200: return ToolResult.fail(f"Error: Bocha API returned HTTP {response.status_code}") data = response.json() # Check API-level error code api_code = data.get("code") if api_code is not None and api_code != 200: msg = data.get("msg") or "Unknown error" return ToolResult.fail(f"Error: Bocha API error (code={api_code}): {msg}") # Extract and format results return self._format_bocha_results(data, query) def _format_bocha_results(self, data: dict, query: str) -> ToolResult: """ Format Bocha API response into unified result structure :param data: Raw API response :param query: Original query :return: Formatted ToolResult """ search_data = data.get("data", {}) web_pages = search_data.get("webPages", {}) pages = web_pages.get("value", []) if not pages: return ToolResult.success({ "query": query, "backend": "bocha", "total": 0, "results": [], "message": "No results found" }) results = [] for page in pages: result = { "title": page.get("name", ""), "url": page.get("url", ""), "snippet": page.get("snippet", ""), "siteName": page.get("siteName", ""), "datePublished": page.get("datePublished") or page.get("dateLastCrawled", ""), } # Include summary only if present if page.get("summary"): result["summary"] = page["summary"] results.append(result) total = web_pages.get("totalEstimatedMatches", len(results)) return ToolResult.success({ "query": query, "backend": "bocha", "total": total, "count": len(results), "results": results }) def _search_linkai(self, query: str, count: int, freshness: str) -> ToolResult: """ Search using LinkAI plugin API :param query: Search query :param count: Number of results :param freshness: Time range filter :return: Formatted search results """ api_key = os.environ.get("LINKAI_API_KEY", "") url = "https://api.link-ai.tech/v1/plugin/execute" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}" } payload = { "code": "web-search", "args": { "query": query, "count": count, "freshness": freshness } } logger.debug(f"[WebSearch] LinkAI search: query='{query}', count={count}") response = requests.post(url, headers=headers, json=payload, timeout=DEFAULT_TIMEOUT) if response.status_code == 401: return ToolResult.fail("Error: Invalid LINKAI_API_KEY. Please check your API key.") if response.status_code != 200: return ToolResult.fail(f"Error: LinkAI API returned HTTP {response.status_code}") data = response.json() if not data.get("success"): msg = data.get("message") or "Unknown error" return ToolResult.fail(f"Error: LinkAI search failed: {msg}") return self._format_linkai_results(data, query) def _format_linkai_results(self, data: dict, query: str) -> ToolResult: """ Format LinkAI API response into unified result structure. LinkAI returns the search data in data.data field, which follows the same Bing-compatible format as Bocha. :param data: Raw API response :param query: Original query :return: Formatted ToolResult """ raw_data = data.get("data", "") # LinkAI may return data as a JSON string if isinstance(raw_data, str): try: raw_data = json.loads(raw_data) except (json.JSONDecodeError, TypeError): # If data is plain text, return it as a single result return ToolResult.success({ "query": query, "backend": "linkai", "total": 1, "count": 1, "results": [{"content": raw_data}] }) # If the response follows Bing-compatible structure if isinstance(raw_data, dict): web_pages = raw_data.get("webPages", {}) pages = web_pages.get("value", []) if pages: results = [] for page in pages: result = { "title": page.get("name", ""), "url": page.get("url", ""), "snippet": page.get("snippet", ""), "siteName": page.get("siteName", ""), "datePublished": page.get("datePublished") or page.get("dateLastCrawled", ""), } if page.get("summary"): result["summary"] = page["summary"] results.append(result) total = web_pages.get("totalEstimatedMatches", len(results)) return ToolResult.success({ "query": query, "backend": "linkai", "total": total, "count": len(results), "results": results }) # Fallback: return raw data return ToolResult.success({ "query": query, "backend": "linkai", "total": 1, "count": 1, "results": [{"content": str(raw_data)}] })
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/write/__init__.py
Python
from .write import Write __all__ = ['Write']
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
agent/tools/write/write.py
Python
""" Write tool - Write file content Creates or overwrites files, automatically creates parent directories """ import os from typing import Dict, Any from pathlib import Path from agent.tools.base_tool import BaseTool, ToolResult from common.utils import expand_path class Write(BaseTool): """Tool for writing file content""" name: str = "write" description: str = "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories. IMPORTANT: Single write should not exceed 10KB. For large files, create a skeleton first, then use edit to add content in chunks." params: dict = { "type": "object", "properties": { "path": { "type": "string", "description": "Path to the file to write (relative or absolute)" }, "content": { "type": "string", "description": "Content to write to the file" } }, "required": ["path", "content"] } def __init__(self, config: dict = None): self.config = config or {} self.cwd = self.config.get("cwd", os.getcwd()) self.memory_manager = self.config.get("memory_manager", None) def execute(self, args: Dict[str, Any]) -> ToolResult: """ Execute file write operation :param args: Contains file path and content :return: Operation result """ path = args.get("path", "").strip() content = args.get("content", "") if not path: return ToolResult.fail("Error: path parameter is required") # Resolve path absolute_path = self._resolve_path(path) try: # Create parent directory (if needed) parent_dir = os.path.dirname(absolute_path) if parent_dir: os.makedirs(parent_dir, exist_ok=True) # Write file with open(absolute_path, 'w', encoding='utf-8') as f: f.write(content) # Get bytes written bytes_written = len(content.encode('utf-8')) # Auto-sync to memory database if this is a memory file if self.memory_manager and 'memory/' in path: self.memory_manager.mark_dirty() result = { "message": f"Successfully wrote {bytes_written} bytes to {path}", "path": path, "bytes_written": bytes_written } return ToolResult.success(result) except PermissionError: return ToolResult.fail(f"Error: Permission denied writing to {path}") except Exception as e: return ToolResult.fail(f"Error writing file: {str(e)}") def _resolve_path(self, path: str) -> str: """ Resolve path to absolute path :param path: Relative or absolute path :return: Absolute path """ # Expand ~ to user home directory path = expand_path(path) if os.path.isabs(path): return path return os.path.abspath(os.path.join(self.cwd, path))
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
app.py
Python
# encoding:utf-8 import os import signal import sys import time from channel import channel_factory from common import const from config import load_config from plugins import * import threading def sigterm_handler_wrap(_signo): old_handler = signal.getsignal(_signo) def func(_signo, _stack_frame): logger.info("signal {} received, exiting...".format(_signo)) conf().save_user_datas() if callable(old_handler): # check old_handler return old_handler(_signo, _stack_frame) sys.exit(0) signal.signal(_signo, func) def start_channel(channel_name: str): channel = channel_factory.create_channel(channel_name) if channel_name in ["wx", "wxy", "terminal", "wechatmp", "web", "wechatmp_service", "wechatcom_app", "wework", const.FEISHU, const.DINGTALK]: PluginManager().load_plugins() if conf().get("use_linkai"): try: from common import linkai_client threading.Thread(target=linkai_client.start, args=(channel,)).start() except Exception as e: pass channel.startup() def run(): try: # load config load_config() # ctrl + c sigterm_handler_wrap(signal.SIGINT) # kill signal sigterm_handler_wrap(signal.SIGTERM) # create channel channel_name = conf().get("channel_type", "wx") if "--cmd" in sys.argv: channel_name = "terminal" if channel_name == "wxy": os.environ["WECHATY_LOG"] = "warn" start_channel(channel_name) while True: time.sleep(1) except Exception as e: logger.error("App startup failed!") logger.exception(e) if __name__ == "__main__": run()
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
bridge/agent_bridge.py
Python
""" Agent Bridge - Integrates Agent system with existing COW bridge """ import os from typing import Optional, List from agent.protocol import Agent, LLMModel, LLMRequest from bridge.agent_event_handler import AgentEventHandler from bridge.agent_initializer import AgentInitializer from bridge.bridge import Bridge from bridge.context import Context from bridge.reply import Reply, ReplyType from common import const from common.log import logger from common.utils import expand_path from models.openai_compatible_bot import OpenAICompatibleBot def add_openai_compatible_support(bot_instance): """ Dynamically add OpenAI-compatible tool calling support to a bot instance. This allows any bot to gain tool calling capability without modifying its code, as long as it uses OpenAI-compatible API format. Note: Some bots like ZHIPUAIBot have native tool calling support and don't need enhancement. """ if hasattr(bot_instance, 'call_with_tools'): # Bot already has tool calling support (e.g., ZHIPUAIBot) logger.info(f"[AgentBridge] {type(bot_instance).__name__} already has native tool calling support") return bot_instance # Create a temporary mixin class that combines the bot with OpenAI compatibility class EnhancedBot(bot_instance.__class__, OpenAICompatibleBot): """Dynamically enhanced bot with OpenAI-compatible tool calling""" def get_api_config(self): """ Infer API config from common configuration patterns. Most OpenAI-compatible bots use similar configuration. """ from config import conf return { 'api_key': conf().get("open_ai_api_key"), 'api_base': conf().get("open_ai_api_base"), 'model': conf().get("model", "gpt-3.5-turbo"), 'default_temperature': conf().get("temperature", 0.9), 'default_top_p': conf().get("top_p", 1.0), 'default_frequency_penalty': conf().get("frequency_penalty", 0.0), 'default_presence_penalty': conf().get("presence_penalty", 0.0), } # Change the bot's class to the enhanced version bot_instance.__class__ = EnhancedBot logger.info( f"[AgentBridge] Enhanced {bot_instance.__class__.__bases__[0].__name__} with OpenAI-compatible tool calling") return bot_instance class AgentLLMModel(LLMModel): """ LLM Model adapter that uses COW's existing bot infrastructure """ def __init__(self, bridge: Bridge, bot_type: str = "chat"): # Get model name directly from config from config import conf model_name = conf().get("model", const.GPT_41) super().__init__(model=model_name) self.bridge = bridge self.bot_type = bot_type self._bot = None self._use_linkai = conf().get("use_linkai", False) and conf().get("linkai_api_key") @property def bot(self): """Lazy load the bot and enhance it with tool calling if needed""" if self._bot is None: # If use_linkai is enabled, use LinkAI bot directly if self._use_linkai: self._bot = self.bridge.find_chat_bot(const.LINKAI) else: self._bot = self.bridge.get_bot(self.bot_type) # Automatically add tool calling support if not present self._bot = add_openai_compatible_support(self._bot) # Log bot info bot_name = type(self._bot).__name__ return self._bot def call(self, request: LLMRequest): """ Call the model using COW's bot infrastructure """ try: # For non-streaming calls, we'll use the existing reply method # This is a simplified implementation if hasattr(self.bot, 'call_with_tools'): # Use tool-enabled call if available kwargs = { 'messages': request.messages, 'tools': getattr(request, 'tools', None), 'stream': False, 'model': self.model # Pass model parameter } # Only pass max_tokens if it's explicitly set if request.max_tokens is not None: kwargs['max_tokens'] = request.max_tokens # Extract system prompt if present system_prompt = getattr(request, 'system', None) if system_prompt: kwargs['system'] = system_prompt response = self.bot.call_with_tools(**kwargs) return self._format_response(response) else: # Fallback to regular call # This would need to be implemented based on your specific needs raise NotImplementedError("Regular call not implemented yet") except Exception as e: logger.error(f"AgentLLMModel call error: {e}") raise def call_stream(self, request: LLMRequest): """ Call the model with streaming using COW's bot infrastructure """ try: if hasattr(self.bot, 'call_with_tools'): # Use tool-enabled streaming call if available # Extract system prompt if present system_prompt = getattr(request, 'system', None) # Build kwargs for call_with_tools kwargs = { 'messages': request.messages, 'tools': getattr(request, 'tools', None), 'stream': True, 'model': self.model # Pass model parameter } # Only pass max_tokens if explicitly set, let the bot use its default if request.max_tokens is not None: kwargs['max_tokens'] = request.max_tokens # Add system prompt if present if system_prompt: kwargs['system'] = system_prompt stream = self.bot.call_with_tools(**kwargs) # Convert stream format to our expected format for chunk in stream: yield self._format_stream_chunk(chunk) else: bot_type = type(self.bot).__name__ raise NotImplementedError(f"Bot {bot_type} does not support call_with_tools. Please add the method.") except Exception as e: logger.error(f"AgentLLMModel call_stream error: {e}", exc_info=True) raise def _format_response(self, response): """Format Claude response to our expected format""" # This would need to be implemented based on Claude's response format return response def _format_stream_chunk(self, chunk): """Format Claude stream chunk to our expected format""" # This would need to be implemented based on Claude's stream format return chunk class AgentBridge: """ Bridge class that integrates super Agent with COW Manages multiple agent instances per session for conversation isolation """ def __init__(self, bridge: Bridge): self.bridge = bridge self.agents = {} # session_id -> Agent instance mapping self.default_agent = None # For backward compatibility (no session_id) self.agent: Optional[Agent] = None self.scheduler_initialized = False # Create helper instances self.initializer = AgentInitializer(bridge, self) def create_agent(self, system_prompt: str, tools: List = None, **kwargs) -> Agent: """ Create the super agent with COW integration Args: system_prompt: System prompt tools: List of tools (optional) **kwargs: Additional agent parameters Returns: Agent instance """ # Create LLM model that uses COW's bot infrastructure model = AgentLLMModel(self.bridge) # Default tools if none provided if tools is None: # Use ToolManager to load all available tools from agent.tools import ToolManager tool_manager = ToolManager() tool_manager.load_tools() tools = [] for tool_name in tool_manager.tool_classes.keys(): try: tool = tool_manager.create_tool(tool_name) if tool: tools.append(tool) except Exception as e: logger.warning(f"[AgentBridge] Failed to load tool {tool_name}: {e}") # Create agent instance agent = Agent( system_prompt=system_prompt, description=kwargs.get("description", "AI Super Agent"), model=model, tools=tools, max_steps=kwargs.get("max_steps", 15), output_mode=kwargs.get("output_mode", "logger"), workspace_dir=kwargs.get("workspace_dir"), # Pass workspace for skills loading enable_skills=kwargs.get("enable_skills", True), # Enable skills by default memory_manager=kwargs.get("memory_manager"), # Pass memory manager max_context_tokens=kwargs.get("max_context_tokens"), context_reserve_tokens=kwargs.get("context_reserve_tokens"), runtime_info=kwargs.get("runtime_info") # Pass runtime_info for dynamic time updates ) # Log skill loading details if agent.skill_manager: logger.debug(f"[AgentBridge] SkillManager initialized with {len(agent.skill_manager.skills)} skills") return agent def get_agent(self, session_id: str = None) -> Optional[Agent]: """ Get agent instance for the given session Args: session_id: Session identifier (e.g., user_id). If None, returns default agent. Returns: Agent instance for this session """ # If no session_id, use default agent (backward compatibility) if session_id is None: if self.default_agent is None: self._init_default_agent() return self.default_agent # Check if agent exists for this session if session_id not in self.agents: self._init_agent_for_session(session_id) return self.agents[session_id] def _init_default_agent(self): """Initialize default super agent""" agent = self.initializer.initialize_agent(session_id=None) self.default_agent = agent def _init_agent_for_session(self, session_id: str): """Initialize agent for a specific session""" agent = self.initializer.initialize_agent(session_id=session_id) self.agents[session_id] = agent def agent_reply(self, query: str, context: Context = None, on_event=None, clear_history: bool = False) -> Reply: """ Use super agent to reply to a query Args: query: User query context: COW context (optional, contains session_id for user isolation) on_event: Event callback (optional) clear_history: Whether to clear conversation history Returns: Reply object """ try: # Extract session_id from context for user isolation session_id = None if context: session_id = context.kwargs.get("session_id") or context.get("session_id") # Get agent for this session (will auto-initialize if needed) agent = self.get_agent(session_id=session_id) if not agent: return Reply(ReplyType.ERROR, "Failed to initialize super agent") # Create event handler for logging and channel communication event_handler = AgentEventHandler(context=context, original_callback=on_event) # Filter tools based on context original_tools = agent.tools filtered_tools = original_tools # If this is a scheduled task execution, exclude scheduler tool to prevent recursion if context and context.get("is_scheduled_task"): filtered_tools = [tool for tool in agent.tools if tool.name != "scheduler"] agent.tools = filtered_tools logger.info(f"[AgentBridge] Scheduled task execution: excluded scheduler tool ({len(filtered_tools)}/{len(original_tools)} tools)") else: # Attach context to scheduler tool if present if context and agent.tools: for tool in agent.tools: if tool.name == "scheduler": try: from agent.tools.scheduler.integration import attach_scheduler_to_tool attach_scheduler_to_tool(tool, context) except Exception as e: logger.warning(f"[AgentBridge] Failed to attach context to scheduler: {e}") break try: # Use agent's run_stream method with event handler response = agent.run_stream( user_message=query, on_event=event_handler.handle_event, clear_history=clear_history ) finally: # Restore original tools if context and context.get("is_scheduled_task"): agent.tools = original_tools # Log execution summary event_handler.log_summary() # Check if there are files to send (from read tool) if hasattr(agent, 'stream_executor') and hasattr(agent.stream_executor, 'files_to_send'): files_to_send = agent.stream_executor.files_to_send if files_to_send: # Send the first file (for now, handle one file at a time) file_info = files_to_send[0] logger.info(f"[AgentBridge] Sending file: {file_info.get('path')}") # Clear files_to_send for next request agent.stream_executor.files_to_send = [] # Return file reply based on file type return self._create_file_reply(file_info, response, context) return Reply(ReplyType.TEXT, response) except Exception as e: logger.error(f"Agent reply error: {e}") return Reply(ReplyType.ERROR, f"Agent error: {str(e)}") def _create_file_reply(self, file_info: dict, text_response: str, context: Context = None) -> Reply: """ Create a reply for sending files Args: file_info: File metadata from read tool text_response: Text response from agent context: Context object Returns: Reply object for file sending """ file_type = file_info.get("file_type", "file") file_path = file_info.get("path") # For images, use IMAGE_URL type (channel will handle upload) if file_type == "image": # Convert local path to file:// URL for channel processing file_url = f"file://{file_path}" logger.info(f"[AgentBridge] Sending image: {file_url}") reply = Reply(ReplyType.IMAGE_URL, file_url) # Attach text message if present (for channels that support text+image) if text_response: reply.text_content = text_response # Store accompanying text return reply # For all file types (document, video, audio), use FILE type if file_type in ["document", "video", "audio"]: file_url = f"file://{file_path}" logger.info(f"[AgentBridge] Sending {file_type}: {file_url}") reply = Reply(ReplyType.FILE, file_url) reply.file_name = file_info.get("file_name", os.path.basename(file_path)) # Attach text message if present if text_response: reply.text_content = text_response return reply # For other unknown file types, return text with file info message = text_response or file_info.get("message", "文件已准备") message += f"\n\n[文件: {file_info.get('file_name', file_path)}]" return Reply(ReplyType.TEXT, message) def _migrate_config_to_env(self, workspace_root: str): """ Migrate API keys from config.json to .env file if not already set Args: workspace_root: Workspace directory path (not used, kept for compatibility) """ from config import conf import os # Mapping from config.json keys to environment variable names key_mapping = { "open_ai_api_key": "OPENAI_API_KEY", "open_ai_api_base": "OPENAI_API_BASE", "gemini_api_key": "GEMINI_API_KEY", "claude_api_key": "CLAUDE_API_KEY", "linkai_api_key": "LINKAI_API_KEY", } # Use fixed secure location for .env file env_file = expand_path("~/.cow/.env") # Read existing env vars from .env file existing_env_vars = {} if os.path.exists(env_file): try: with open(env_file, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if line and not line.startswith('#') and '=' in line: key, _ = line.split('=', 1) existing_env_vars[key.strip()] = True except Exception as e: logger.warning(f"[AgentBridge] Failed to read .env file: {e}") # Check which keys need to be migrated keys_to_migrate = {} for config_key, env_key in key_mapping.items(): # Skip if already in .env file if env_key in existing_env_vars: continue # Get value from config.json value = conf().get(config_key, "") if value and value.strip(): # Only migrate non-empty values keys_to_migrate[env_key] = value.strip() # Log summary if there are keys to skip if existing_env_vars: logger.debug(f"[AgentBridge] {len(existing_env_vars)} env vars already in .env") # Write new keys to .env file if keys_to_migrate: try: # Ensure ~/.cow directory and .env file exist env_dir = os.path.dirname(env_file) if not os.path.exists(env_dir): os.makedirs(env_dir, exist_ok=True) if not os.path.exists(env_file): open(env_file, 'a').close() # Append new keys with open(env_file, 'a', encoding='utf-8') as f: f.write('\n# Auto-migrated from config.json\n') for key, value in keys_to_migrate.items(): f.write(f'{key}={value}\n') # Also set in current process os.environ[key] = value logger.info(f"[AgentBridge] Migrated {len(keys_to_migrate)} API keys from config.json to .env: {list(keys_to_migrate.keys())}") except Exception as e: logger.warning(f"[AgentBridge] Failed to migrate API keys: {e}") def clear_session(self, session_id: str): """ Clear a specific session's agent and conversation history Args: session_id: Session identifier to clear """ if session_id in self.agents: logger.info(f"[AgentBridge] Clearing session: {session_id}") del self.agents[session_id] def clear_all_sessions(self): """Clear all agent sessions""" logger.info(f"[AgentBridge] Clearing all sessions ({len(self.agents)} total)") self.agents.clear() self.default_agent = None def refresh_all_skills(self) -> int: """ Refresh skills and conditional tools in all agent instances after environment variable changes. This allows hot-reload without restarting. Returns: Number of agent instances refreshed """ import os from dotenv import load_dotenv from config import conf # Reload environment variables from .env file workspace_root = expand_path(conf().get("agent_workspace", "~/cow")) env_file = os.path.join(workspace_root, '.env') if os.path.exists(env_file): load_dotenv(env_file, override=True) logger.info(f"[AgentBridge] Reloaded environment variables from {env_file}") refreshed_count = 0 # Collect all agent instances to refresh agents_to_refresh = [] if self.default_agent: agents_to_refresh.append(("default", self.default_agent)) for session_id, agent in self.agents.items(): agents_to_refresh.append((session_id, agent)) for label, agent in agents_to_refresh: # Refresh skills if hasattr(agent, 'skill_manager') and agent.skill_manager: agent.skill_manager.refresh_skills() # Refresh conditional tools (e.g. web_search depends on API keys) self._refresh_conditional_tools(agent) refreshed_count += 1 if refreshed_count > 0: logger.info(f"[AgentBridge] Refreshed skills & tools in {refreshed_count} agent instance(s)") return refreshed_count @staticmethod def _refresh_conditional_tools(agent): """ Add or remove conditional tools based on current environment variables. For example, web_search should only be present when BOCHA_API_KEY or LINKAI_API_KEY is set. """ try: from agent.tools.web_search.web_search import WebSearch has_tool = any(t.name == "web_search" for t in agent.tools) available = WebSearch.is_available() if available and not has_tool: # API key was added - inject the tool tool = WebSearch() tool.model = agent.model agent.tools.append(tool) logger.info("[AgentBridge] web_search tool added (API key now available)") elif not available and has_tool: # API key was removed - remove the tool agent.tools = [t for t in agent.tools if t.name != "web_search"] logger.info("[AgentBridge] web_search tool removed (API key no longer available)") except Exception as e: logger.debug(f"[AgentBridge] Failed to refresh conditional tools: {e}")
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
bridge/agent_event_handler.py
Python
""" Agent Event Handler - Handles agent events and thinking process output """ from common.log import logger class AgentEventHandler: """ Handles agent events and optionally sends intermediate messages to channel """ def __init__(self, context=None, original_callback=None): """ Initialize event handler Args: context: COW context (for accessing channel) original_callback: Original event callback to chain """ self.context = context self.original_callback = original_callback # Get channel for sending intermediate messages self.channel = None if context: self.channel = context.kwargs.get("channel") if hasattr(context, "kwargs") else None # Track current thinking for channel output self.current_thinking = "" self.turn_number = 0 def handle_event(self, event): """ Main event handler Args: event: Event dict with type and data """ event_type = event.get("type") data = event.get("data", {}) # Dispatch to specific handlers if event_type == "turn_start": self._handle_turn_start(data) elif event_type == "message_update": self._handle_message_update(data) elif event_type == "message_end": self._handle_message_end(data) elif event_type == "tool_execution_start": self._handle_tool_execution_start(data) elif event_type == "tool_execution_end": self._handle_tool_execution_end(data) # Call original callback if provided if self.original_callback: self.original_callback(event) def _handle_turn_start(self, data): """Handle turn start event""" self.turn_number = data.get("turn", 0) self.has_tool_calls_in_turn = False self.current_thinking = "" def _handle_message_update(self, data): """Handle message update event (streaming text)""" delta = data.get("delta", "") self.current_thinking += delta def _handle_message_end(self, data): """Handle message end event""" tool_calls = data.get("tool_calls", []) # Only send thinking process if followed by tool calls if tool_calls: if self.current_thinking.strip(): logger.debug(f"💭 {self.current_thinking.strip()[:200]}{'...' if len(self.current_thinking) > 200 else ''}") # Send thinking process to channel self._send_to_channel(f"{self.current_thinking.strip()}") else: # No tool calls = final response (logged at agent_stream level) if self.current_thinking.strip(): logger.debug(f"💬 {self.current_thinking.strip()[:200]}{'...' if len(self.current_thinking) > 200 else ''}") self.current_thinking = "" def _handle_tool_execution_start(self, data): """Handle tool execution start event - logged by agent_stream.py""" pass def _handle_tool_execution_end(self, data): """Handle tool execution end event - logged by agent_stream.py""" pass def _send_to_channel(self, message): """ Try to send message to channel Args: message: Message to send """ if self.channel: try: from bridge.reply import Reply, ReplyType # Create a Reply object for the message reply = Reply(ReplyType.TEXT, message) self.channel._send(reply, self.context) except Exception as e: logger.debug(f"[AgentEventHandler] Failed to send to channel: {e}") def log_summary(self): """Log execution summary - simplified""" # Summary removed as per user request # Real-time logging during execution is sufficient pass
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
bridge/agent_initializer.py
Python
""" Agent Initializer - Handles agent initialization logic """ import os import asyncio import datetime import time from typing import Optional, List from agent.protocol import Agent from agent.tools import ToolManager from common.log import logger from common.utils import expand_path class AgentInitializer: """ Handles agent initialization including: - Workspace setup - Memory system initialization - Tool loading - System prompt building """ def __init__(self, bridge, agent_bridge): """ Initialize agent initializer Args: bridge: COW bridge instance agent_bridge: AgentBridge instance (for create_agent method) """ self.bridge = bridge self.agent_bridge = agent_bridge def initialize_agent(self, session_id: Optional[str] = None) -> Agent: """ Initialize agent for a session Args: session_id: Session ID (None for default agent) Returns: Initialized agent instance """ from config import conf # Get workspace from config workspace_root = expand_path(conf().get("agent_workspace", "~/cow")) # Migrate API keys self._migrate_config_to_env(workspace_root) # Load environment variables self._load_env_file() # Initialize workspace from agent.prompt import ensure_workspace, load_context_files, PromptBuilder workspace_files = ensure_workspace(workspace_root, create_templates=True) if session_id is None: logger.info(f"[AgentInitializer] Workspace initialized at: {workspace_root}") # Setup memory system memory_manager, memory_tools = self._setup_memory_system(workspace_root, session_id) # Load tools tools = self._load_tools(workspace_root, memory_manager, memory_tools, session_id) # Initialize scheduler if needed self._initialize_scheduler(tools, session_id) # Load context files context_files = load_context_files(workspace_root) # Initialize skill manager skill_manager = self._initialize_skill_manager(workspace_root, session_id) # Check if first conversation from agent.prompt.workspace import is_first_conversation, mark_conversation_started is_first = is_first_conversation(workspace_root) # Build system prompt prompt_builder = PromptBuilder(workspace_dir=workspace_root, language="zh") runtime_info = self._get_runtime_info(workspace_root) system_prompt = prompt_builder.build( tools=tools, context_files=context_files, skill_manager=skill_manager, memory_manager=memory_manager, runtime_info=runtime_info, is_first_conversation=is_first ) if is_first: mark_conversation_started(workspace_root) # Get cost control parameters from config import conf max_steps = conf().get("agent_max_steps", 20) max_context_tokens = conf().get("agent_max_context_tokens", 50000) # Create agent agent = self.agent_bridge.create_agent( system_prompt=system_prompt, tools=tools, max_steps=max_steps, output_mode="logger", workspace_dir=workspace_root, skill_manager=skill_manager, enable_skills=True, max_context_tokens=max_context_tokens, runtime_info=runtime_info # Pass runtime_info for dynamic time updates ) # Attach memory manager if memory_manager: agent.memory_manager = memory_manager return agent def _load_env_file(self): """Load environment variables from .env file""" env_file = expand_path("~/.cow/.env") if os.path.exists(env_file): try: from dotenv import load_dotenv load_dotenv(env_file, override=True) except ImportError: logger.warning("[AgentInitializer] python-dotenv not installed") except Exception as e: logger.warning(f"[AgentInitializer] Failed to load .env file: {e}") def _setup_memory_system(self, workspace_root: str, session_id: Optional[str] = None): """ Setup memory system Returns: (memory_manager, memory_tools) tuple """ memory_manager = None memory_tools = [] try: from agent.memory import MemoryManager, MemoryConfig, create_embedding_provider from agent.tools import MemorySearchTool, MemoryGetTool from config import conf # Get OpenAI config openai_api_key = conf().get("open_ai_api_key", "") openai_api_base = conf().get("open_ai_api_base", "") # Initialize embedding provider embedding_provider = None if openai_api_key and openai_api_key not in ["", "YOUR API KEY", "YOUR_API_KEY"]: try: embedding_provider = create_embedding_provider( provider="openai", model="text-embedding-3-small", api_key=openai_api_key, api_base=openai_api_base or "https://api.openai.com/v1" ) if session_id is None: logger.info("[AgentInitializer] OpenAI embedding initialized") except Exception as e: logger.warning(f"[AgentInitializer] OpenAI embedding failed: {e}") # Create memory manager memory_config = MemoryConfig(workspace_root=workspace_root) memory_manager = MemoryManager(memory_config, embedding_provider=embedding_provider) # Sync memory self._sync_memory(memory_manager, session_id) # Create memory tools memory_tools = [ MemorySearchTool(memory_manager), MemoryGetTool(memory_manager) ] if session_id is None: logger.info("[AgentInitializer] Memory system initialized") except Exception as e: logger.warning(f"[AgentInitializer] Memory system not available: {e}") return memory_manager, memory_tools def _sync_memory(self, memory_manager, session_id: Optional[str] = None): """Sync memory database""" try: loop = asyncio.get_event_loop() if loop.is_closed(): raise RuntimeError("Event loop is closed") except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: if loop.is_running(): asyncio.create_task(memory_manager.sync()) else: loop.run_until_complete(memory_manager.sync()) except Exception as e: logger.warning(f"[AgentInitializer] Memory sync failed: {e}") def _load_tools(self, workspace_root: str, memory_manager, memory_tools: List, session_id: Optional[str] = None): """Load all tools""" tool_manager = ToolManager() tool_manager.load_tools() tools = [] file_config = { "cwd": workspace_root, "memory_manager": memory_manager } if memory_manager else {"cwd": workspace_root} for tool_name in tool_manager.tool_classes.keys(): try: # Skip web_search if no API key is available if tool_name == "web_search": from agent.tools.web_search.web_search import WebSearch if not WebSearch.is_available(): logger.debug("[AgentInitializer] WebSearch skipped - no BOCHA_API_KEY or LINKAI_API_KEY") continue # Special handling for EnvConfig tool if tool_name == "env_config": from agent.tools import EnvConfig tool = EnvConfig({"agent_bridge": self.agent_bridge}) else: tool = tool_manager.create_tool(tool_name) if tool: # Apply workspace config to file operation tools if tool_name in ['read', 'write', 'edit', 'bash', 'grep', 'find', 'ls']: tool.config = file_config tool.cwd = file_config.get("cwd", getattr(tool, 'cwd', None)) if 'memory_manager' in file_config: tool.memory_manager = file_config['memory_manager'] tools.append(tool) except Exception as e: logger.warning(f"[AgentInitializer] Failed to load tool {tool_name}: {e}") # Add memory tools if memory_tools: tools.extend(memory_tools) if session_id is None: logger.info(f"[AgentInitializer] Added {len(memory_tools)} memory tools") if session_id is None: logger.info(f"[AgentInitializer] Loaded {len(tools)} tools: {[t.name for t in tools]}") return tools def _initialize_scheduler(self, tools: List, session_id: Optional[str] = None): """Initialize scheduler service if needed""" if not self.agent_bridge.scheduler_initialized: try: from agent.tools.scheduler.integration import init_scheduler if init_scheduler(self.agent_bridge): self.agent_bridge.scheduler_initialized = True if session_id is None: logger.info("[AgentInitializer] Scheduler service initialized") except Exception as e: logger.warning(f"[AgentInitializer] Failed to initialize scheduler: {e}") # Inject scheduler dependencies if self.agent_bridge.scheduler_initialized: try: from agent.tools.scheduler.integration import get_task_store, get_scheduler_service from agent.tools import SchedulerTool from config import conf task_store = get_task_store() scheduler_service = get_scheduler_service() for tool in tools: if isinstance(tool, SchedulerTool): tool.task_store = task_store tool.scheduler_service = scheduler_service if not tool.config: tool.config = {} tool.config["channel_type"] = conf().get("channel_type", "unknown") except Exception as e: logger.warning(f"[AgentInitializer] Failed to inject scheduler dependencies: {e}") def _initialize_skill_manager(self, workspace_root: str, session_id: Optional[str] = None): """Initialize skill manager""" try: from agent.skills import SkillManager skill_manager = SkillManager(workspace_dir=workspace_root) return skill_manager except Exception as e: logger.warning(f"[AgentInitializer] Failed to initialize SkillManager: {e}") return None def _get_runtime_info(self, workspace_root: str): """Get runtime information with dynamic time support""" from config import conf def get_current_time(): """Get current time dynamically - called each time system prompt is accessed""" now = datetime.datetime.now() # Get timezone info try: offset = -time.timezone if not time.daylight else -time.altzone hours = offset // 3600 minutes = (offset % 3600) // 60 timezone_name = f"UTC{hours:+03d}:{minutes:02d}" if minutes else f"UTC{hours:+03d}" except Exception: timezone_name = "UTC" # Chinese weekday mapping weekday_map = { 'Monday': '星期一', 'Tuesday': '星期二', 'Wednesday': '星期三', 'Thursday': '星期四', 'Friday': '星期五', 'Saturday': '星期六', 'Sunday': '星期日' } weekday_zh = weekday_map.get(now.strftime("%A"), now.strftime("%A")) return { 'time': now.strftime("%Y-%m-%d %H:%M:%S"), 'weekday': weekday_zh, 'timezone': timezone_name } return { "model": conf().get("model", "unknown"), "workspace": workspace_root, "channel": conf().get("channel_type", "unknown"), "_get_current_time": get_current_time # Dynamic time function } def _migrate_config_to_env(self, workspace_root: str): """Migrate API keys from config.json to .env file""" from config import conf key_mapping = { "open_ai_api_key": "OPENAI_API_KEY", "open_ai_api_base": "OPENAI_API_BASE", "gemini_api_key": "GEMINI_API_KEY", "claude_api_key": "CLAUDE_API_KEY", "linkai_api_key": "LINKAI_API_KEY", } env_file = expand_path("~/.cow/.env") # Read existing env vars existing_env_vars = {} if os.path.exists(env_file): try: with open(env_file, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if line and not line.startswith('#') and '=' in line: key, _ = line.split('=', 1) existing_env_vars[key.strip()] = True except Exception as e: logger.warning(f"[AgentInitializer] Failed to read .env file: {e}") # Check which keys need migration keys_to_migrate = {} for config_key, env_key in key_mapping.items(): if env_key in existing_env_vars: continue value = conf().get(config_key, "") if value and value.strip(): keys_to_migrate[env_key] = value.strip() # Write new keys if keys_to_migrate: try: env_dir = os.path.dirname(env_file) if not os.path.exists(env_dir): os.makedirs(env_dir, exist_ok=True) if not os.path.exists(env_file): open(env_file, 'a').close() with open(env_file, 'a', encoding='utf-8') as f: f.write('\n# Auto-migrated from config.json\n') for key, value in keys_to_migrate.items(): f.write(f'{key}={value}\n') os.environ[key] = value logger.info(f"[AgentInitializer] Migrated {len(keys_to_migrate)} API keys to .env: {list(keys_to_migrate.keys())}") except Exception as e: logger.warning(f"[AgentInitializer] Failed to migrate API keys: {e}")
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
bridge/bridge.py
Python
from models.bot_factory import create_bot from bridge.context import Context from bridge.reply import Reply from common import const from common.log import logger from common.singleton import singleton from config import conf from translate.factory import create_translator from voice.factory import create_voice @singleton class Bridge(object): def __init__(self): self.btype = { "chat": const.CHATGPT, "voice_to_text": conf().get("voice_to_text", "openai"), "text_to_voice": conf().get("text_to_voice", "google"), "translate": conf().get("translate", "baidu"), } # 这边取配置的模型 bot_type = conf().get("bot_type") if bot_type: self.btype["chat"] = bot_type else: model_type = conf().get("model") or const.GPT_41_MINI # Ensure model_type is string to prevent AttributeError when using startswith() # This handles cases where numeric model names (e.g., "1") are parsed as integers from YAML if not isinstance(model_type, str): logger.warning(f"[Bridge] model_type is not a string: {model_type} (type: {type(model_type).__name__}), converting to string") model_type = str(model_type) if model_type in ["text-davinci-003"]: self.btype["chat"] = const.OPEN_AI if conf().get("use_azure_chatgpt", False): self.btype["chat"] = const.CHATGPTONAZURE if model_type in ["wenxin", "wenxin-4"]: self.btype["chat"] = const.BAIDU if model_type in ["xunfei"]: self.btype["chat"] = const.XUNFEI if model_type in [const.QWEN]: self.btype["chat"] = const.QWEN if model_type in [const.QWEN_TURBO, const.QWEN_PLUS, const.QWEN_MAX]: self.btype["chat"] = const.QWEN_DASHSCOPE # Support Qwen3 and other DashScope models if model_type and (model_type.startswith("qwen") or model_type.startswith("qwq") or model_type.startswith("qvq")): self.btype["chat"] = const.QWEN_DASHSCOPE if model_type and model_type.startswith("gemini"): self.btype["chat"] = const.GEMINI if model_type and model_type.startswith("glm"): self.btype["chat"] = const.ZHIPU_AI if model_type and model_type.startswith("claude"): self.btype["chat"] = const.CLAUDEAPI if model_type in [const.MOONSHOT, "moonshot-v1-8k", "moonshot-v1-32k", "moonshot-v1-128k"]: self.btype["chat"] = const.MOONSHOT if model_type and model_type.startswith("kimi"): self.btype["chat"] = const.MOONSHOT if model_type and model_type.startswith("doubao"): self.btype["chat"] = const.DOUBAO if model_type in [const.MODELSCOPE]: self.btype["chat"] = const.MODELSCOPE # MiniMax models if model_type and (model_type in ["abab6.5-chat", "abab6.5"] or model_type.lower().startswith("minimax")): self.btype["chat"] = const.MiniMax if conf().get("use_linkai") and conf().get("linkai_api_key"): self.btype["chat"] = const.LINKAI if not conf().get("voice_to_text") or conf().get("voice_to_text") in ["openai"]: self.btype["voice_to_text"] = const.LINKAI if not conf().get("text_to_voice") or conf().get("text_to_voice") in ["openai", const.TTS_1, const.TTS_1_HD]: self.btype["text_to_voice"] = const.LINKAI self.bots = {} self.chat_bots = {} self._agent_bridge = None # 模型对应的接口 def get_bot(self, typename): if self.bots.get(typename) is None: logger.info("create bot {} for {}".format(self.btype[typename], typename)) if typename == "text_to_voice": self.bots[typename] = create_voice(self.btype[typename]) elif typename == "voice_to_text": self.bots[typename] = create_voice(self.btype[typename]) elif typename == "chat": self.bots[typename] = create_bot(self.btype[typename]) elif typename == "translate": self.bots[typename] = create_translator(self.btype[typename]) return self.bots[typename] def get_bot_type(self, typename): return self.btype[typename] def fetch_reply_content(self, query, context: Context) -> Reply: return self.get_bot("chat").reply(query, context) def fetch_voice_to_text(self, voiceFile) -> Reply: return self.get_bot("voice_to_text").voiceToText(voiceFile) def fetch_text_to_voice(self, text) -> Reply: return self.get_bot("text_to_voice").textToVoice(text) def fetch_translate(self, text, from_lang="", to_lang="en") -> Reply: return self.get_bot("translate").translate(text, from_lang, to_lang) def find_chat_bot(self, bot_type: str): if self.chat_bots.get(bot_type) is None: self.chat_bots[bot_type] = create_bot(bot_type) return self.chat_bots.get(bot_type) def reset_bot(self): """ 重置bot路由 """ self.__init__() def get_agent_bridge(self): """ Get agent bridge for agent-based conversations """ if self._agent_bridge is None: from bridge.agent_bridge import AgentBridge self._agent_bridge = AgentBridge(self) return self._agent_bridge def fetch_agent_reply(self, query: str, context: Context = None, on_event=None, clear_history: bool = False) -> Reply: """ Use super agent to handle the query Args: query: User query context: Context object on_event: Event callback for streaming clear_history: Whether to clear conversation history Returns: Reply object """ agent_bridge = self.get_agent_bridge() return agent_bridge.agent_reply(query, context, on_event, clear_history)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
bridge/context.py
Python
# encoding:utf-8 from enum import Enum class ContextType(Enum): TEXT = 1 # 文本消息 VOICE = 2 # 音频消息 IMAGE = 3 # 图片消息 FILE = 4 # 文件信息 VIDEO = 5 # 视频信息 SHARING = 6 # 分享信息 IMAGE_CREATE = 10 # 创建图片命令 ACCEPT_FRIEND = 19 # 同意好友请求 JOIN_GROUP = 20 # 加入群聊 PATPAT = 21 # 拍了拍 FUNCTION = 22 # 函数调用 EXIT_GROUP = 23 #退出 def __str__(self): return self.name class Context: def __init__(self, type: ContextType = None, content=None, kwargs=dict()): self.type = type self.content = content self.kwargs = kwargs def __contains__(self, key): if key == "type": return self.type is not None elif key == "content": return self.content is not None else: return key in self.kwargs def __getitem__(self, key): if key == "type": return self.type elif key == "content": return self.content else: return self.kwargs[key] def get(self, key, default=None): try: return self[key] except KeyError: return default def __setitem__(self, key, value): if key == "type": self.type = value elif key == "content": self.content = value else: self.kwargs[key] = value def __delitem__(self, key): if key == "type": self.type = None elif key == "content": self.content = None else: del self.kwargs[key] def __str__(self): return "Context(type={}, content={}, kwargs={})".format(self.type, self.content, self.kwargs)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
bridge/reply.py
Python
# encoding:utf-8 from enum import Enum class ReplyType(Enum): TEXT = 1 # 文本 VOICE = 2 # 音频文件 IMAGE = 3 # 图片文件 IMAGE_URL = 4 # 图片URL VIDEO_URL = 5 # 视频URL FILE = 6 # 文件 CARD = 7 # 微信名片,仅支持ntchat INVITE_ROOM = 8 # 邀请好友进群 INFO = 9 ERROR = 10 TEXT_ = 11 # 强制文本 VIDEO = 12 MINIAPP = 13 # 小程序 def __str__(self): return self.name class Reply: def __init__(self, type: ReplyType = None, content=None): self.type = type self.content = content def __str__(self): return "Reply(type={}, content={})".format(self.type, self.content)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/channel.py
Python
""" Message sending channel abstract class """ from bridge.bridge import Bridge from bridge.context import Context from bridge.reply import * from common.log import logger from config import conf class Channel(object): channel_type = "" NOT_SUPPORT_REPLYTYPE = [ReplyType.VOICE, ReplyType.IMAGE] def startup(self): """ init channel """ raise NotImplementedError def handle_text(self, msg): """ process received msg :param msg: message object """ raise NotImplementedError # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息 def send(self, reply: Reply, context: Context): """ send message to user :param msg: message content :param receiver: receiver channel account :return: """ raise NotImplementedError def build_reply_content(self, query, context: Context = None) -> Reply: """ Build reply content, using agent if enabled in config """ # Check if agent mode is enabled use_agent = conf().get("agent", False) if use_agent: try: logger.info("[Channel] Using agent mode") # Add channel_type to context if not present if context and "channel_type" not in context: context["channel_type"] = self.channel_type # Use agent bridge to handle the query return Bridge().fetch_agent_reply( query=query, context=context, on_event=None, clear_history=False ) except Exception as e: logger.error(f"[Channel] Agent mode failed, fallback to normal mode: {e}") # Fallback to normal mode if agent fails return Bridge().fetch_reply_content(query, context) else: # Normal mode return Bridge().fetch_reply_content(query, context) def build_voice_to_text(self, voice_file) -> Reply: return Bridge().fetch_voice_to_text(voice_file) def build_text_to_voice(self, text) -> Reply: return Bridge().fetch_text_to_voice(text)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/channel_factory.py
Python
""" channel factory """ from common import const from .channel import Channel def create_channel(channel_type) -> Channel: """ create a channel instance :param channel_type: channel type code :return: channel instance """ ch = Channel() if channel_type == "wx": from channel.wechat.wechat_channel import WechatChannel ch = WechatChannel() elif channel_type == "wxy": from channel.wechat.wechaty_channel import WechatyChannel ch = WechatyChannel() elif channel_type == "wcf": from channel.wechat.wcf_channel import WechatfChannel ch = WechatfChannel() elif channel_type == "terminal": from channel.terminal.terminal_channel import TerminalChannel ch = TerminalChannel() elif channel_type == 'web': from channel.web.web_channel import WebChannel ch = WebChannel() elif channel_type == "wechatmp": from channel.wechatmp.wechatmp_channel import WechatMPChannel ch = WechatMPChannel(passive_reply=True) elif channel_type == "wechatmp_service": from channel.wechatmp.wechatmp_channel import WechatMPChannel ch = WechatMPChannel(passive_reply=False) elif channel_type == "wechatcom_app": from channel.wechatcom.wechatcomapp_channel import WechatComAppChannel ch = WechatComAppChannel() elif channel_type == "wework": from channel.wework.wework_channel import WeworkChannel ch = WeworkChannel() elif channel_type == const.FEISHU: from channel.feishu.feishu_channel import FeiShuChanel ch = FeiShuChanel() elif channel_type == const.DINGTALK: from channel.dingtalk.dingtalk_channel import DingTalkChanel ch = DingTalkChanel() else: raise RuntimeError ch.channel_type = channel_type return ch
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/chat_channel.py
Python
import os import re import threading import time from asyncio import CancelledError from concurrent.futures import Future, ThreadPoolExecutor from bridge.context import * from bridge.reply import * from channel.channel import Channel from common.dequeue import Dequeue from common import memory from plugins import * try: from voice.audio_convert import any_to_wav except Exception as e: pass handler_pool = ThreadPoolExecutor(max_workers=8) # 处理消息的线程池 # 抽象类, 它包含了与消息通道无关的通用处理逻辑 class ChatChannel(Channel): name = None # 登录的用户名 user_id = None # 登录的用户id futures = {} # 记录每个session_id提交到线程池的future对象, 用于重置会话时把没执行的future取消掉,正在执行的不会被取消 sessions = {} # 用于控制并发,每个session_id同时只能有一个context在处理 lock = threading.Lock() # 用于控制对sessions的访问 def __init__(self): _thread = threading.Thread(target=self.consume) _thread.setDaemon(True) _thread.start() # 根据消息构造context,消息内容相关的触发项写在这里 def _compose_context(self, ctype: ContextType, content, **kwargs): context = Context(ctype, content) context.kwargs = kwargs # context首次传入时,origin_ctype是None, # 引入的起因是:当输入语音时,会嵌套生成两个context,第一步语音转文本,第二步通过文本生成文字回复。 # origin_ctype用于第二步文本回复时,判断是否需要匹配前缀,如果是私聊的语音,就不需要匹配前缀 if "origin_ctype" not in context: context["origin_ctype"] = ctype # context首次传入时,receiver是None,根据类型设置receiver first_in = "receiver" not in context # 群名匹配过程,设置session_id和receiver if first_in: # context首次传入时,receiver是None,根据类型设置receiver config = conf() cmsg = context["msg"] user_data = conf().get_user_data(cmsg.from_user_id) context["openai_api_key"] = user_data.get("openai_api_key") context["gpt_model"] = user_data.get("gpt_model") if context.get("isgroup", False): group_name = cmsg.other_user_nickname group_id = cmsg.other_user_id group_name_white_list = config.get("group_name_white_list", []) group_name_keyword_white_list = config.get("group_name_keyword_white_list", []) if any( [ group_name in group_name_white_list, "ALL_GROUP" in group_name_white_list, check_contain(group_name, group_name_keyword_white_list), ] ): # Check global group_shared_session config first group_shared_session = conf().get("group_shared_session", True) if group_shared_session: # All users in the group share the same session session_id = group_id else: # Check group-specific whitelist (legacy behavior) group_chat_in_one_session = conf().get("group_chat_in_one_session", []) session_id = cmsg.actual_user_id if any( [ group_name in group_chat_in_one_session, "ALL_GROUP" in group_chat_in_one_session, ] ): session_id = group_id else: logger.debug(f"No need reply, groupName not in whitelist, group_name={group_name}") return None context["session_id"] = session_id context["receiver"] = group_id else: context["session_id"] = cmsg.other_user_id context["receiver"] = cmsg.other_user_id e_context = PluginManager().emit_event(EventContext(Event.ON_RECEIVE_MESSAGE, {"channel": self, "context": context})) context = e_context["context"] if e_context.is_pass() or context is None: return context if cmsg.from_user_id == self.user_id and not config.get("trigger_by_self", True): logger.debug("[chat_channel]self message skipped") return None # 消息内容匹配过程,并处理content if ctype == ContextType.TEXT: if first_in and "」\n- - - - - - -" in content: # 初次匹配 过滤引用消息 logger.debug(content) logger.debug("[chat_channel]reference query skipped") return None nick_name_black_list = conf().get("nick_name_black_list", []) if context.get("isgroup", False): # 群聊 # 校验关键字 match_prefix = check_prefix(content, conf().get("group_chat_prefix")) match_contain = check_contain(content, conf().get("group_chat_keyword")) flag = False if context["msg"].to_user_id != context["msg"].actual_user_id: if match_prefix is not None or match_contain is not None: flag = True if match_prefix: content = content.replace(match_prefix, "", 1).strip() if context["msg"].is_at: nick_name = context["msg"].actual_user_nickname if nick_name and nick_name in nick_name_black_list: # 黑名单过滤 logger.warning(f"[chat_channel] Nickname {nick_name} in In BlackList, ignore") return None logger.info("[chat_channel]receive group at") if not conf().get("group_at_off", False): flag = True self.name = self.name if self.name is not None else "" # 部分渠道self.name可能没有赋值 pattern = f"@{re.escape(self.name)}(\u2005|\u0020)" subtract_res = re.sub(pattern, r"", content) if isinstance(context["msg"].at_list, list): for at in context["msg"].at_list: pattern = f"@{re.escape(at)}(\u2005|\u0020)" subtract_res = re.sub(pattern, r"", subtract_res) if subtract_res == content and context["msg"].self_display_name: # 前缀移除后没有变化,使用群昵称再次移除 pattern = f"@{re.escape(context['msg'].self_display_name)}(\u2005|\u0020)" subtract_res = re.sub(pattern, r"", content) content = subtract_res if not flag: if context["origin_ctype"] == ContextType.VOICE: logger.info("[chat_channel]receive group voice, but checkprefix didn't match") return None else: # 单聊 nick_name = context["msg"].from_user_nickname if nick_name and nick_name in nick_name_black_list: # 黑名单过滤 logger.warning(f"[chat_channel] Nickname '{nick_name}' in In BlackList, ignore") return None match_prefix = check_prefix(content, conf().get("single_chat_prefix", [""])) if match_prefix is not None: # 判断如果匹配到自定义前缀,则返回过滤掉前缀+空格后的内容 content = content.replace(match_prefix, "", 1).strip() elif context["origin_ctype"] == ContextType.VOICE: # 如果源消息是私聊的语音消息,允许不匹配前缀,放宽条件 pass else: logger.info("[chat_channel]receive single chat msg, but checkprefix didn't match") return None content = content.strip() img_match_prefix = check_prefix(content, conf().get("image_create_prefix",[""])) if img_match_prefix: content = content.replace(img_match_prefix, "", 1) context.type = ContextType.IMAGE_CREATE else: context.type = ContextType.TEXT context.content = content.strip() if "desire_rtype" not in context and conf().get("always_reply_voice") and ReplyType.VOICE not in self.NOT_SUPPORT_REPLYTYPE: context["desire_rtype"] = ReplyType.VOICE elif context.type == ContextType.VOICE: if "desire_rtype" not in context and conf().get("voice_reply_voice") and ReplyType.VOICE not in self.NOT_SUPPORT_REPLYTYPE: context["desire_rtype"] = ReplyType.VOICE return context def _handle(self, context: Context): if context is None or not context.content: return logger.debug("[chat_channel] handling context: {}".format(context)) # reply的构建步骤 reply = self._generate_reply(context) logger.debug("[chat_channel] decorating reply: {}".format(reply)) # reply的包装步骤 if reply and reply.content: reply = self._decorate_reply(context, reply) # reply的发送步骤 self._send_reply(context, reply) def _generate_reply(self, context: Context, reply: Reply = Reply()) -> Reply: e_context = PluginManager().emit_event( EventContext( Event.ON_HANDLE_CONTEXT, {"channel": self, "context": context, "reply": reply}, ) ) reply = e_context["reply"] if not e_context.is_pass(): logger.debug("[chat_channel] type={}, content={}".format(context.type, context.content)) if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE: # 文字和图片消息 context["channel"] = e_context["channel"] reply = super().build_reply_content(context.content, context) elif context.type == ContextType.VOICE: # 语音消息 cmsg = context["msg"] cmsg.prepare() file_path = context.content wav_path = os.path.splitext(file_path)[0] + ".wav" try: any_to_wav(file_path, wav_path) except Exception as e: # 转换失败,直接使用mp3,对于某些api,mp3也可以识别 logger.warning("[chat_channel]any to wav error, use raw path. " + str(e)) wav_path = file_path # 语音识别 reply = super().build_voice_to_text(wav_path) # 删除临时文件 try: os.remove(file_path) if wav_path != file_path: os.remove(wav_path) except Exception as e: pass # logger.warning("[chat_channel]delete temp file error: " + str(e)) if reply.type == ReplyType.TEXT: new_context = self._compose_context(ContextType.TEXT, reply.content, **context.kwargs) if new_context: reply = self._generate_reply(new_context) else: return elif context.type == ContextType.IMAGE: # 图片消息,当前仅做下载保存到本地的逻辑 memory.USER_IMAGE_CACHE[context["session_id"]] = { "path": context.content, "msg": context.get("msg") } elif context.type == ContextType.SHARING: # 分享信息,当前无默认逻辑 pass elif context.type == ContextType.FUNCTION or context.type == ContextType.FILE: # 文件消息及函数调用等,当前无默认逻辑 pass else: logger.warning("[chat_channel] unknown context type: {}".format(context.type)) return return reply def _decorate_reply(self, context: Context, reply: Reply) -> Reply: if reply and reply.type: e_context = PluginManager().emit_event( EventContext( Event.ON_DECORATE_REPLY, {"channel": self, "context": context, "reply": reply}, ) ) reply = e_context["reply"] desire_rtype = context.get("desire_rtype") if not e_context.is_pass() and reply and reply.type: if reply.type in self.NOT_SUPPORT_REPLYTYPE: logger.error("[chat_channel]reply type not support: " + str(reply.type)) reply.type = ReplyType.ERROR reply.content = "不支持发送的消息类型: " + str(reply.type) if reply.type == ReplyType.TEXT: reply_text = reply.content if desire_rtype == ReplyType.VOICE and ReplyType.VOICE not in self.NOT_SUPPORT_REPLYTYPE: reply = super().build_text_to_voice(reply.content) return self._decorate_reply(context, reply) if context.get("isgroup", False): if not context.get("no_need_at", False): reply_text = "@" + context["msg"].actual_user_nickname + "\n" + reply_text.strip() reply_text = conf().get("group_chat_reply_prefix", "") + reply_text + conf().get("group_chat_reply_suffix", "") else: reply_text = conf().get("single_chat_reply_prefix", "") + reply_text + conf().get("single_chat_reply_suffix", "") reply.content = reply_text elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO: reply.content = "[" + str(reply.type) + "]\n" + reply.content elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE or reply.type == ReplyType.FILE or reply.type == ReplyType.VIDEO or reply.type == ReplyType.VIDEO_URL: pass else: logger.error("[chat_channel] unknown reply type: {}".format(reply.type)) return if desire_rtype and desire_rtype != reply.type and reply.type not in [ReplyType.ERROR, ReplyType.INFO]: logger.warning("[chat_channel] desire_rtype: {}, but reply type: {}".format(context.get("desire_rtype"), reply.type)) return reply def _send_reply(self, context: Context, reply: Reply): if reply and reply.type: e_context = PluginManager().emit_event( EventContext( Event.ON_SEND_REPLY, {"channel": self, "context": context, "reply": reply}, ) ) reply = e_context["reply"] if not e_context.is_pass() and reply and reply.type: logger.debug("[chat_channel] sending reply: {}, context: {}".format(reply, context)) # 如果是文本回复,尝试提取并发送图片 if reply.type == ReplyType.TEXT: self._extract_and_send_images(reply, context) # 如果是图片回复但带有文本内容,先发文本再发图片 elif reply.type == ReplyType.IMAGE_URL and hasattr(reply, 'text_content') and reply.text_content: # 先发送文本 text_reply = Reply(ReplyType.TEXT, reply.text_content) self._send(text_reply, context) # 短暂延迟后发送图片 time.sleep(0.3) self._send(reply, context) else: self._send(reply, context) def _extract_and_send_images(self, reply: Reply, context: Context): """ 从文本回复中提取图片/视频URL并单独发送 支持格式:[图片: /path/to/image.png], [视频: /path/to/video.mp4], ![](url), <img src="url"> 最多发送5个媒体文件 """ content = reply.content media_items = [] # [(url, type), ...] # 正则提取各种格式的媒体URL patterns = [ (r'\[图片:\s*([^\]]+)\]', 'image'), # [图片: /path/to/image.png] (r'\[视频:\s*([^\]]+)\]', 'video'), # [视频: /path/to/video.mp4] (r'!\[.*?\]\(([^\)]+)\)', 'image'), # ![alt](url) - 默认图片 (r'<img[^>]+src=["\']([^"\']+)["\']', 'image'), # <img src="url"> (r'<video[^>]+src=["\']([^"\']+)["\']', 'video'), # <video src="url"> (r'https?://[^\s]+\.(?:jpg|jpeg|png|gif|webp)', 'image'), # 直接的图片URL (r'https?://[^\s]+\.(?:mp4|avi|mov|wmv|flv)', 'video'), # 直接的视频URL ] for pattern, media_type in patterns: matches = re.findall(pattern, content, re.IGNORECASE) for match in matches: media_items.append((match, media_type)) # 去重(保持顺序)并限制最多5个 seen = set() unique_items = [] for url, mtype in media_items: if url not in seen: seen.add(url) unique_items.append((url, mtype)) media_items = unique_items[:5] if media_items: logger.info(f"[chat_channel] Extracted {len(media_items)} media item(s) from reply") # 先发送文本(保持原文本不变) logger.info(f"[chat_channel] Sending text content before media: {reply.content[:100]}...") self._send(reply, context) logger.info(f"[chat_channel] Text sent, now sending {len(media_items)} media item(s)") # 然后逐个发送媒体文件 for i, (url, media_type) in enumerate(media_items): try: # 判断是本地文件还是URL if url.startswith(('http://', 'https://')): # 网络资源 if media_type == 'video': # 视频使用 FILE 类型发送 media_reply = Reply(ReplyType.FILE, url) media_reply.file_name = os.path.basename(url) else: # 图片使用 IMAGE_URL 类型 media_reply = Reply(ReplyType.IMAGE_URL, url) elif os.path.exists(url): # 本地文件 if media_type == 'video': # 视频使用 FILE 类型,转换为 file:// URL media_reply = Reply(ReplyType.FILE, f"file://{url}") media_reply.file_name = os.path.basename(url) else: # 图片使用 IMAGE_URL 类型,转换为 file:// URL media_reply = Reply(ReplyType.IMAGE_URL, f"file://{url}") else: logger.warning(f"[chat_channel] Media file not found or invalid URL: {url}") continue # 发送媒体文件(添加小延迟避免频率限制) if i > 0: time.sleep(0.5) self._send(media_reply, context) logger.info(f"[chat_channel] Sent {media_type} {i+1}/{len(media_items)}: {url[:50]}...") except Exception as e: logger.error(f"[chat_channel] Failed to send {media_type} {url}: {e}") else: # 没有媒体文件,正常发送文本 self._send(reply, context) def _send(self, reply: Reply, context: Context, retry_cnt=0): try: self.send(reply, context) except Exception as e: logger.error("[chat_channel] sendMsg error: {}".format(str(e))) if isinstance(e, NotImplementedError): return logger.exception(e) if retry_cnt < 2: time.sleep(3 + 3 * retry_cnt) self._send(reply, context, retry_cnt + 1) def _success_callback(self, session_id, **kwargs): # 线程正常结束时的回调函数 logger.debug("Worker return success, session_id = {}".format(session_id)) def _fail_callback(self, session_id, exception, **kwargs): # 线程异常结束时的回调函数 logger.exception("Worker return exception: {}".format(exception)) def _thread_pool_callback(self, session_id, **kwargs): def func(worker: Future): try: worker_exception = worker.exception() if worker_exception: self._fail_callback(session_id, exception=worker_exception, **kwargs) else: self._success_callback(session_id, **kwargs) except CancelledError as e: logger.info("Worker cancelled, session_id = {}".format(session_id)) except Exception as e: logger.exception("Worker raise exception: {}".format(e)) with self.lock: self.sessions[session_id][1].release() return func def produce(self, context: Context): session_id = context["session_id"] with self.lock: if session_id not in self.sessions: self.sessions[session_id] = [ Dequeue(), threading.BoundedSemaphore(conf().get("concurrency_in_session", 4)), ] if context.type == ContextType.TEXT and context.content.startswith("#"): self.sessions[session_id][0].putleft(context) # 优先处理管理命令 else: self.sessions[session_id][0].put(context) # 消费者函数,单独线程,用于从消息队列中取出消息并处理 def consume(self): while True: with self.lock: session_ids = list(self.sessions.keys()) for session_id in session_ids: with self.lock: context_queue, semaphore = self.sessions[session_id] if semaphore.acquire(blocking=False): # 等线程处理完毕才能删除 if not context_queue.empty(): context = context_queue.get() logger.debug("[chat_channel] consume context: {}".format(context)) future: Future = handler_pool.submit(self._handle, context) future.add_done_callback(self._thread_pool_callback(session_id, context=context)) with self.lock: if session_id not in self.futures: self.futures[session_id] = [] self.futures[session_id].append(future) elif semaphore._initial_value == semaphore._value + 1: # 除了当前,没有任务再申请到信号量,说明所有任务都处理完毕 with self.lock: self.futures[session_id] = [t for t in self.futures[session_id] if not t.done()] assert len(self.futures[session_id]) == 0, "thread pool error" del self.sessions[session_id] else: semaphore.release() time.sleep(0.2) # 取消session_id对应的所有任务,只能取消排队的消息和已提交线程池但未执行的任务 def cancel_session(self, session_id): with self.lock: if session_id in self.sessions: for future in self.futures[session_id]: future.cancel() cnt = self.sessions[session_id][0].qsize() if cnt > 0: logger.info("Cancel {} messages in session {}".format(cnt, session_id)) self.sessions[session_id][0] = Dequeue() def cancel_all_session(self): with self.lock: for session_id in self.sessions: for future in self.futures[session_id]: future.cancel() cnt = self.sessions[session_id][0].qsize() if cnt > 0: logger.info("Cancel {} messages in session {}".format(cnt, session_id)) self.sessions[session_id][0] = Dequeue() def check_prefix(content, prefix_list): if not prefix_list: return None for prefix in prefix_list: if content.startswith(prefix): return prefix return None def check_contain(content, keyword_list): if not keyword_list: return None for ky in keyword_list: if content.find(ky) != -1: return True return None
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/chat_message.py
Python
""" 本类表示聊天消息,用于对itchat和wechaty的消息进行统一的封装。 填好必填项(群聊6个,非群聊8个),即可接入ChatChannel,并支持插件,参考TerminalChannel ChatMessage msg_id: 消息id (必填) create_time: 消息创建时间 ctype: 消息类型 : ContextType (必填) content: 消息内容, 如果是声音/图片,这里是文件路径 (必填) from_user_id: 发送者id (必填) from_user_nickname: 发送者昵称 to_user_id: 接收者id (必填) to_user_nickname: 接收者昵称 other_user_id: 对方的id,如果你是发送者,那这个就是接收者id,如果你是接收者,那这个就是发送者id,如果是群消息,那这一直是群id (必填) other_user_nickname: 同上 is_group: 是否是群消息 (群聊必填) is_at: 是否被at - (群消息时,一般会存在实际发送者,是群内某个成员的id和昵称,下列项仅在群消息时存在) actual_user_id: 实际发送者id (群聊必填) actual_user_nickname:实际发送者昵称 self_display_name: 自身的展示名,设置群昵称时,该字段表示群昵称 _prepare_fn: 准备函数,用于准备消息的内容,比如下载图片等, _prepared: 是否已经调用过准备函数 _rawmsg: 原始消息对象 """ class ChatMessage(object): msg_id = None create_time = None ctype = None content = None from_user_id = None from_user_nickname = None to_user_id = None to_user_nickname = None other_user_id = None other_user_nickname = None my_msg = False self_display_name = None is_group = False is_at = False actual_user_id = None actual_user_nickname = None at_list = None _prepare_fn = None _prepared = False _rawmsg = None def __init__(self, _rawmsg): self._rawmsg = _rawmsg def prepare(self): if self._prepare_fn and not self._prepared: self._prepared = True self._prepare_fn() def __str__(self): return "ChatMessage: id={}, create_time={}, ctype={}, content={}, from_user_id={}, from_user_nickname={}, to_user_id={}, to_user_nickname={}, other_user_id={}, other_user_nickname={}, is_group={}, is_at={}, actual_user_id={}, actual_user_nickname={}, at_list={}".format( self.msg_id, self.create_time, self.ctype, self.content, self.from_user_id, self.from_user_nickname, self.to_user_id, self.to_user_nickname, self.other_user_id, self.other_user_nickname, self.is_group, self.is_at, self.actual_user_id, self.actual_user_nickname, self.at_list )
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/dingtalk/dingtalk_channel.py
Python
""" 钉钉通道接入 @author huiwen @Date 2023/11/28 """ import copy import json # -*- coding=utf-8 -*- import logging import os import time import requests import dingtalk_stream from dingtalk_stream import AckMessage from dingtalk_stream.card_replier import AICardReplier from dingtalk_stream.card_replier import AICardStatus from dingtalk_stream.card_replier import CardReplier from bridge.context import Context, ContextType from bridge.reply import Reply, ReplyType from channel.chat_channel import ChatChannel from common.utils import expand_path from channel.dingtalk.dingtalk_message import DingTalkMessage from common.expired_dict import ExpiredDict from common.log import logger from common.singleton import singleton from common.time_check import time_checker from config import conf class CustomAICardReplier(CardReplier): def __init__(self, dingtalk_client, incoming_message): super(AICardReplier, self).__init__(dingtalk_client, incoming_message) def start( self, card_template_id: str, card_data: dict, recipients: list = None, support_forward: bool = True, ) -> str: """ AI卡片的创建接口 :param support_forward: :param recipients: :param card_template_id: :param card_data: :return: """ card_data_with_status = copy.deepcopy(card_data) card_data_with_status["flowStatus"] = AICardStatus.PROCESSING return self.create_and_send_card( card_template_id, card_data_with_status, at_sender=True, at_all=False, recipients=recipients, support_forward=support_forward, ) # 对 AICardReplier 进行猴子补丁 AICardReplier.start = CustomAICardReplier.start def _check(func): def wrapper(self, cmsg: DingTalkMessage): msgId = cmsg.msg_id if msgId in self.receivedMsgs: logger.info("DingTalk message {} already received, ignore".format(msgId)) return self.receivedMsgs[msgId] = True create_time = cmsg.create_time # 消息时间戳 if conf().get("hot_reload") == True and int(create_time) < int(time.time()) - 60: # 跳过1分钟前的历史消息 logger.debug("[DingTalk] History message {} skipped".format(msgId)) return if cmsg.my_msg and not cmsg.is_group: logger.debug("[DingTalk] My message {} skipped".format(msgId)) return return func(self, cmsg) return wrapper @singleton class DingTalkChanel(ChatChannel, dingtalk_stream.ChatbotHandler): dingtalk_client_id = conf().get('dingtalk_client_id') dingtalk_client_secret = conf().get('dingtalk_client_secret') def setup_logger(self): logger = logging.getLogger() handler = logging.StreamHandler() handler.setFormatter( logging.Formatter('%(asctime)s %(name)-8s %(levelname)-8s %(message)s [%(filename)s:%(lineno)d]')) logger.addHandler(handler) logger.setLevel(logging.INFO) return logger def __init__(self): super().__init__() super(dingtalk_stream.ChatbotHandler, self).__init__() self.logger = self.setup_logger() # 历史消息id暂存,用于幂等控制 self.receivedMsgs = ExpiredDict(conf().get("expires_in_seconds", 3600)) logger.debug("[DingTalk] client_id={}, client_secret={} ".format( self.dingtalk_client_id, self.dingtalk_client_secret)) # 无需群校验和前缀 conf()["group_name_white_list"] = ["ALL_GROUP"] # 单聊无需前缀 conf()["single_chat_prefix"] = [""] # Access token cache self._access_token = None self._access_token_expires_at = 0 # Robot code cache (extracted from incoming messages) self._robot_code = None def startup(self): credential = dingtalk_stream.Credential(self.dingtalk_client_id, self.dingtalk_client_secret) client = dingtalk_stream.DingTalkStreamClient(credential) client.register_callback_handler(dingtalk_stream.chatbot.ChatbotMessage.TOPIC, self) logger.info("[DingTalk] ✅ Stream connected, ready to receive messages") client.start_forever() def get_access_token(self): """ 获取企业内部应用的 access_token 文档: https://open.dingtalk.com/document/orgapp/obtain-orgapp-token """ current_time = time.time() # 如果 token 还没过期,直接返回缓存的 token if self._access_token and current_time < self._access_token_expires_at: return self._access_token # 获取新的 access_token url = "https://api.dingtalk.com/v1.0/oauth2/accessToken" headers = {"Content-Type": "application/json"} data = { "appKey": self.dingtalk_client_id, "appSecret": self.dingtalk_client_secret } try: response = requests.post(url, headers=headers, json=data, timeout=10) result = response.json() if response.status_code == 200 and "accessToken" in result: self._access_token = result["accessToken"] # Token 有效期为 2 小时,提前 5 分钟刷新 self._access_token_expires_at = current_time + result.get("expireIn", 7200) - 300 logger.info("[DingTalk] Access token refreshed successfully") return self._access_token else: logger.error(f"[DingTalk] Failed to get access token: {result}") return None except Exception as e: logger.error(f"[DingTalk] Error getting access token: {e}") return None def send_single_message(self, user_id: str, content: str, robot_code: str) -> bool: """ Send message to single user (private chat) API: https://open.dingtalk.com/document/orgapp/chatbots-send-one-on-one-chat-messages-in-batches """ access_token = self.get_access_token() if not access_token: logger.error("[DingTalk] Failed to send single message: Access token not available.") return False if not robot_code: logger.error("[DingTalk] Cannot send single message: robot_code is required") return False url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend" headers = { "x-acs-dingtalk-access-token": access_token, "Content-Type": "application/json" } data = { "msgParam": json.dumps({"content": content}), "msgKey": "sampleText", "userIds": [user_id], "robotCode": robot_code } logger.info(f"[DingTalk] Sending single message to user {user_id} with robot_code {robot_code}") try: response = requests.post(url, headers=headers, json=data, timeout=10) result = response.json() if response.status_code == 200 and result.get("processQueryKey"): logger.info(f"[DingTalk] Single message sent successfully to {user_id}") return True else: logger.error(f"[DingTalk] Failed to send single message: {result}") return False except Exception as e: logger.error(f"[DingTalk] Error sending single message: {e}") return False def send_group_message(self, conversation_id: str, content: str, robot_code: str = None): """ 主动发送群消息 文档: https://open.dingtalk.com/document/orgapp/the-robot-sends-a-group-message Args: conversation_id: 会话ID (openConversationId) content: 消息内容 robot_code: 机器人编码,默认使用 dingtalk_client_id """ access_token = self.get_access_token() if not access_token: logger.error("[DingTalk] Cannot send group message: no access token") return False # Validate robot_code if not robot_code: logger.error("[DingTalk] Cannot send group message: robot_code is required") return False url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send" headers = { "x-acs-dingtalk-access-token": access_token, "Content-Type": "application/json" } data = { "msgParam": json.dumps({"content": content}), "msgKey": "sampleText", "openConversationId": conversation_id, "robotCode": robot_code } try: response = requests.post(url, headers=headers, json=data, timeout=10) result = response.json() if response.status_code == 200: logger.info(f"[DingTalk] Group message sent successfully to {conversation_id}") return True else: logger.error(f"[DingTalk] Failed to send group message: {result}") return False except Exception as e: logger.error(f"[DingTalk] Error sending group message: {e}") return False def upload_media(self, file_path: str, media_type: str = "image") -> str: """ 上传媒体文件到钉钉 Args: file_path: 本地文件路径或URL media_type: 媒体类型 (image, video, voice, file) Returns: media_id,如果上传失败返回 None """ access_token = self.get_access_token() if not access_token: logger.error("[DingTalk] Cannot upload media: no access token") return None # 处理 file:// URL if file_path.startswith("file://"): file_path = file_path[7:] # 如果是 HTTP URL,先下载 if file_path.startswith("http://") or file_path.startswith("https://"): try: import uuid response = requests.get(file_path, timeout=(5, 60)) if response.status_code != 200: logger.error(f"[DingTalk] Failed to download file from URL: {file_path}") return None # 保存到临时文件 file_name = os.path.basename(file_path) or f"media_{uuid.uuid4()}" workspace_root = expand_path(conf().get("agent_workspace", "~/cow")) tmp_dir = os.path.join(workspace_root, "tmp") os.makedirs(tmp_dir, exist_ok=True) temp_file = os.path.join(tmp_dir, file_name) with open(temp_file, "wb") as f: f.write(response.content) file_path = temp_file logger.info(f"[DingTalk] Downloaded file to {file_path}") except Exception as e: logger.error(f"[DingTalk] Error downloading file: {e}") return None if not os.path.exists(file_path): logger.error(f"[DingTalk] File not found: {file_path}") return None # 上传到钉钉 # 钉钉上传媒体文件 API: https://open.dingtalk.com/document/orgapp/upload-media-files url = "https://oapi.dingtalk.com/media/upload" params = { "access_token": access_token, "type": media_type } try: with open(file_path, "rb") as f: files = {"media": (os.path.basename(file_path), f)} response = requests.post(url, params=params, files=files, timeout=(5, 60)) result = response.json() if result.get("errcode") == 0: media_id = result.get("media_id") logger.info(f"[DingTalk] Media uploaded successfully, media_id={media_id}") return media_id else: logger.error(f"[DingTalk] Failed to upload media: {result}") return None except Exception as e: logger.error(f"[DingTalk] Error uploading media: {e}") return None def send_image_with_media_id(self, access_token: str, media_id: str, incoming_message, is_group: bool) -> bool: """ 发送图片消息(使用 media_id) Args: access_token: 访问令牌 media_id: 媒体ID incoming_message: 钉钉消息对象 is_group: 是否为群聊 Returns: 是否发送成功 """ headers = { "x-acs-dingtalk-access-token": access_token, 'Content-Type': 'application/json' } msg_param = { "photoURL": media_id # 钉钉图片消息使用 photoURL 字段 } body = { "robotCode": incoming_message.robot_code, "msgKey": "sampleImageMsg", "msgParam": json.dumps(msg_param), } if is_group: # 群聊 url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send" body["openConversationId"] = incoming_message.conversation_id else: # 单聊 url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend" body["userIds"] = [incoming_message.sender_staff_id] try: response = requests.post(url=url, headers=headers, json=body, timeout=10) result = response.json() logger.info(f"[DingTalk] Image send result: {response.text}") if response.status_code == 200: return True else: logger.error(f"[DingTalk] Send image error: {response.text}") return False except Exception as e: logger.error(f"[DingTalk] Send image exception: {e}") return False def send_image_message(self, receiver: str, media_id: str, is_group: bool, robot_code: str) -> bool: """ 发送图片消息 Args: receiver: 接收者ID (user_id 或 conversation_id) media_id: 媒体ID is_group: 是否为群聊 robot_code: 机器人编码 Returns: 是否发送成功 """ access_token = self.get_access_token() if not access_token: logger.error("[DingTalk] Cannot send image: no access token") return False if not robot_code: logger.error("[DingTalk] Cannot send image: robot_code is required") return False if is_group: # 发送群聊图片 url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send" headers = { "x-acs-dingtalk-access-token": access_token, "Content-Type": "application/json" } data = { "msgParam": json.dumps({"mediaId": media_id}), "msgKey": "sampleImageMsg", "openConversationId": receiver, "robotCode": robot_code } else: # 发送单聊图片 url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend" headers = { "x-acs-dingtalk-access-token": access_token, "Content-Type": "application/json" } data = { "msgParam": json.dumps({"mediaId": media_id}), "msgKey": "sampleImageMsg", "userIds": [receiver], "robotCode": robot_code } try: response = requests.post(url, headers=headers, json=data, timeout=10) result = response.json() if response.status_code == 200: logger.info(f"[DingTalk] Image message sent successfully") return True else: logger.error(f"[DingTalk] Failed to send image message: {result}") return False except Exception as e: logger.error(f"[DingTalk] Error sending image message: {e}") return False def get_image_download_url(self, download_code: str) -> str: """ 获取图片下载地址 返回一个特殊的 URL 格式:dingtalk://download/{robot_code}:{download_code} 后续会在 download_image_file 中使用新版 API 下载 """ # 获取 robot_code if not hasattr(self, '_robot_code_cache'): self._robot_code_cache = None robot_code = self._robot_code_cache if not robot_code: logger.error("[DingTalk] robot_code not available for image download") return None # 返回一个特殊的 URL,包含 robot_code 和 download_code logger.info(f"[DingTalk] Successfully got image download URL for code: {download_code}") return f"dingtalk://download/{robot_code}:{download_code}" async def process(self, callback: dingtalk_stream.CallbackMessage): try: incoming_message = dingtalk_stream.ChatbotMessage.from_dict(callback.data) # 缓存 robot_code,用于后续图片下载 if hasattr(incoming_message, 'robot_code'): self._robot_code_cache = incoming_message.robot_code # Debug: 打印完整的 event 数据 logger.debug(f"[DingTalk] ===== Incoming Message Debug =====") logger.debug(f"[DingTalk] callback.data keys: {callback.data.keys() if hasattr(callback.data, 'keys') else 'N/A'}") logger.debug(f"[DingTalk] incoming_message attributes: {dir(incoming_message)}") logger.debug(f"[DingTalk] robot_code: {getattr(incoming_message, 'robot_code', 'N/A')}") logger.debug(f"[DingTalk] chatbot_corp_id: {getattr(incoming_message, 'chatbot_corp_id', 'N/A')}") logger.debug(f"[DingTalk] chatbot_user_id: {getattr(incoming_message, 'chatbot_user_id', 'N/A')}") logger.debug(f"[DingTalk] conversation_id: {getattr(incoming_message, 'conversation_id', 'N/A')}") logger.debug(f"[DingTalk] Raw callback.data: {callback.data}") logger.debug(f"[DingTalk] =====================================") image_download_handler = self # 传入方法所在的类实例 dingtalk_msg = DingTalkMessage(incoming_message, image_download_handler) if dingtalk_msg.is_group: self.handle_group(dingtalk_msg) else: self.handle_single(dingtalk_msg) return AckMessage.STATUS_OK, 'OK' except Exception as e: logger.error(f"[DingTalk] process error: {e}") logger.exception(e) # 打印完整堆栈跟踪 return AckMessage.STATUS_SYSTEM_EXCEPTION, 'ERROR' @time_checker @_check def handle_single(self, cmsg: DingTalkMessage): # 处理单聊消息 if cmsg.ctype == ContextType.VOICE: logger.debug("[DingTalk]receive voice msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.IMAGE: logger.debug("[DingTalk]receive image msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.IMAGE_CREATE: logger.debug("[DingTalk]receive image create msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.PATPAT: logger.debug("[DingTalk]receive patpat msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.TEXT: logger.debug("[DingTalk]receive text msg: {}".format(cmsg.content)) else: logger.debug("[DingTalk]receive other msg: {}".format(cmsg.content)) # 处理文件缓存逻辑 from channel.file_cache import get_file_cache file_cache = get_file_cache() # 单聊的 session_id 就是 sender_id session_id = cmsg.from_user_id # 如果是单张图片消息,缓存起来 if cmsg.ctype == ContextType.IMAGE: if hasattr(cmsg, 'image_path') and cmsg.image_path: file_cache.add(session_id, cmsg.image_path, file_type='image') logger.info(f"[DingTalk] Image cached for session {session_id}, waiting for user query...") # 单张图片不直接处理,等待用户提问 return # 如果是文本消息,检查是否有缓存的文件 if cmsg.ctype == ContextType.TEXT: cached_files = file_cache.get(session_id) if cached_files: # 将缓存的文件附加到文本消息中 file_refs = [] for file_info in cached_files: file_path = file_info['path'] file_type = file_info['type'] if file_type == 'image': file_refs.append(f"[图片: {file_path}]") elif file_type == 'video': file_refs.append(f"[视频: {file_path}]") else: file_refs.append(f"[文件: {file_path}]") cmsg.content = cmsg.content + "\n" + "\n".join(file_refs) logger.info(f"[DingTalk] Attached {len(cached_files)} cached file(s) to user query") # 清除缓存 file_cache.clear(session_id) context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=False, msg=cmsg) if context: self.produce(context) @time_checker @_check def handle_group(self, cmsg: DingTalkMessage): # 处理群聊消息 if cmsg.ctype == ContextType.VOICE: logger.debug("[DingTalk]receive voice msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.IMAGE: logger.debug("[DingTalk]receive image msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.IMAGE_CREATE: logger.debug("[DingTalk]receive image create msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.PATPAT: logger.debug("[DingTalk]receive patpat msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.TEXT: logger.debug("[DingTalk]receive text msg: {}".format(cmsg.content)) else: logger.debug("[DingTalk]receive other msg: {}".format(cmsg.content)) # 处理文件缓存逻辑 from channel.file_cache import get_file_cache file_cache = get_file_cache() # 群聊的 session_id if conf().get("group_shared_session", True): session_id = cmsg.other_user_id # conversation_id else: session_id = cmsg.from_user_id + "_" + cmsg.other_user_id # 如果是单张图片消息,缓存起来 if cmsg.ctype == ContextType.IMAGE: if hasattr(cmsg, 'image_path') and cmsg.image_path: file_cache.add(session_id, cmsg.image_path, file_type='image') logger.info(f"[DingTalk] Image cached for session {session_id}, waiting for user query...") # 单张图片不直接处理,等待用户提问 return # 如果是文本消息,检查是否有缓存的文件 if cmsg.ctype == ContextType.TEXT: cached_files = file_cache.get(session_id) if cached_files: # 将缓存的文件附加到文本消息中 file_refs = [] for file_info in cached_files: file_path = file_info['path'] file_type = file_info['type'] if file_type == 'image': file_refs.append(f"[图片: {file_path}]") elif file_type == 'video': file_refs.append(f"[视频: {file_path}]") else: file_refs.append(f"[文件: {file_path}]") cmsg.content = cmsg.content + "\n" + "\n".join(file_refs) logger.info(f"[DingTalk] Attached {len(cached_files)} cached file(s) to user query") # 清除缓存 file_cache.clear(session_id) context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=True, msg=cmsg) context['no_need_at'] = True if context: self.produce(context) def send(self, reply: Reply, context: Context): logger.debug(f"[DingTalk] send() called with reply.type={reply.type}, content_length={len(str(reply.content))}") receiver = context["receiver"] # Check if msg exists (for scheduled tasks, msg might be None) msg = context.kwargs.get('msg') if msg is None: # 定时任务场景:使用主动发送 API is_group = context.get("isgroup", False) logger.info(f"[DingTalk] Sending scheduled task message to {receiver} (is_group={is_group})") # 使用缓存的 robot_code 或配置的值 robot_code = self._robot_code or conf().get("dingtalk_robot_code") logger.info(f"[DingTalk] Using robot_code: {robot_code}, cached: {self._robot_code}, config: {conf().get('dingtalk_robot_code')}") if not robot_code: logger.error(f"[DingTalk] Cannot send scheduled task: robot_code not available. Please send at least one message to the bot first, or configure dingtalk_robot_code in config.json") return # 根据是否群聊选择不同的 API if is_group: success = self.send_group_message(receiver, reply.content, robot_code) else: # 单聊场景:尝试从 context 中获取 dingtalk_sender_staff_id sender_staff_id = context.get("dingtalk_sender_staff_id") if not sender_staff_id: logger.error(f"[DingTalk] Cannot send single chat scheduled message: sender_staff_id not available in context") return logger.info(f"[DingTalk] Sending single message to staff_id: {sender_staff_id}") success = self.send_single_message(sender_staff_id, reply.content, robot_code) if not success: logger.error(f"[DingTalk] Failed to send scheduled task message") return # 从正常消息中提取并缓存 robot_code if hasattr(msg, 'robot_code'): robot_code = msg.robot_code if robot_code and robot_code != self._robot_code: self._robot_code = robot_code logger.debug(f"[DingTalk] Cached robot_code: {robot_code}") isgroup = msg.is_group incoming_message = msg.incoming_message robot_code = self._robot_code or conf().get("dingtalk_robot_code") # 处理图片和视频发送 if reply.type == ReplyType.IMAGE_URL: logger.info(f"[DingTalk] Sending image: {reply.content}") # 如果有附加的文本内容,先发送文本 if hasattr(reply, 'text_content') and reply.text_content: self.reply_text(reply.text_content, incoming_message) import time time.sleep(0.3) # 短暂延迟,确保文本先到达 media_id = self.upload_media(reply.content, media_type="image") if media_id: # 使用主动发送 API 发送图片 access_token = self.get_access_token() if access_token: success = self.send_image_with_media_id( access_token, media_id, incoming_message, isgroup ) if not success: logger.error("[DingTalk] Failed to send image message") self.reply_text("抱歉,图片发送失败", incoming_message) else: logger.error("[DingTalk] Cannot get access token") self.reply_text("抱歉,图片发送失败(无法获取token)", incoming_message) else: logger.error("[DingTalk] Failed to upload image") self.reply_text("抱歉,图片上传失败", incoming_message) return elif reply.type == ReplyType.FILE: # 如果有附加的文本内容,先发送文本 if hasattr(reply, 'text_content') and reply.text_content: self.reply_text(reply.text_content, incoming_message) import time time.sleep(0.3) # 短暂延迟,确保文本先到达 # 判断是否为视频文件 file_path = reply.content if file_path.startswith("file://"): file_path = file_path[7:] is_video = file_path.lower().endswith(('.mp4', '.avi', '.mov', '.wmv', '.flv')) access_token = self.get_access_token() if not access_token: logger.error("[DingTalk] Cannot get access token") self.reply_text("抱歉,文件发送失败(无法获取token)", incoming_message) return if is_video: logger.info(f"[DingTalk] Sending video: {reply.content}") media_id = self.upload_media(reply.content, media_type="video") if media_id: # 发送视频消息 msg_param = { "duration": "30", # TODO: 获取实际视频时长 "videoMediaId": media_id, "videoType": "mp4", "height": "400", "width": "600", } success = self._send_file_message( access_token, incoming_message, "sampleVideo", msg_param, isgroup ) if not success: self.reply_text("抱歉,视频发送失败", incoming_message) else: logger.error("[DingTalk] Failed to upload video") self.reply_text("抱歉,视频上传失败", incoming_message) else: # 其他文件类型 logger.info(f"[DingTalk] Sending file: {reply.content}") media_id = self.upload_media(reply.content, media_type="file") if media_id: file_name = os.path.basename(file_path) file_base, file_extension = os.path.splitext(file_name) msg_param = { "mediaId": media_id, "fileName": file_name, "fileType": file_extension[1:] if file_extension else "file" } success = self._send_file_message( access_token, incoming_message, "sampleFile", msg_param, isgroup ) if not success: self.reply_text("抱歉,文件发送失败", incoming_message) else: logger.error("[DingTalk] Failed to upload file") self.reply_text("抱歉,文件上传失败", incoming_message) return # 处理文本消息 elif reply.type == ReplyType.TEXT: logger.info(f"[DingTalk] Sending text message, length={len(reply.content)}") if conf().get("dingtalk_card_enabled"): logger.info("[Dingtalk] sendMsg={}, receiver={}".format(reply, receiver)) def reply_with_text(): self.reply_text(reply.content, incoming_message) def reply_with_at_text(): self.reply_text("📢 您有一条新的消息,请查看。", incoming_message) def reply_with_ai_markdown(): button_list, markdown_content = self.generate_button_markdown_content(context, reply) self.reply_ai_markdown_button(incoming_message, markdown_content, button_list, "", "📌 内容由AI生成", "",[incoming_message.sender_staff_id]) if reply.type in [ReplyType.IMAGE_URL, ReplyType.IMAGE, ReplyType.TEXT]: if isgroup: reply_with_ai_markdown() reply_with_at_text() else: reply_with_ai_markdown() else: # 暂不支持其它类型消息回复 reply_with_text() else: self.reply_text(reply.content, incoming_message) return def _send_file_message(self, access_token: str, incoming_message, msg_key: str, msg_param: dict, is_group: bool) -> bool: """ 发送文件/视频消息的通用方法 Args: access_token: 访问令牌 incoming_message: 钉钉消息对象 msg_key: 消息类型 (sampleFile, sampleVideo, sampleAudio) msg_param: 消息参数 is_group: 是否为群聊 Returns: 是否发送成功 """ headers = { "x-acs-dingtalk-access-token": access_token, 'Content-Type': 'application/json' } body = { "robotCode": incoming_message.robot_code, "msgKey": msg_key, "msgParam": json.dumps(msg_param), } if is_group: # 群聊 url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send" body["openConversationId"] = incoming_message.conversation_id else: # 单聊 url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend" body["userIds"] = [incoming_message.sender_staff_id] try: response = requests.post(url=url, headers=headers, json=body, timeout=10) result = response.json() logger.info(f"[DingTalk] File send result: {response.text}") if response.status_code == 200: return True else: logger.error(f"[DingTalk] Send file error: {response.text}") return False except Exception as e: logger.error(f"[DingTalk] Send file exception: {e}") return False def generate_button_markdown_content(self, context, reply): image_url = context.kwargs.get("image_url") promptEn = context.kwargs.get("promptEn") reply_text = reply.content button_list = [] markdown_content = f""" {reply.content} """ if image_url is not None and promptEn is not None: button_list = [ {"text": "查看原图", "url": image_url, "iosUrl": image_url, "color": "blue"} ] markdown_content = f""" {promptEn} !["图片"]({image_url}) {reply_text} """ logger.debug(f"[Dingtalk] generate_button_markdown_content, button_list={button_list} , markdown_content={markdown_content}") return button_list, markdown_content
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/dingtalk/dingtalk_message.py
Python
import os import re import requests from dingtalk_stream import ChatbotMessage from bridge.context import ContextType from channel.chat_message import ChatMessage # -*- coding=utf-8 -*- from common.log import logger from common.tmp_dir import TmpDir from common.utils import expand_path from config import conf class DingTalkMessage(ChatMessage): def __init__(self, event: ChatbotMessage, image_download_handler): super().__init__(event) self.image_download_handler = image_download_handler self.msg_id = event.message_id self.message_type = event.message_type self.incoming_message = event self.sender_staff_id = event.sender_staff_id self.other_user_id = event.conversation_id self.create_time = event.create_at self.image_content = event.image_content self.rich_text_content = event.rich_text_content self.robot_code = event.robot_code # 机器人编码 if event.conversation_type == "1": self.is_group = False else: self.is_group = True if self.message_type == "text": self.ctype = ContextType.TEXT self.content = event.text.content.strip() elif self.message_type == "audio": # 钉钉支持直接识别语音,所以此处将直接提取文字,当文字处理 self.content = event.extensions['content']['recognition'].strip() self.ctype = ContextType.TEXT elif (self.message_type == 'picture') or (self.message_type == 'richText'): # 钉钉图片类型或富文本类型消息处理 image_list = event.get_image_list() if self.message_type == 'picture' and len(image_list) > 0: # 单张图片消息:下载到工作空间,用于文件缓存 self.ctype = ContextType.IMAGE download_code = image_list[0] download_url = image_download_handler.get_image_download_url(download_code) # 下载到工作空间 tmp 目录 workspace_root = expand_path(conf().get("agent_workspace", "~/cow")) tmp_dir = os.path.join(workspace_root, "tmp") os.makedirs(tmp_dir, exist_ok=True) image_path = download_image_file(download_url, tmp_dir) if image_path: self.content = image_path self.image_path = image_path # 保存图片路径用于缓存 logger.info(f"[DingTalk] Downloaded single image to {image_path}") else: self.content = "[图片下载失败]" self.image_path = None elif self.message_type == 'richText' and len(image_list) > 0: # 富文本消息:下载所有图片并附加到文本中 self.ctype = ContextType.TEXT # 下载到工作空间 tmp 目录 workspace_root = expand_path(conf().get("agent_workspace", "~/cow")) tmp_dir = os.path.join(workspace_root, "tmp") os.makedirs(tmp_dir, exist_ok=True) # 提取富文本中的文本内容 text_content = "" if self.rich_text_content: # rich_text_content 是一个 RichTextContent 对象,需要从中提取文本 text_list = event.get_text_list() if text_list: text_content = "".join(text_list).strip() # 下载所有图片 image_paths = [] for download_code in image_list: download_url = image_download_handler.get_image_download_url(download_code) image_path = download_image_file(download_url, tmp_dir) if image_path: image_paths.append(image_path) # 构建消息内容:文本 + 图片路径 content_parts = [] if text_content: content_parts.append(text_content) for img_path in image_paths: content_parts.append(f"[图片: {img_path}]") self.content = "\n".join(content_parts) if content_parts else "[富文本消息]" logger.info(f"[DingTalk] Received richText with {len(image_paths)} image(s): {self.content}") else: self.ctype = ContextType.IMAGE self.content = "[未找到图片]" logger.debug(f"[DingTalk] messageType: {self.message_type}, imageList isEmpty") if self.is_group: self.from_user_id = event.conversation_id self.actual_user_id = event.sender_id self.is_at = True else: self.from_user_id = event.sender_id self.actual_user_id = event.sender_id self.to_user_id = event.chatbot_user_id self.other_user_nickname = event.conversation_title def download_image_file(image_url, temp_dir): """ 下载图片文件 支持两种方式: 1. 普通 HTTP(S) URL 2. 钉钉 downloadCode: dingtalk://download/{download_code} """ # 检查临时目录是否存在,如果不存在则创建 if not os.path.exists(temp_dir): os.makedirs(temp_dir) # 处理钉钉 downloadCode if image_url.startswith("dingtalk://download/"): download_code = image_url.replace("dingtalk://download/", "") logger.info(f"[DingTalk] Downloading image with downloadCode: {download_code[:20]}...") # 需要从外部传入 access_token,这里先用一个临时方案 # 从 config 获取 dingtalk_client_id 和 dingtalk_client_secret from config import conf client_id = conf().get("dingtalk_client_id") client_secret = conf().get("dingtalk_client_secret") if not client_id or not client_secret: logger.error("[DingTalk] Missing dingtalk_client_id or dingtalk_client_secret") return None # 解析 robot_code 和 download_code parts = download_code.split(":", 1) if len(parts) != 2: logger.error(f"[DingTalk] Invalid download_code format (expected robot_code:download_code): {download_code[:50]}") return None robot_code, actual_download_code = parts # 获取 access_token(使用新版 API) token_url = "https://api.dingtalk.com/v1.0/oauth2/accessToken" token_headers = { "Content-Type": "application/json" } token_body = { "appKey": client_id, "appSecret": client_secret } try: token_response = requests.post(token_url, json=token_body, headers=token_headers, timeout=10) if token_response.status_code == 200: token_data = token_response.json() access_token = token_data.get("accessToken") if not access_token: logger.error(f"[DingTalk] Failed to get access token: {token_data}") return None # 获取下载 URL(使用新版 API) download_api_url = "https://api.dingtalk.com/v1.0/robot/messageFiles/download" download_headers = { "x-acs-dingtalk-access-token": access_token, "Content-Type": "application/json" } download_body = { "downloadCode": actual_download_code, "robotCode": robot_code } download_response = requests.post(download_api_url, json=download_body, headers=download_headers, timeout=10) if download_response.status_code == 200: download_data = download_response.json() download_url = download_data.get("downloadUrl") if not download_url: logger.error(f"[DingTalk] No downloadUrl in response: {download_data}") return None # 从 downloadUrl 下载实际图片 image_response = requests.get(download_url, stream=True, timeout=60) if image_response.status_code == 200: # 生成文件名(使用 download_code 的 hash,避免特殊字符) import hashlib file_hash = hashlib.md5(actual_download_code.encode()).hexdigest()[:16] file_name = f"{file_hash}.png" file_path = os.path.join(temp_dir, file_name) with open(file_path, 'wb') as file: file.write(image_response.content) logger.info(f"[DingTalk] Image downloaded successfully: {file_path}") return file_path else: logger.error(f"[DingTalk] Failed to download image from URL: {image_response.status_code}") return None else: logger.error(f"[DingTalk] Failed to get download URL: {download_response.status_code}, {download_response.text}") return None else: logger.error(f"[DingTalk] Failed to get access token: {token_response.status_code}, {token_response.text}") return None except Exception as e: logger.error(f"[DingTalk] Exception downloading image: {e}") import traceback logger.error(traceback.format_exc()) return None # 普通 HTTP(S) URL else: headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36' } try: response = requests.get(image_url, headers=headers, stream=True, timeout=60 * 5) if response.status_code == 200: # 生成文件名 file_name = image_url.split("/")[-1].split("?")[0] # 将文件保存到临时目录 file_path = os.path.join(temp_dir, file_name) with open(file_path, 'wb') as file: file.write(response.content) return file_path else: logger.info(f"[Dingtalk] Failed to download image file, {response.content}") return None except Exception as e: logger.error(f"[Dingtalk] Exception downloading image: {e}") return None
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/feishu/feishu_channel.py
Python
""" 飞书通道接入 支持两种事件接收模式: 1. webhook模式: 通过HTTP服务器接收事件(需要公网IP) 2. websocket模式: 通过长连接接收事件(本地开发友好) 通过配置项 feishu_event_mode 选择模式: "webhook" 或 "websocket" @author Saboteur7 @Date 2023/11/19 """ import json import os import ssl import threading # -*- coding=utf-8 -*- import uuid import requests import web from bridge.context import Context from bridge.context import ContextType from bridge.reply import Reply, ReplyType from channel.chat_channel import ChatChannel, check_prefix from channel.feishu.feishu_message import FeishuMessage from common import utils from common.expired_dict import ExpiredDict from common.log import logger from common.singleton import singleton from config import conf URL_VERIFICATION = "url_verification" # 尝试导入飞书SDK,如果未安装则websocket模式不可用 try: import lark_oapi as lark LARK_SDK_AVAILABLE = True except ImportError: LARK_SDK_AVAILABLE = False logger.warning( "[FeiShu] lark_oapi not installed, websocket mode is not available. Install with: pip install lark-oapi") @singleton class FeiShuChanel(ChatChannel): feishu_app_id = conf().get('feishu_app_id') feishu_app_secret = conf().get('feishu_app_secret') feishu_token = conf().get('feishu_token') feishu_event_mode = conf().get('feishu_event_mode', 'websocket') # webhook 或 websocket def __init__(self): super().__init__() # 历史消息id暂存,用于幂等控制 self.receivedMsgs = ExpiredDict(60 * 60 * 7.1) logger.debug("[FeiShu] app_id={}, app_secret={}, verification_token={}, event_mode={}".format( self.feishu_app_id, self.feishu_app_secret, self.feishu_token, self.feishu_event_mode)) # 无需群校验和前缀 conf()["group_name_white_list"] = ["ALL_GROUP"] conf()["single_chat_prefix"] = [""] # 验证配置 if self.feishu_event_mode == 'websocket' and not LARK_SDK_AVAILABLE: logger.error("[FeiShu] websocket mode requires lark_oapi. Please install: pip install lark-oapi") raise Exception("lark_oapi not installed") def startup(self): if self.feishu_event_mode == 'websocket': self._startup_websocket() else: self._startup_webhook() def _startup_webhook(self): """启动HTTP服务器接收事件(webhook模式)""" logger.debug("[FeiShu] Starting in webhook mode...") urls = ( '/', 'channel.feishu.feishu_channel.FeishuController' ) app = web.application(urls, globals(), autoreload=False) port = conf().get("feishu_port", 9891) web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", port)) def _startup_websocket(self): """启动长连接接收事件(websocket模式)""" logger.debug("[FeiShu] Starting in websocket mode...") # 创建事件处理器 def handle_message_event(data: lark.im.v1.P2ImMessageReceiveV1) -> None: """处理接收消息事件 v2.0""" try: logger.debug(f"[FeiShu] websocket receive event: {lark.JSON.marshal(data, indent=2)}") # 转换为标准的event格式 event_dict = json.loads(lark.JSON.marshal(data)) event = event_dict.get("event", {}) # 处理消息 self._handle_message_event(event) except Exception as e: logger.error(f"[FeiShu] websocket handle message error: {e}", exc_info=True) # 构建事件分发器 event_handler = lark.EventDispatcherHandler.builder("", "") \ .register_p2_im_message_receive_v1(handle_message_event) \ .build() # 尝试连接,如果遇到SSL错误则自动禁用证书验证 def start_client_with_retry(): """启动websocket客户端,自动处理SSL证书错误""" # 全局禁用SSL证书验证(在导入lark_oapi之前设置) import ssl as ssl_module # 保存原始的SSL上下文创建方法 original_create_default_context = ssl_module.create_default_context def create_unverified_context(*args, **kwargs): """创建一个不验证证书的SSL上下文""" context = original_create_default_context(*args, **kwargs) context.check_hostname = False context.verify_mode = ssl.CERT_NONE return context # 尝试正常连接,如果失败则禁用SSL验证 for attempt in range(2): try: if attempt == 1: # 第二次尝试:禁用SSL验证 logger.warning("[FeiShu] SSL certificate verification disabled due to certificate error. " "This may happen when using corporate proxy or self-signed certificates.") ssl_module.create_default_context = create_unverified_context ssl_module._create_unverified_context = create_unverified_context ws_client = lark.ws.Client( self.feishu_app_id, self.feishu_app_secret, event_handler=event_handler, log_level=lark.LogLevel.DEBUG if conf().get("debug") else lark.LogLevel.INFO ) logger.debug("[FeiShu] Websocket client starting...") ws_client.start() # 如果成功启动,跳出循环 break except Exception as e: error_msg = str(e) # 检查是否是SSL证书验证错误 is_ssl_error = "CERTIFICATE_VERIFY_FAILED" in error_msg or "certificate verify failed" in error_msg.lower() if is_ssl_error and attempt == 0: # 第一次遇到SSL错误,记录日志并继续循环(下次会禁用验证) logger.warning(f"[FeiShu] SSL certificate verification failed: {error_msg}") logger.info("[FeiShu] Retrying connection with SSL verification disabled...") continue else: # 其他错误或禁用验证后仍失败,抛出异常 logger.error(f"[FeiShu] Websocket client error: {e}", exc_info=True) # 恢复原始方法 ssl_module.create_default_context = original_create_default_context raise # 注意:不恢复原始方法,因为ws_client.start()会持续运行 # 在新线程中启动客户端,避免阻塞主线程 ws_thread = threading.Thread(target=start_client_with_retry, daemon=True) ws_thread.start() # 保持主线程运行 logger.info("[FeiShu] ✅ Websocket connected, ready to receive messages") ws_thread.join() def _handle_message_event(self, event: dict): """ 处理消息事件的核心逻辑 webhook和websocket模式共用此方法 """ if not event.get("message") or not event.get("sender"): logger.warning(f"[FeiShu] invalid message, event={event}") return msg = event.get("message") # 幂等判断 msg_id = msg.get("message_id") if self.receivedMsgs.get(msg_id): logger.warning(f"[FeiShu] repeat msg filtered, msg_id={msg_id}") return self.receivedMsgs[msg_id] = True is_group = False chat_type = msg.get("chat_type") if chat_type == "group": if not msg.get("mentions") and msg.get("message_type") == "text": # 群聊中未@不响应 return if msg.get("mentions") and msg.get("mentions")[0].get("name") != conf().get("feishu_bot_name") and msg.get( "message_type") == "text": # 不是@机器人,不响应 return # 群聊 is_group = True receive_id_type = "chat_id" elif chat_type == "p2p": receive_id_type = "open_id" else: logger.warning("[FeiShu] message ignore") return # 构造飞书消息对象 feishu_msg = FeishuMessage(event, is_group=is_group, access_token=self.fetch_access_token()) if not feishu_msg: return # 处理文件缓存逻辑 from channel.file_cache import get_file_cache file_cache = get_file_cache() # 获取 session_id(用于缓存关联) if is_group: if conf().get("group_shared_session", True): session_id = msg.get("chat_id") # 群共享会话 else: session_id = feishu_msg.from_user_id + "_" + msg.get("chat_id") else: session_id = feishu_msg.from_user_id # 如果是单张图片消息,缓存起来 if feishu_msg.ctype == ContextType.IMAGE: if hasattr(feishu_msg, 'image_path') and feishu_msg.image_path: file_cache.add(session_id, feishu_msg.image_path, file_type='image') logger.info(f"[FeiShu] Image cached for session {session_id}, waiting for user query...") # 单张图片不直接处理,等待用户提问 return # 如果是文本消息,检查是否有缓存的文件 if feishu_msg.ctype == ContextType.TEXT: cached_files = file_cache.get(session_id) if cached_files: # 将缓存的文件附加到文本消息中 file_refs = [] for file_info in cached_files: file_path = file_info['path'] file_type = file_info['type'] if file_type == 'image': file_refs.append(f"[图片: {file_path}]") elif file_type == 'video': file_refs.append(f"[视频: {file_path}]") else: file_refs.append(f"[文件: {file_path}]") feishu_msg.content = feishu_msg.content + "\n" + "\n".join(file_refs) logger.info(f"[FeiShu] Attached {len(cached_files)} cached file(s) to user query") # 清除缓存 file_cache.clear(session_id) context = self._compose_context( feishu_msg.ctype, feishu_msg.content, isgroup=is_group, msg=feishu_msg, receive_id_type=receive_id_type, no_need_at=True ) if context: self.produce(context) logger.debug(f"[FeiShu] query={feishu_msg.content}, type={feishu_msg.ctype}") def send(self, reply: Reply, context: Context): msg = context.get("msg") is_group = context["isgroup"] if msg: access_token = msg.access_token else: access_token = self.fetch_access_token() headers = { "Authorization": "Bearer " + access_token, "Content-Type": "application/json", } msg_type = "text" logger.debug(f"[FeiShu] sending reply, type={context.type}, content={reply.content[:100]}...") reply_content = reply.content content_key = "text" if reply.type == ReplyType.IMAGE_URL: # 图片上传 reply_content = self._upload_image_url(reply.content, access_token) if not reply_content: logger.warning("[FeiShu] upload image failed") return msg_type = "image" content_key = "image_key" elif reply.type == ReplyType.FILE: # 如果有附加的文本内容,先发送文本 if hasattr(reply, 'text_content') and reply.text_content: logger.info(f"[FeiShu] Sending text before file: {reply.text_content[:50]}...") text_reply = Reply(ReplyType.TEXT, reply.text_content) self._send(text_reply, context) import time time.sleep(0.3) # 短暂延迟,确保文本先到达 # 判断是否为视频文件 file_path = reply.content if file_path.startswith("file://"): file_path = file_path[7:] is_video = file_path.lower().endswith(('.mp4', '.avi', '.mov', '.wmv', '.flv')) if is_video: # 视频上传(包含duration信息) upload_data = self._upload_video_url(reply.content, access_token) if not upload_data or not upload_data.get('file_key'): logger.warning("[FeiShu] upload video failed") return # 视频使用 media 类型(根据官方文档) # 错误码 230055 说明:上传 mp4 时必须使用 msg_type="media" msg_type = "media" reply_content = upload_data # 完整的上传响应数据(包含file_key和duration) logger.info( f"[FeiShu] Sending video: file_key={upload_data.get('file_key')}, duration={upload_data.get('duration')}ms") content_key = None # 直接序列化整个对象 else: # 其他文件使用 file 类型 file_key = self._upload_file_url(reply.content, access_token) if not file_key: logger.warning("[FeiShu] upload file failed") return reply_content = file_key msg_type = "file" content_key = "file_key" # Check if we can reply to an existing message (need msg_id) can_reply = is_group and msg and hasattr(msg, 'msg_id') and msg.msg_id # Build content JSON content_json = json.dumps(reply_content) if content_key is None else json.dumps({content_key: reply_content}) logger.debug(f"[FeiShu] Sending message: msg_type={msg_type}, content={content_json[:200]}") if can_reply: # 群聊中回复已有消息 url = f"https://open.feishu.cn/open-apis/im/v1/messages/{msg.msg_id}/reply" data = { "msg_type": msg_type, "content": content_json } res = requests.post(url=url, headers=headers, json=data, timeout=(5, 10)) else: # 发送新消息(私聊或群聊中无msg_id的情况,如定时任务) url = "https://open.feishu.cn/open-apis/im/v1/messages" params = {"receive_id_type": context.get("receive_id_type") or "open_id"} data = { "receive_id": context.get("receiver"), "msg_type": msg_type, "content": content_json } res = requests.post(url=url, headers=headers, params=params, json=data, timeout=(5, 10)) res = res.json() if res.get("code") == 0: logger.info(f"[FeiShu] send message success") else: logger.error(f"[FeiShu] send message failed, code={res.get('code')}, msg={res.get('msg')}") def fetch_access_token(self) -> str: url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/" headers = { "Content-Type": "application/json" } req_body = { "app_id": self.feishu_app_id, "app_secret": self.feishu_app_secret } data = bytes(json.dumps(req_body), encoding='utf8') response = requests.post(url=url, data=data, headers=headers) if response.status_code == 200: res = response.json() if res.get("code") != 0: logger.error(f"[FeiShu] get tenant_access_token error, code={res.get('code')}, msg={res.get('msg')}") return "" else: return res.get("tenant_access_token") else: logger.error(f"[FeiShu] fetch token error, res={response}") def _upload_image_url(self, img_url, access_token): logger.debug(f"[FeiShu] start process image, img_url={img_url}") # Check if it's a local file path (file:// protocol) if img_url.startswith("file://"): local_path = img_url[7:] # Remove "file://" prefix logger.info(f"[FeiShu] uploading local file: {local_path}") if not os.path.exists(local_path): logger.error(f"[FeiShu] local file not found: {local_path}") return None # Upload directly from local file upload_url = "https://open.feishu.cn/open-apis/im/v1/images" data = {'image_type': 'message'} headers = {'Authorization': f'Bearer {access_token}'} with open(local_path, "rb") as file: upload_response = requests.post(upload_url, files={"image": file}, data=data, headers=headers) logger.info(f"[FeiShu] upload file, res={upload_response.content}") response_data = upload_response.json() if response_data.get("code") == 0: return response_data.get("data").get("image_key") else: logger.error(f"[FeiShu] upload failed: {response_data}") return None # Original logic for HTTP URLs response = requests.get(img_url) suffix = utils.get_path_suffix(img_url) temp_name = str(uuid.uuid4()) + "." + suffix if response.status_code == 200: # 将图片内容保存为临时文件 with open(temp_name, "wb") as file: file.write(response.content) # upload upload_url = "https://open.feishu.cn/open-apis/im/v1/images" data = { 'image_type': 'message' } headers = { 'Authorization': f'Bearer {access_token}', } with open(temp_name, "rb") as file: upload_response = requests.post(upload_url, files={"image": file}, data=data, headers=headers) logger.info(f"[FeiShu] upload file, res={upload_response.content}") os.remove(temp_name) return upload_response.json().get("data").get("image_key") def _get_video_duration(self, file_path: str) -> int: """ 获取视频时长(毫秒) Args: file_path: 视频文件路径 Returns: 视频时长(毫秒),如果获取失败返回0 """ try: import subprocess # 使用 ffprobe 获取视频时长 cmd = [ 'ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', file_path ] result = subprocess.run(cmd, capture_output=True, text=True, timeout=10) if result.returncode == 0: duration_seconds = float(result.stdout.strip()) duration_ms = int(duration_seconds * 1000) logger.info(f"[FeiShu] Video duration: {duration_seconds:.2f}s ({duration_ms}ms)") return duration_ms else: logger.warning(f"[FeiShu] Failed to get video duration via ffprobe: {result.stderr}") return 0 except FileNotFoundError: logger.warning("[FeiShu] ffprobe not found, video duration will be 0. Install ffmpeg to fix this.") return 0 except Exception as e: logger.warning(f"[FeiShu] Failed to get video duration: {e}") return 0 def _upload_video_url(self, video_url, access_token): """ Upload video to Feishu and return video info (file_key and duration) Supports: - file:// URLs for local files - http(s):// URLs (download then upload) Returns: dict with 'file_key' and 'duration' (milliseconds), or None if failed """ local_path = None temp_file = None try: # For file:// URLs (local files), upload directly if video_url.startswith("file://"): local_path = video_url[7:] # Remove file:// prefix if not os.path.exists(local_path): logger.error(f"[FeiShu] local video file not found: {local_path}") return None else: # For HTTP URLs, download first logger.info(f"[FeiShu] Downloading video from URL: {video_url}") response = requests.get(video_url, timeout=(5, 60)) if response.status_code != 200: logger.error(f"[FeiShu] download video failed, status={response.status_code}") return None # Save to temp file import uuid file_name = os.path.basename(video_url) or "video.mp4" temp_file = str(uuid.uuid4()) + "_" + file_name with open(temp_file, "wb") as file: file.write(response.content) logger.info(f"[FeiShu] Video downloaded, size={len(response.content)} bytes") local_path = temp_file # Get video duration duration = self._get_video_duration(local_path) # Upload to Feishu file_name = os.path.basename(local_path) file_ext = os.path.splitext(file_name)[1].lower() file_type_map = {'.mp4': 'mp4'} file_type = file_type_map.get(file_ext, 'mp4') upload_url = "https://open.feishu.cn/open-apis/im/v1/files" data = { 'file_type': file_type, 'file_name': file_name } # Add duration only if available (required for video/audio) if duration: data['duration'] = duration # Must be int, not string headers = {'Authorization': f'Bearer {access_token}'} logger.info(f"[FeiShu] Uploading video: file_name={file_name}, duration={duration}ms") with open(local_path, "rb") as file: upload_response = requests.post( upload_url, files={"file": file}, data=data, headers=headers, timeout=(5, 60) ) logger.info( f"[FeiShu] upload video response, status={upload_response.status_code}, res={upload_response.content}") response_data = upload_response.json() if response_data.get("code") == 0: # Add duration to the response data (API doesn't return it) upload_data = response_data.get("data") upload_data['duration'] = duration # Add our calculated duration logger.info( f"[FeiShu] Upload complete: file_key={upload_data.get('file_key')}, duration={duration}ms") return upload_data else: logger.error(f"[FeiShu] upload video failed: {response_data}") return None except Exception as e: logger.error(f"[FeiShu] upload video exception: {e}") return None finally: # Clean up temp file if temp_file and os.path.exists(temp_file): try: os.remove(temp_file) except Exception as e: logger.warning(f"[FeiShu] Failed to remove temp file {temp_file}: {e}") def _upload_file_url(self, file_url, access_token): """ Upload file to Feishu Supports both local files (file://) and HTTP URLs """ logger.debug(f"[FeiShu] start process file, file_url={file_url}") # Check if it's a local file path (file:// protocol) if file_url.startswith("file://"): local_path = file_url[7:] # Remove "file://" prefix logger.info(f"[FeiShu] uploading local file: {local_path}") if not os.path.exists(local_path): logger.error(f"[FeiShu] local file not found: {local_path}") return None # Get file info file_name = os.path.basename(local_path) file_ext = os.path.splitext(file_name)[1].lower() # Determine file type for Feishu API # Feishu supports: opus, mp4, pdf, doc, xls, ppt, stream (other types) file_type_map = { '.opus': 'opus', '.mp4': 'mp4', '.pdf': 'pdf', '.doc': 'doc', '.docx': 'doc', '.xls': 'xls', '.xlsx': 'xls', '.ppt': 'ppt', '.pptx': 'ppt', } file_type = file_type_map.get(file_ext, 'stream') # Default to stream for other types # Upload file to Feishu upload_url = "https://open.feishu.cn/open-apis/im/v1/files" data = {'file_type': file_type, 'file_name': file_name} headers = {'Authorization': f'Bearer {access_token}'} try: with open(local_path, "rb") as file: upload_response = requests.post( upload_url, files={"file": file}, data=data, headers=headers, timeout=(5, 30) # 5s connect, 30s read timeout ) logger.info( f"[FeiShu] upload file response, status={upload_response.status_code}, res={upload_response.content}") response_data = upload_response.json() if response_data.get("code") == 0: return response_data.get("data").get("file_key") else: logger.error(f"[FeiShu] upload file failed: {response_data}") return None except Exception as e: logger.error(f"[FeiShu] upload file exception: {e}") return None # For HTTP URLs, download first then upload try: response = requests.get(file_url, timeout=(5, 30)) if response.status_code != 200: logger.error(f"[FeiShu] download file failed, status={response.status_code}") return None # Save to temp file import uuid file_name = os.path.basename(file_url) temp_name = str(uuid.uuid4()) + "_" + file_name with open(temp_name, "wb") as file: file.write(response.content) # Upload file_ext = os.path.splitext(file_name)[1].lower() file_type_map = { '.opus': 'opus', '.mp4': 'mp4', '.pdf': 'pdf', '.doc': 'doc', '.docx': 'doc', '.xls': 'xls', '.xlsx': 'xls', '.ppt': 'ppt', '.pptx': 'ppt', } file_type = file_type_map.get(file_ext, 'stream') upload_url = "https://open.feishu.cn/open-apis/im/v1/files" data = {'file_type': file_type, 'file_name': file_name} headers = {'Authorization': f'Bearer {access_token}'} with open(temp_name, "rb") as file: upload_response = requests.post(upload_url, files={"file": file}, data=data, headers=headers) logger.info(f"[FeiShu] upload file, res={upload_response.content}") response_data = upload_response.json() os.remove(temp_name) # Clean up temp file if response_data.get("code") == 0: return response_data.get("data").get("file_key") else: logger.error(f"[FeiShu] upload file failed: {response_data}") return None except Exception as e: logger.error(f"[FeiShu] upload file from URL exception: {e}") return None def _compose_context(self, ctype: ContextType, content, **kwargs): context = Context(ctype, content) context.kwargs = kwargs if "origin_ctype" not in context: context["origin_ctype"] = ctype cmsg = context["msg"] # Set session_id based on chat type if cmsg.is_group: # Group chat: check if group_shared_session is enabled if conf().get("group_shared_session", True): # All users in the group share the same session context context["session_id"] = cmsg.other_user_id # group_id else: # Each user has their own session within the group # This ensures: # - Same user in different groups have separate conversation histories # - Same user in private chat and group chat have separate histories context["session_id"] = f"{cmsg.from_user_id}:{cmsg.other_user_id}" else: # Private chat: use user_id only context["session_id"] = cmsg.from_user_id context["receiver"] = cmsg.other_user_id if ctype == ContextType.TEXT: # 1.文本请求 # 图片生成处理 img_match_prefix = check_prefix(content, conf().get("image_create_prefix")) if img_match_prefix: content = content.replace(img_match_prefix, "", 1) context.type = ContextType.IMAGE_CREATE else: context.type = ContextType.TEXT context.content = content.strip() elif context.type == ContextType.VOICE: # 2.语音请求 if "desire_rtype" not in context and conf().get("voice_reply_voice"): context["desire_rtype"] = ReplyType.VOICE return context class FeishuController: """ HTTP服务器控制器,用于webhook模式 """ # 类常量 FAILED_MSG = '{"success": false}' SUCCESS_MSG = '{"success": true}' MESSAGE_RECEIVE_TYPE = "im.message.receive_v1" def GET(self): return "Feishu service start success!" def POST(self): try: channel = FeiShuChanel() request = json.loads(web.data().decode("utf-8")) logger.debug(f"[FeiShu] receive request: {request}") # 1.事件订阅回调验证 if request.get("type") == URL_VERIFICATION: varify_res = {"challenge": request.get("challenge")} return json.dumps(varify_res) # 2.消息接收处理 # token 校验 header = request.get("header") if not header or header.get("token") != channel.feishu_token: return self.FAILED_MSG # 处理消息事件 event = request.get("event") if header.get("event_type") == self.MESSAGE_RECEIVE_TYPE and event: channel._handle_message_event(event) return self.SUCCESS_MSG except Exception as e: logger.error(e) return self.FAILED_MSG
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/feishu/feishu_message.py
Python
from bridge.context import ContextType from channel.chat_message import ChatMessage import json import os import requests from common.log import logger from common.tmp_dir import TmpDir from common import utils from common.utils import expand_path from config import conf class FeishuMessage(ChatMessage): def __init__(self, event: dict, is_group=False, access_token=None): super().__init__(event) msg = event.get("message") sender = event.get("sender") self.access_token = access_token self.msg_id = msg.get("message_id") self.create_time = msg.get("create_time") self.is_group = is_group msg_type = msg.get("message_type") if msg_type == "text": self.ctype = ContextType.TEXT content = json.loads(msg.get('content')) self.content = content.get("text").strip() elif msg_type == "image": # 单张图片消息:下载并缓存,等待用户提问时一起发送 self.ctype = ContextType.IMAGE content = json.loads(msg.get("content")) image_key = content.get("image_key") # 下载图片到工作空间临时目录 workspace_root = expand_path(conf().get("agent_workspace", "~/cow")) tmp_dir = os.path.join(workspace_root, "tmp") os.makedirs(tmp_dir, exist_ok=True) image_path = os.path.join(tmp_dir, f"{image_key}.png") # 下载图片 url = f"https://open.feishu.cn/open-apis/im/v1/messages/{msg.get('message_id')}/resources/{image_key}" headers = {"Authorization": "Bearer " + access_token} params = {"type": "image"} response = requests.get(url=url, headers=headers, params=params) if response.status_code == 200: with open(image_path, "wb") as f: f.write(response.content) logger.info(f"[FeiShu] Downloaded single image, key={image_key}, path={image_path}") self.content = image_path self.image_path = image_path # 保存图片路径 else: logger.error(f"[FeiShu] Failed to download single image, key={image_key}, status={response.status_code}") self.content = f"[图片下载失败: {image_key}]" self.image_path = None elif msg_type == "post": # 富文本消息,可能包含图片、文本等多种元素 content = json.loads(msg.get("content")) # 飞书富文本消息结构:content 直接包含 title 和 content 数组 # 不是嵌套在 post 字段下 title = content.get("title", "") content_list = content.get("content", []) logger.info(f"[FeiShu] Post message - title: '{title}', content_list length: {len(content_list)}") # 收集所有图片和文本 image_keys = [] text_parts = [] if title: text_parts.append(title) for block in content_list: logger.debug(f"[FeiShu] Processing block: {block}") # block 本身就是元素列表 if not isinstance(block, list): continue for element in block: element_tag = element.get("tag") logger.debug(f"[FeiShu] Element tag: {element_tag}, element: {element}") if element_tag == "img": # 找到图片元素 image_key = element.get("image_key") if image_key: image_keys.append(image_key) elif element_tag == "text": # 文本元素 text_content = element.get("text", "") if text_content: text_parts.append(text_content) logger.info(f"[FeiShu] Parsed - images: {len(image_keys)}, text_parts: {text_parts}") # 富文本消息统一作为文本消息处理 self.ctype = ContextType.TEXT if image_keys: # 如果包含图片,下载并在文本中引用本地路径 workspace_root = expand_path(conf().get("agent_workspace", "~/cow")) tmp_dir = os.path.join(workspace_root, "tmp") os.makedirs(tmp_dir, exist_ok=True) # 保存图片路径映射 self.image_paths = {} for image_key in image_keys: image_path = os.path.join(tmp_dir, f"{image_key}.png") self.image_paths[image_key] = image_path def _download_images(): for image_key, image_path in self.image_paths.items(): url = f"https://open.feishu.cn/open-apis/im/v1/messages/{self.msg_id}/resources/{image_key}" headers = {"Authorization": "Bearer " + access_token} params = {"type": "image"} response = requests.get(url=url, headers=headers, params=params) if response.status_code == 200: with open(image_path, "wb") as f: f.write(response.content) logger.info(f"[FeiShu] Image downloaded from post message, key={image_key}, path={image_path}") else: logger.error(f"[FeiShu] Failed to download image from post, key={image_key}, status={response.status_code}") # 立即下载图片,不使用延迟下载 # 因为 TEXT 类型消息不会调用 prepare() _download_images() # 构建消息内容:文本 + 图片路径 content_parts = [] if text_parts: content_parts.append("\n".join(text_parts).strip()) for image_key, image_path in self.image_paths.items(): content_parts.append(f"[图片: {image_path}]") self.content = "\n".join(content_parts) logger.info(f"[FeiShu] Received post message with {len(image_keys)} image(s) and text: {self.content}") else: # 纯文本富文本消息 self.content = "\n".join(text_parts).strip() if text_parts else "[富文本消息]" logger.info(f"[FeiShu] Received post message (text only): {self.content}") elif msg_type == "file": self.ctype = ContextType.FILE content = json.loads(msg.get("content")) file_key = content.get("file_key") file_name = content.get("file_name") self.content = TmpDir().path() + file_key + "." + utils.get_path_suffix(file_name) def _download_file(): # 如果响应状态码是200,则将响应内容写入本地文件 url = f"https://open.feishu.cn/open-apis/im/v1/messages/{self.msg_id}/resources/{file_key}" headers = { "Authorization": "Bearer " + access_token, } params = { "type": "file" } response = requests.get(url=url, headers=headers, params=params) if response.status_code == 200: with open(self.content, "wb") as f: f.write(response.content) else: logger.info(f"[FeiShu] Failed to download file, key={file_key}, res={response.text}") self._prepare_fn = _download_file else: raise NotImplementedError("Unsupported message type: Type:{} ".format(msg_type)) self.from_user_id = sender.get("sender_id").get("open_id") self.to_user_id = event.get("app_id") if is_group: # 群聊 self.other_user_id = msg.get("chat_id") self.actual_user_id = self.from_user_id self.content = self.content.replace("@_user_1", "").strip() self.actual_user_nickname = "" else: # 私聊 self.other_user_id = self.from_user_id self.actual_user_id = self.from_user_id
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/file_cache.py
Python
""" 文件缓存管理器 用于缓存单独发送的文件消息(图片、视频、文档等),在用户提问时自动附加 """ import time import logging logger = logging.getLogger(__name__) class FileCache: """文件缓存管理器,按 session_id 缓存文件,TTL=2分钟""" def __init__(self, ttl=120): """ Args: ttl: 缓存过期时间(秒),默认2分钟 """ self.cache = {} self.ttl = ttl def add(self, session_id: str, file_path: str, file_type: str = "image"): """ 添加文件到缓存 Args: session_id: 会话ID file_path: 文件本地路径 file_type: 文件类型(image, video, file 等) """ if session_id not in self.cache: self.cache[session_id] = { 'files': [], 'timestamp': time.time() } # 添加文件(去重) file_info = {'path': file_path, 'type': file_type} if file_info not in self.cache[session_id]['files']: self.cache[session_id]['files'].append(file_info) logger.info(f"[FileCache] Added {file_type} to cache for session {session_id}: {file_path}") def get(self, session_id: str) -> list: """ 获取缓存的文件列表 Args: session_id: 会话ID Returns: 文件信息列表 [{'path': '...', 'type': 'image'}, ...],如果没有或已过期返回空列表 """ if session_id not in self.cache: return [] item = self.cache[session_id] # 检查是否过期 if time.time() - item['timestamp'] > self.ttl: logger.info(f"[FileCache] Cache expired for session {session_id}, clearing...") del self.cache[session_id] return [] return item['files'] def clear(self, session_id: str): """ 清除指定会话的缓存 Args: session_id: 会话ID """ if session_id in self.cache: logger.info(f"[FileCache] Cleared cache for session {session_id}") del self.cache[session_id] def cleanup_expired(self): """清理所有过期的缓存""" current_time = time.time() expired_sessions = [] for session_id, item in self.cache.items(): if current_time - item['timestamp'] > self.ttl: expired_sessions.append(session_id) for session_id in expired_sessions: del self.cache[session_id] logger.debug(f"[FileCache] Cleaned up expired cache for session {session_id}") if expired_sessions: logger.info(f"[FileCache] Cleaned up {len(expired_sessions)} expired cache(s)") # 全局单例 _file_cache = FileCache() def get_file_cache() -> FileCache: """获取全局文件缓存实例""" return _file_cache
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/terminal/terminal_channel.py
Python
import sys from bridge.context import * from bridge.reply import Reply, ReplyType from channel.chat_channel import ChatChannel, check_prefix from channel.chat_message import ChatMessage from common.log import logger from config import conf class TerminalMessage(ChatMessage): def __init__( self, msg_id, content, ctype=ContextType.TEXT, from_user_id="User", to_user_id="Chatgpt", other_user_id="Chatgpt", ): self.msg_id = msg_id self.ctype = ctype self.content = content self.from_user_id = from_user_id self.to_user_id = to_user_id self.other_user_id = other_user_id class TerminalChannel(ChatChannel): NOT_SUPPORT_REPLYTYPE = [ReplyType.VOICE] def send(self, reply: Reply, context: Context): print("\nBot:") if reply.type == ReplyType.IMAGE: from PIL import Image image_storage = reply.content image_storage.seek(0) img = Image.open(image_storage) print("<IMAGE>") img.show() elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片 import io import requests from PIL import Image img_url = reply.content pic_res = requests.get(img_url, stream=True) image_storage = io.BytesIO() for block in pic_res.iter_content(1024): image_storage.write(block) image_storage.seek(0) img = Image.open(image_storage) print(img_url) img.show() else: print(reply.content) print("\nUser:", end="") sys.stdout.flush() return def startup(self): context = Context() logger.setLevel("WARN") print("\nPlease input your question:\nUser:", end="") sys.stdout.flush() msg_id = 0 while True: try: prompt = self.get_input() except KeyboardInterrupt: print("\nExiting...") sys.exit() msg_id += 1 trigger_prefixs = conf().get("single_chat_prefix", [""]) if check_prefix(prompt, trigger_prefixs) is None: prompt = trigger_prefixs[0] + prompt # 给没触发的消息加上触发前缀 context = self._compose_context(ContextType.TEXT, prompt, msg=TerminalMessage(msg_id, prompt)) context["isgroup"] = False if context: self.produce(context) else: raise Exception("context is None") def get_input(self): """ Multi-line input function """ sys.stdout.flush() line = input() return line
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/web/chat.html
HTML
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CowAgent - Personal AI Agent</title> <link rel="icon" href="assets/favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> <script src="https://cdn.jsdelivr.net/npm/markdown-it@13.0.1/dist/markdown-it.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/python.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/javascript.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/java.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/go.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/cpp.min.js"></script> <script src="assets/axios.min.js"></script> <style> :root { --primary-color: #10a37f; --primary-hover: #0d8a6c; --bg-color: #f7f7f8; --chat-bg: #ffffff; --user-msg-bg: #10a37f; --bot-msg-bg: #f7f7f8; --border-color: #e5e5e5; --text-color: #343541; --text-light: #6e6e80; --shadow: 0 2px 6px rgba(0, 0, 0, 0.1); } * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: var(--text-color); background-color: var(--bg-color); display: flex; flex-direction: column; height: 100vh; margin: 0; overflow: hidden; } #app-container { display: flex; height: 100vh; width: 100%; } #sidebar { width: 260px; background-color: #202123; color: white; display: flex; flex-direction: column; transition: all 0.3s ease; } #new-chat { margin: 15px; padding: 12px; border: 1px solid rgba(255, 255, 255, 0.2); border-radius: 6px; display: flex; align-items: center; cursor: pointer; transition: background 0.2s; } #new-chat:hover { background-color: rgba(255, 255, 255, 0.1); } #new-chat i { margin-right: 10px; } #chat-history { flex: 1; overflow-y: auto; padding: 10px 15px; } .history-item { padding: 10px; border-radius: 6px; margin-bottom: 5px; cursor: pointer; display: flex; align-items: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .history-item:hover { background-color: rgba(255, 255, 255, 0.1); } .history-item i { margin-right: 10px; } #sidebar-footer { padding: 15px; border-top: 1px solid rgba(255, 255, 255, 0.1); } #user-info { display: flex; align-items: center; cursor: pointer; padding: 5px; border-radius: 6px; } #user-info:hover { background-color: rgba(255, 255, 255, 0.1); } #user-avatar { width: 30px; height: 30px; background-color: #10a37f; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-right: 10px; } #main-content { flex: 1; display: flex; flex-direction: column; height: 100%; position: relative; } #chat-header { padding: 15px 20px; border-bottom: 1px solid var(--border-color); display: flex; align-items: center; background-color: var(--chat-bg); } #menu-toggle { display: none; background: none; border: none; font-size: 20px; cursor: pointer; color: var(--text-color); margin-right: 15px; } #header-logo { height: 30px; margin-right: 10px; } #chat-title { font-weight: 600; flex: 1; } #github-link { display: flex; align-items: center; margin-left: 15px; color: var(--text-color); text-decoration: none; transition: opacity 0.2s; } #github-link:hover { opacity: 0.8; } #github-icon { height: 24px; width: 24px; } #messages { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 20px; background-color: var(--chat-bg); } .message-container { display: flex; padding: 15px 20px; width: 100%; max-width: 800px; margin: 0 auto; align-items: flex-start; } .bot-container { background-color: var(--bot-msg-bg); /* border-bottom: 1px solid var(--border-color); */ width: 100%; margin: 0; padding: 20px; } .user-container { display: flex; justify-content: flex-end; margin: 10px 0; padding: 0 0; } .user-container .message-container { flex-direction: row-reverse; text-align: right; } .user-container .avatar { margin-left: 20px; margin-right: 0; } .user-container .message-content { align-items: flex-end; } .user-container .message { padding: 13px 16px; background-color: var(--bot-msg-bg); border-radius: 10px; margin-bottom: 8px; } .bot-container .message { background-color: var(--bot-msg-bg); border-radius: 10px 10px 10px 0; margin-bottom: 8px; } .avatar { width: 36px; height: 36px; border-radius: 50%; background-color: #e0e0e0; display: flex; align-items: center; justify-content: center; margin-right: 15px; flex-shrink: 0; } .bot-avatar { background-color: #10a37f; color: white; margin-top: 4px; /* 微调头像位置,使其与文本更好地对齐 */ } .user-avatar { background-color: #d9d9e3; color: #40414f; } .message-content { display: flex; flex-direction: column; flex: 1; padding-top: 0; /* 移除顶部内边距 */ } .bot-container .message-content { align-items: flex-start; margin-top: 0; /* 确保没有顶部外边距 */ } .message { padding: 5px 16px; border-radius: 10px; margin-top: 0; margin-bottom: 8px; word-wrap: break-word; overflow-wrap: break-word; line-height: 1.5; } .message p { margin: 0.8em 0; line-height: 1.6; } .message p:first-child { margin-top: 0; } .message p:last-child { margin-bottom: 0; } .message h1, .message h2, .message h3, .message h4, .message h5, .message h6 { margin-top: 1.5em; margin-bottom: 0.75em; font-weight: 600; line-height: 1.25; } .message h1 { font-size: 1.5em; border-bottom: 1px solid var(--border-color); padding-bottom: 0.3em; } .message h2 { font-size: 1.3em; border-bottom: 1px solid var(--border-color); padding-bottom: 0.3em; } .message h3 { font-size: 1.15em; } .message h4 { font-size: 1em; } .message ul, .message ol { margin: 0.8em 0; padding-left: 2em; } .message li { margin: 0.3em 0; } .message li > p { margin: 0.3em 0; } .message pre { background-color: #f0f0f0; padding: 12px; border-radius: 6px; overflow-x: auto; margin: 1em 0; } .message code { font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace; background-color: rgba(0, 0, 0, 0.05); padding: 2px 4px; border-radius: 3px; font-size: 0.9em; } .message pre code { background-color: transparent; padding: 0; border-radius: 0; font-size: 0.9em; line-height: 1.5; } .message blockquote { border-left: 4px solid #ddd; padding: 0 0 0 1em; margin: 1em 0; color: #777; } .message blockquote > :first-child { margin-top: 0; } .message blockquote > :last-child { margin-bottom: 0; } .message table { border-collapse: collapse; width: 100%; margin: 1em 0; overflow-x: auto; display: block; } .message th, .message td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; } .message th { background-color: #f2f2f2; font-weight: 600; } .message tr:nth-child(even) { background-color: #f9f9f9; } .message hr { height: 1px; background-color: var(--border-color); border: none; margin: 1.5em 0; } .message img { max-width: 100%; height: auto; margin: 0 0; } .timestamp { font-size: 0.75rem; color: var(--text-light); padding-left: 2px; } /* 为机器人消息的时间戳添加左对齐 */ .bot-container .timestamp { align-self: flex-start; margin-left: 15px; } /* 为用户消息的时间戳添加右对齐 */ .user-container .timestamp { align-self: flex-end; padding-right: 2px; padding-left: 0; } #input-container { padding: 15px 20px; background-color: var(--chat-bg); border-top: 1px solid var(--border-color); position: relative; display: flex; flex-direction: column; align-items: center; } #input-wrapper { position: relative; width: 100%; max-width: 768px; margin: 0 auto; } #input { width: 100%; padding: 12px 45px 12px 15px; border: 1px solid var(--border-color); border-radius: 6px; font-size: 16px; line-height: 1.5; color: var(--text-color); background-color: var(--chat-bg); resize: none; height: 52px; max-height: 200px; overflow-y: auto; box-shadow: var(--shadow); transition: border-color 0.3s; } #input:focus { outline: none; border-color: var(--primary-color); } #send { position: absolute; top: 0; right: 10px; height: 100%; background-color: transparent; border: none; color: var(--primary-color); font-size: 20px; cursor: pointer; display: flex; align-items: center; justify-content: center; width: 32px; border-radius: 4px; transition: background-color 0.2s; } #send:hover { background-color: rgba(16, 163, 127, 0.1); } #send:disabled { color: var(--border-color); cursor: not-allowed; } #welcome-screen { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; text-align: center; padding: 20px; } #welcome-title { font-size: 2rem; margin-bottom: 20px; font-weight: 600; } #welcome-subtitle { font-size: 1.2rem; color: var(--text-light); margin-bottom: 40px; } .examples-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 15px; width: 100%; max-width: 900px; } .example-card { background-color: white; border: 1px solid var(--border-color); border-radius: 8px; padding: 15px; cursor: pointer; transition: all 0.2s; } .example-card:hover { background-color: #f0f0f0; } .example-title { font-weight: 600; margin-bottom: 8px; } .example-text { color: var(--text-light); font-size: 0.9rem; } /* Responsive styles */ @media (max-width: 768px) { #sidebar { position: fixed; left: -260px; height: 100%; z-index: 1000; transition: left 0.3s ease; } #sidebar.active { left: 0; box-shadow: 2px 0 10px rgba(0, 0, 0, 0.2); } #menu-toggle { display: block; } .message-container { padding: 10px 0 10px 0; } .bot-container { padding: 15px; } #input-container { padding: 10px; } .examples-container { grid-template-columns: 1fr; } #header-logo { height: 24px; } /* 添加遮罩层,当侧边栏打开时显示 */ #sidebar-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); z-index: 999; cursor: pointer; } #sidebar.active + #sidebar-overlay { display: block; } } /* Dark mode support */ @media (prefers-color-scheme: dark) { :root { --bg-color: #343541; --chat-bg: #444654; --bot-msg-bg: #444654; --border-color: #565869; --text-color: #ececf1; --text-light: #acacbe; } #input { background-color: #40414f; } .example-card { background-color: #40414f; } .example-card:hover { background-color: #565869; } .message pre { background-color: #2d2d2d; } .message code { background-color: rgba(255, 255, 255, 0.1); } .message blockquote { border-left-color: #555; color: #aaa; } .message th, .message td { border-color: #555; } .message th { background-color: #3a3a3a; } .hljs { background: #2d2d2d !important; color: #d4d4d4 !important; } } .typing-indicator { display: inline-flex; align-items: center; margin-left: 0; justify-content: flex-start; width: auto; position: relative; top: -5px; left: -10px; margin-top: 10px; margin-bottom: 5px; } .typing-indicator span { height: 8px; width: 8px; margin: 0 2px; background-color: var(--text-light); border-radius: 50%; display: inline-block; opacity: 0.4; } .typing-indicator span:nth-child(1) { animation: pulse 1s infinite; } .typing-indicator span:nth-child(2) { animation: pulse 1s infinite 0.2s; } .typing-indicator span:nth-child(3) { animation: pulse 1s infinite 0.4s; } @keyframes pulse { 0% { opacity: 0.4; transform: scale(1); } 50% { opacity: 1; transform: scale(1.2); } 100% { opacity: 0.4; transform: scale(1); } } .history-divider { padding: 10px; color: var(--text-light); font-size: 0.8rem; text-transform: uppercase; letter-spacing: 1px; margin-top: 10px; } .history-item.active { background-color: rgba(255, 255, 255, 0.1); font-weight: bold; } /* 确保代码块内的文本不会溢出 */ .hljs { white-space: pre-wrap; word-break: break-all; } </style> </head> <body> <div id="app-container"> <div id="sidebar"> <div id="new-chat"> <i class="fas fa-plus"></i> <span>新对话</span> </div> <div id="chat-history"> <!-- 历史对话将在这里动态添加 --> </div> <div id="sidebar-footer"> <div id="user-info"> <div id="user-avatar">U</div> <span>用户</span> </div> </div> </div> <div id="sidebar-overlay"></div> <div id="main-content"> <div id="chat-header"> <button id="menu-toggle"> <i class="fas fa-bars"></i> </button> <img id="header-logo" src="assets/logo.jpg" alt="AI Assistant Logo"> <div id="chat-title" class="agent-title">AI 助手</div> <a id="github-link" href="https://github.com/zhayujie/chatgpt-on-wechat" target="_blank" rel="noopener noreferrer"> <img id="github-icon" src="assets/github.png" alt="GitHub"> </a> </div> <div id="messages"> <!-- 初始欢迎界面 --> <div id="welcome-screen"> <h1 id="welcome-title" class="agent-title">AI 助手</h1> <p id="welcome-subtitle" class="agent-subtitle">我可以回答问题、提供信息或者帮助您完成各种任务</p> <div class="examples-container"> <div class="example-card"> <div class="example-title">📁 系统管理</div> <div class="example-text">帮我查看工作空间里有哪些文件</div> </div> <div class="example-card"> <div class="example-title">⏰ 智能任务</div> <div class="example-text">提醒我5分钟后查看服务器情况</div> </div> <div class="example-card"> <div class="example-title">💻 编程助手</div> <div class="example-text">帮我编写一个Python爬虫脚本</div> </div> <!-- <div class="example-card"> <div class="example-title">生活建议</div> <div class="example-text">推荐一些提高工作效率的方法</div> </div> --> </div> </div> <!-- 消息将在这里动态添加 --> </div> <div id="input-container"> <div id="input-wrapper"> <textarea id="input" placeholder="发送消息..." rows="1"></textarea> <button id="send" disabled> <i class="fas fa-paper-plane"></i> </button> </div> </div> </div> </div> <script> // DOM 元素 const messagesDiv = document.getElementById('messages'); const input = document.getElementById('input'); const sendButton = document.getElementById('send'); const menuToggle = document.getElementById('menu-toggle'); const sidebar = document.getElementById('sidebar'); const welcomeScreen = document.getElementById('welcome-screen'); const exampleCards = document.querySelectorAll('.example-card'); const newChatButton = document.getElementById('new-chat'); const chatHistory = document.getElementById('chat-history'); // 生成新的会话ID function generateSessionId() { return 'session_' + ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) ); } // 生成初始会话ID let sessionId = generateSessionId(); console.log('Session ID:', sessionId); // 获取配置并更新标题 let appConfig = { use_agent: false, title: "AI 助手", subtitle: "我可以回答问题、提供信息或者帮助您完成各种任务" }; // 从服务器获取配置 axios.get('/config') .then(response => { if (response.data.status === "success") { appConfig = response.data; updateTitle(appConfig.title, appConfig.subtitle); } }) .catch(error => { console.error('Error loading config:', error); }); // 更新标题的函数 function updateTitle(title, subtitle) { // 更新顶部标题 const chatTitle = document.getElementById('chat-title'); if (chatTitle) { chatTitle.textContent = title; } // 更新欢迎屏幕标题 const welcomeTitle = document.getElementById('welcome-title'); if (welcomeTitle) { welcomeTitle.textContent = title; } const welcomeSubtitle = document.getElementById('welcome-subtitle'); if (welcomeSubtitle) { welcomeSubtitle.textContent = subtitle; } } // 添加一个变量来跟踪输入法状态 let isComposing = false; // 监听输入法组合状态开始 input.addEventListener('compositionstart', function() { isComposing = true; }); // 监听输入法组合状态结束 input.addEventListener('compositionend', function() { isComposing = false; }); // 自动调整文本区域高度 input.addEventListener('input', function() { this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px'; // 启用/禁用发送按钮 sendButton.disabled = !this.value.trim(); }); // 处理示例卡片点击 exampleCards.forEach(card => { card.addEventListener('click', function() { const exampleText = this.querySelector('.example-text').textContent; input.value = exampleText; input.dispatchEvent(new Event('input')); input.focus(); }); }); // 处理菜单切换 menuToggle.addEventListener('click', function(event) { event.stopPropagation(); // 防止事件冒泡到 main-content sidebar.classList.toggle('active'); }); // 处理新对话按钮 - 创建新的会话ID和清空当前对话 newChatButton.addEventListener('click', function() { // 生成新的会话ID sessionId = generateSessionId(); // 将新的会话ID保存到全局变量,供轮询函数使用 window.sessionId = sessionId; console.log('New conversation started with new session ID:', sessionId); // 清空聊天记录 clearChat(); }); // 发送按钮点击事件 sendButton.addEventListener('click', function() { sendMessage(); }); // 输入框按键事件 input.addEventListener('keydown', function(event) { // Ctrl+Enter 或 Shift+Enter 添加换行 if ((event.ctrlKey || event.shiftKey) && event.key === 'Enter') { const start = this.selectionStart; const end = this.selectionEnd; const value = this.value; this.value = value.substring(0, start) + '\n' + value.substring(end); this.selectionStart = this.selectionEnd = start + 1; event.preventDefault(); } // Enter 键发送消息,但只在不是输入法组合状态时 else if (event.key === 'Enter' && !event.shiftKey && !event.ctrlKey && !isComposing) { sendMessage(); event.preventDefault(); } }); // 在发送消息函数前添加调试代码 console.log('Axios loaded:', typeof axios !== 'undefined'); // 发送消息函数 function sendMessage() { console.log('Send message function called'); const userMessage = input.value.trim(); if (userMessage) { // 隐藏欢迎屏幕 const welcomeScreenElement = document.getElementById('welcome-screen'); if (welcomeScreenElement) { welcomeScreenElement.remove(); } const timestamp = new Date(); // 添加用户消息到界面 addUserMessage(userMessage, timestamp); // 添加一个等待中的机器人消息 const loadingContainer = addLoadingMessage(); // 清空输入框并重置高度 - 移到这里,确保发送后立即清空 input.value = ''; input.style.height = '52px'; sendButton.disabled = true; // 使用当前的全局会话ID const currentSessionId = window.sessionId || sessionId; // 发送到服务器并获取请求ID axios({ method: 'post', url: '/message', data: { session_id: currentSessionId, // 使用最新的会话ID message: userMessage, timestamp: timestamp.toISOString() }, timeout: 10000 // 10秒超时 }) .then(response => { if (response.data.status === "success") { // 保存当前请求ID,用于识别响应 const currentRequestId = response.data.request_id; // 如果还没有开始轮询,则开始轮询 if (!window.isPolling) { startPolling(currentSessionId); } // 将请求ID和加载容器关联起来 window.loadingContainers = window.loadingContainers || {}; window.loadingContainers[currentRequestId] = loadingContainer; // 初始化请求的响应容器映射 window.requestContainers = window.requestContainers || {}; } else { // 处理错误 if (loadingContainer.parentNode) { messagesDiv.removeChild(loadingContainer); } addBotMessage("抱歉,发生了错误,请稍后再试。", new Date()); } }) .catch(error => { console.error('Error sending message:', error); // 移除加载消息 if (loadingContainer.parentNode) { messagesDiv.removeChild(loadingContainer); } // 显示错误消息 if (error.code === 'ECONNABORTED') { addBotMessage("请求超时,请再试一次吧。", new Date()); } else { addBotMessage("抱歉,发生了错误,请稍后再试。", new Date()); } }); } } // 修改轮询函数,确保正确处理多条回复 function startPolling(sessionId) { if (window.isPolling) return; window.isPolling = true; console.log('Starting polling with session ID:', sessionId); function poll() { if (!window.isPolling) return; // 如果页面已关闭或导航离开,停止轮询 if (document.hidden) { setTimeout(poll, 5000); // 页面不可见时降低轮询频率 return; } // 使用当前的会话ID,而不是闭包中的sessionId const currentSessionId = window.sessionId || sessionId; axios({ method: 'post', url: '/poll', data: { session_id: currentSessionId }, timeout: 5000 }) .then(response => { if (response.data.status === "success") { if (response.data.has_content) { console.log('Received response:', response.data); // 获取请求ID和内容 const requestId = response.data.request_id; const content = response.data.content; const timestamp = new Date(response.data.timestamp * 1000); // 检查是否有对应的加载容器 if (window.loadingContainers && window.loadingContainers[requestId]) { // 移除加载容器 const loadingContainer = window.loadingContainers[requestId]; if (loadingContainer && loadingContainer.parentNode) { messagesDiv.removeChild(loadingContainer); } // 删除已处理的加载容器引用 delete window.loadingContainers[requestId]; } // 始终创建新的消息,无论是否是同一个请求的后续回复 addBotMessage(content, timestamp, requestId); // 滚动到底部 scrollToBottom(); } // 继续轮询,使用原来的2秒间隔 setTimeout(poll, 2000); } else { // 处理错误但继续轮询 console.error('Error in polling response:', response.data.message); setTimeout(poll, 3000); } }) .catch(error => { console.error('Error polling for response:', error); // 出错后继续轮询,但间隔更长 setTimeout(poll, 3000); }); } // 开始轮询 poll(); } // 添加机器人消息的函数 (保存到localStorage),增加requestId参数 function addBotMessage(content, timestamp, requestId) { // 显示消息 displayBotMessage(content, timestamp, requestId); // 保存到localStorage saveMessageToLocalStorage({ role: 'assistant', content: content, timestamp: timestamp.getTime(), requestId: requestId }); } // 修改显示机器人消息的函数,增加requestId参数 function displayBotMessage(content, timestamp, requestId) { const botContainer = document.createElement('div'); botContainer.className = 'bot-container'; // 如果有requestId,将其存储在数据属性中 if (requestId) { botContainer.dataset.requestId = requestId; } const messageContainer = document.createElement('div'); messageContainer.className = 'message-container'; // 安全地格式化消息 let formattedContent; try { formattedContent = formatMessage(content); } catch (e) { console.error('Error formatting bot message:', e); formattedContent = `<p>${content.replace(/\n/g, '<br>')}</p>`; } messageContainer.innerHTML = ` <div class="avatar bot-avatar"> <i class="fas fa-robot"></i> </div> <div class="message-content"> <div class="message">${formattedContent}</div> <div class="timestamp">${formatTimestamp(timestamp)}</div> </div> `; botContainer.appendChild(messageContainer); messagesDiv.appendChild(botContainer); // 应用代码高亮 setTimeout(() => { applyHighlighting(); }, 0); scrollToBottom(); } // 处理响应 function handleResponse(requestId, content) { // 获取该请求的加载容器 const loadingContainer = window.loadingContainers && window.loadingContainers[requestId]; // 如果有加载容器,移除它 if (loadingContainer && loadingContainer.parentNode) { messagesDiv.removeChild(loadingContainer); delete window.loadingContainers[requestId]; } // 为每个请求创建一个新的消息容器 if (!window.requestContainers[requestId]) { window.requestContainers[requestId] = createBotMessageContainer(content, new Date()); } else { // 更新现有消息容器 updateBotMessageContent(window.requestContainers[requestId], content); } // 保存消息到localStorage saveMessageToLocalStorage({ role: 'assistant', content: content, timestamp: new Date().getTime(), request_id: requestId }); } // 修改createBotMessageContainer函数,使其返回创建的容器 function createBotMessageContainer(content, timestamp) { const botContainer = document.createElement('div'); botContainer.className = 'bot-container'; const messageContainer = document.createElement('div'); messageContainer.className = 'message-container'; // 安全地格式化消息 let formattedContent; try { formattedContent = formatMessage(content); } catch (e) { console.error('Error formatting bot message:', e); formattedContent = `<p>${content.replace(/\n/g, '<br>')}</p>`; } messageContainer.innerHTML = ` <div class="avatar bot-avatar"> <i class="fas fa-robot"></i> </div> <div class="message-content"> <div class="message">${formattedContent}</div> <div class="timestamp">${formatTimestamp(timestamp)}</div> </div> `; botContainer.appendChild(messageContainer); messagesDiv.appendChild(botContainer); // 应用代码高亮 setTimeout(() => { applyHighlighting(); }, 0); scrollToBottom(); return botContainer; } // 格式化时间戳 function formatTimestamp(date) { return date.toLocaleTimeString(); } // 滚动到底部 function scrollToBottom() { messagesDiv.scrollTop = messagesDiv.scrollHeight; } // 处理窗口大小变化 window.addEventListener('resize', function() { if (window.innerWidth > 768) { sidebar.classList.remove('active'); } }); // 初始化 input.focus(); // 清空聊天记录并显示欢迎屏幕 function clearChat() { // 清空消息区域 messagesDiv.innerHTML = ''; // 创建欢迎屏幕 const newWelcomeScreen = document.createElement('div'); newWelcomeScreen.id = 'welcome-screen'; newWelcomeScreen.innerHTML = ` <h1 id="welcome-title" class="agent-title">${appConfig.title}</h1> <p id="welcome-subtitle" class="agent-subtitle">${appConfig.subtitle}</p> <div class="examples-container"> <div class="example-card"> <div class="example-title">📁 系统管理</div> <div class="example-text">帮我查看工作空间里有哪些文件</div> </div> <div class="example-card"> <div class="example-title">⏰ 智能任务</div> <div class="example-text">提醒我5分钟后查看服务器情况</div> </div> <div class="example-card"> <div class="example-title">💻 编程助手</div> <div class="example-text">帮我编写一个Python爬虫脚本</div> </div> </div> `; // 设置样式 newWelcomeScreen.style.display = 'flex'; newWelcomeScreen.style.flexDirection = 'column'; newWelcomeScreen.style.alignItems = 'center'; newWelcomeScreen.style.justifyContent = 'center'; newWelcomeScreen.style.height = '100%'; newWelcomeScreen.style.textAlign = 'center'; newWelcomeScreen.style.padding = '20px'; // 添加到DOM messagesDiv.appendChild(newWelcomeScreen); // 绑定示例卡片事件 newWelcomeScreen.querySelectorAll('.example-card').forEach(card => { card.addEventListener('click', function() { const exampleText = this.querySelector('.example-text').textContent; input.value = exampleText; input.dispatchEvent(new Event('input')); input.focus(); }); }); // 清空localStorage中的消息 - 使用会话ID作为键 localStorage.setItem(`chatMessages_${sessionId}`, JSON.stringify([])); // 在移动设备上关闭侧边栏 if (window.innerWidth <= 768) { sidebar.classList.remove('active'); } } // 从localStorage加载消息 - 使用会话ID作为键 function loadMessagesFromLocalStorage() { try { return JSON.parse(localStorage.getItem(`chatMessages_${sessionId}`) || '[]'); } catch (error) { console.error('Error loading messages from localStorage:', error); return []; } } // 保存消息到localStorage - 使用会话ID作为键 function saveMessageToLocalStorage(message) { try { const messages = loadMessagesFromLocalStorage(); messages.push(message); localStorage.setItem(`chatMessages_${sessionId}`, JSON.stringify(messages)); } catch (error) { console.error('Error saving message to localStorage:', error); } } // 添加用户消息的函数 (保存到localStorage) function addUserMessage(content, timestamp) { // 显示消息 displayUserMessage(content, timestamp); // 保存到localStorage saveMessageToLocalStorage({ role: 'user', content: content, timestamp: timestamp.getTime() }); } // 只显示用户消息而不保存到localStorage function displayUserMessage(content, timestamp) { const userContainer = document.createElement('div'); userContainer.className = 'user-container'; const messageContainer = document.createElement('div'); messageContainer.className = 'message-container'; // 安全地格式化消息 let formattedContent; try { formattedContent = formatMessage(content); } catch (e) { console.error('Error formatting user message:', e); formattedContent = `<p>${content.replace(/\n/g, '<br>')}</p>`; } messageContainer.innerHTML = ` <div class="avatar user-avatar"> <i class="fas fa-user"></i> </div> <div class="message-content"> <div class="message">${formattedContent}</div> <div class="timestamp">${formatTimestamp(timestamp)}</div> </div> `; userContainer.appendChild(messageContainer); messagesDiv.appendChild(userContainer); // 应用代码高亮 setTimeout(() => { applyHighlighting(); }, 0); scrollToBottom(); } // 添加加载中的消息 function addLoadingMessage() { const botContainer = document.createElement('div'); botContainer.className = 'bot-container loading-container'; const messageContainer = document.createElement('div'); messageContainer.className = 'message-container'; messageContainer.innerHTML = ` <div class="avatar bot-avatar"> <i class="fas fa-robot"></i> </div> <div class="message-content"> <div class="message"> <div class="typing-indicator"> <span></span> <span></span> <span></span> </div> </div> </div> `; botContainer.appendChild(messageContainer); messagesDiv.appendChild(botContainer); scrollToBottom(); return botContainer; } // 自动将链接设置为在新标签页打开 const externalLinksPlugin = (md) => { // 保存原始的链接渲染器 const defaultRender = md.renderer.rules.link_open || function(tokens, idx, options, env, self) { return self.renderToken(tokens, idx, options); }; // 重写链接渲染器 md.renderer.rules.link_open = function(tokens, idx, options, env, self) { // 为所有链接添加 target="_blank" 和 rel="noopener noreferrer" const token = tokens[idx]; // 添加 target="_blank" 属性 token.attrPush(['target', '_blank']); // 添加 rel="noopener noreferrer" 以提高安全性 token.attrPush(['rel', 'noopener noreferrer']); // 调用默认渲染器 return defaultRender(tokens, idx, options, env, self); }; }; // 替换 formatMessage 函数,使用 markdown-it 替代 marked function formatMessage(content) { try { // 初始化 markdown-it 实例 const md = window.markdownit({ html: false, // 禁用 HTML 标签 xhtmlOut: false, // 使用 '/' 关闭单标签 breaks: true, // 将换行符转换为 <br> linkify: true, // 自动将 URL 转换为链接 typographer: true, // 启用一些语言中性的替换和引号美化 highlight: function(str, lang) { if (lang && hljs.getLanguage(lang)) { try { return hljs.highlight(str, { language: lang }).value; } catch (e) { console.error('Error highlighting code:', e); } } return hljs.highlightAuto(str).value; } }); // 自动将图片URL转换为图片标签 const autoImagePlugin = (md) => { const defaultRender = md.renderer.rules.text || function(tokens, idx, options, env, self) { return self.renderToken(tokens, idx, options); }; md.renderer.rules.text = function(tokens, idx, options, env, self) { const token = tokens[idx]; const text = token.content.trim(); // 检测是否完全是一个图片链接 (以https://开头,以图片扩展名结尾) const imageRegex = /^https?:\/\/\S+\.(jpg|jpeg|png|gif|webp)(\?\S*)?$/i; if (imageRegex.test(text)) { return `<img src="${text}" alt="Image" style="max-width: 100%; height: auto;" />`; } // 使用默认渲染 return defaultRender(tokens, idx, options, env, self); }; }; // 应用插件 md.use(autoImagePlugin); // 应用外部链接插件 md.use(externalLinksPlugin); // 渲染 Markdown return md.render(content); } catch (e) { console.error('Error parsing markdown:', e); // 如果解析失败,至少确保换行符正确显示 return content.replace(/\n/g, '<br>'); } } // 更新 applyHighlighting 函数 function applyHighlighting() { try { document.querySelectorAll('pre code').forEach((block) => { // 确保代码块有正确的类 if (!block.classList.contains('hljs')) { block.classList.add('hljs'); } // 尝试获取语言 let language = ''; block.classList.forEach(cls => { if (cls.startsWith('language-')) { language = cls.replace('language-', ''); } }); // 应用高亮 if (language && hljs.getLanguage(language)) { try { hljs.highlightBlock(block); } catch (e) { console.error('Error highlighting specific language:', e); hljs.highlightAuto(block); } } else { hljs.highlightAuto(block); } }); } catch (e) { console.error('Error applying code highlighting:', e); } } // 在 #main-content 上添加点击事件,用于关闭侧边栏 document.getElementById('main-content').addEventListener('click', function(event) { // 只在移动视图下且侧边栏打开时处理 if (window.innerWidth <= 768 && sidebar.classList.contains('active')) { sidebar.classList.remove('active'); } }); // 阻止侧边栏内部点击事件冒泡到 main-content document.getElementById('sidebar').addEventListener('click', function(event) { event.stopPropagation(); }); // 添加遮罩层点击事件,用于关闭侧边栏 document.getElementById('sidebar-overlay').addEventListener('click', function() { if (sidebar.classList.contains('active')) { sidebar.classList.remove('active'); } }); </script> </body> </html>
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/web/static/axios.min.js
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).axios=t()}(this,(function(){"use strict";function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function r(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function o(e,t){return function(){return e.apply(t,arguments)}}var i,s=Object.prototype.toString,a=Object.getPrototypeOf,u=(i=Object.create(null),function(e){var t=s.call(e);return i[t]||(i[t]=t.slice(8,-1).toLowerCase())}),c=function(e){return e=e.toLowerCase(),function(t){return u(t)===e}},f=function(t){return function(n){return e(n)===t}},l=Array.isArray,d=f("undefined");var h=c("ArrayBuffer");var p=f("string"),m=f("function"),v=f("number"),y=function(t){return null!==t&&"object"===e(t)},b=function(e){if("object"!==u(e))return!1;var t=a(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},g=c("Date"),E=c("File"),w=c("Blob"),O=c("FileList"),R=c("URLSearchParams");function S(t,n){var r,o,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=i.allOwnKeys,a=void 0!==s&&s;if(null!=t)if("object"!==e(t)&&(t=[t]),l(t))for(r=0,o=t.length;r<o;r++)n.call(null,t[r],r,t);else{var u,c=a?Object.getOwnPropertyNames(t):Object.keys(t),f=c.length;for(r=0;r<f;r++)u=c[r],n.call(null,t[u],u,t)}}var A,j=(A="undefined"!=typeof Uint8Array&&a(Uint8Array),function(e){return A&&e instanceof A}),T=c("HTMLFormElement"),x=function(e){var t=Object.prototype.hasOwnProperty;return function(e,n){return t.call(e,n)}}(),C=c("RegExp"),N=function(e,t){var n=Object.getOwnPropertyDescriptors(e),r={};S(n,(function(n,o){!1!==t(n,o,e)&&(r[o]=n)})),Object.defineProperties(e,r)},P={isArray:l,isArrayBuffer:h,isBuffer:function(e){return null!==e&&!d(e)&&null!==e.constructor&&!d(e.constructor)&&m(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:function(e){var t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||s.call(e)===t||m(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&h(e.buffer)},isString:p,isNumber:v,isBoolean:function(e){return!0===e||!1===e},isObject:y,isPlainObject:b,isUndefined:d,isDate:g,isFile:E,isBlob:w,isRegExp:C,isFunction:m,isStream:function(e){return y(e)&&m(e.pipe)},isURLSearchParams:R,isTypedArray:j,isFileList:O,forEach:S,merge:function e(){for(var t={},n=function(n,r){b(t[r])&&b(n)?t[r]=e(t[r],n):b(n)?t[r]=e({},n):l(n)?t[r]=n.slice():t[r]=n},r=0,o=arguments.length;r<o;r++)arguments[r]&&S(arguments[r],n);return t},extend:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=r.allOwnKeys;return S(t,(function(t,r){n&&m(t)?e[r]=o(t,n):e[r]=t}),{allOwnKeys:i}),e},trim:function(e){return e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits:function(e,t,n,r){e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:function(e,t,n,r){var o,i,s,u={};if(t=t||{},null==e)return t;do{for(i=(o=Object.getOwnPropertyNames(e)).length;i-- >0;)s=o[i],r&&!r(s,e,t)||u[s]||(t[s]=e[s],u[s]=!0);e=!1!==n&&a(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:u,kindOfTest:c,endsWith:function(e,t,n){e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;var r=e.indexOf(t,n);return-1!==r&&r===n},toArray:function(e){if(!e)return null;if(l(e))return e;var t=e.length;if(!v(t))return null;for(var n=new Array(t);t-- >0;)n[t]=e[t];return n},forEachEntry:function(e,t){for(var n,r=(e&&e[Symbol.iterator]).call(e);(n=r.next())&&!n.done;){var o=n.value;t.call(e,o[0],o[1])}},matchAll:function(e,t){for(var n,r=[];null!==(n=e.exec(t));)r.push(n);return r},isHTMLForm:T,hasOwnProperty:x,hasOwnProp:x,reduceDescriptors:N,freezeMethods:function(e){N(e,(function(t,n){var r=e[n];m(r)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=function(){throw Error("Can not read-only method '"+n+"'")}))}))},toObjectSet:function(e,t){var n={},r=function(e){e.forEach((function(e){n[e]=!0}))};return l(e)?r(e):r(String(e).split(t)),n},toCamelCase:function(e){return e.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,(function(e,t,n){return t.toUpperCase()+n}))},noop:function(){},toFiniteNumber:function(e,t){return e=+e,Number.isFinite(e)?e:t}};function _(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}P.inherits(_,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var B=_.prototype,D={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((function(e){D[e]={value:e}})),Object.defineProperties(_,D),Object.defineProperty(B,"isAxiosError",{value:!0}),_.from=function(e,t,n,r,o,i){var s=Object.create(B);return P.toFlatObject(e,s,(function(e){return e!==Error.prototype}),(function(e){return"isAxiosError"!==e})),_.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};var F="object"==("undefined"==typeof self?"undefined":e(self))?self.FormData:window.FormData;function U(e){return P.isPlainObject(e)||P.isArray(e)}function k(e){return P.endsWith(e,"[]")?e.slice(0,-2):e}function L(e,t,n){return e?e.concat(t).map((function(e,t){return e=k(e),!n&&t?"["+e+"]":e})).join(n?".":""):t}var q=P.toFlatObject(P,{},null,(function(e){return/^is[A-Z]/.test(e)}));function z(t,n,r){if(!P.isObject(t))throw new TypeError("target must be an object");n=n||new(F||FormData);var o,i=(r=P.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!P.isUndefined(t[e])}))).metaTokens,s=r.visitor||l,a=r.dots,u=r.indexes,c=(r.Blob||"undefined"!=typeof Blob&&Blob)&&((o=n)&&P.isFunction(o.append)&&"FormData"===o[Symbol.toStringTag]&&o[Symbol.iterator]);if(!P.isFunction(s))throw new TypeError("visitor must be a function");function f(e){if(null===e)return"";if(P.isDate(e))return e.toISOString();if(!c&&P.isBlob(e))throw new _("Blob is not supported. Use a Buffer instead.");return P.isArrayBuffer(e)||P.isTypedArray(e)?c&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(t,r,o){var s=t;if(t&&!o&&"object"===e(t))if(P.endsWith(r,"{}"))r=i?r:r.slice(0,-2),t=JSON.stringify(t);else if(P.isArray(t)&&function(e){return P.isArray(e)&&!e.some(U)}(t)||P.isFileList(t)||P.endsWith(r,"[]")&&(s=P.toArray(t)))return r=k(r),s.forEach((function(e,t){!P.isUndefined(e)&&n.append(!0===u?L([r],t,a):null===u?r:r+"[]",f(e))})),!1;return!!U(t)||(n.append(L(o,r,a),f(t)),!1)}var d=[],h=Object.assign(q,{defaultVisitor:l,convertValue:f,isVisitable:U});if(!P.isObject(t))throw new TypeError("data must be an object");return function e(t,r){if(!P.isUndefined(t)){if(-1!==d.indexOf(t))throw Error("Circular reference detected in "+r.join("."));d.push(t),P.forEach(t,(function(t,o){!0===(!P.isUndefined(t)&&s.call(n,t,P.isString(o)?o.trim():o,r,h))&&e(t,r?r.concat(o):[o])})),d.pop()}}(t),n}function I(e){var t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function M(e,t){this._pairs=[],e&&z(e,this,t)}var J=M.prototype;function H(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function V(e,t,n){if(!t)return e;var r=e.indexOf("#");-1!==r&&(e=e.slice(0,r));var o=n&&n.encode||H,i=P.isURLSearchParams(t)?t.toString():new M(t,n).toString(o);return i&&(e+=(-1===e.indexOf("?")?"?":"&")+i),e}J.append=function(e,t){this._pairs.push([e,t])},J.toString=function(e){var t=e?function(t){return e.call(this,t,I)}:I;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var W,K=function(){function e(){t(this,e),this.handlers=[]}return r(e,[{key:"use",value:function(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}},{key:"eject",value:function(e){this.handlers[e]&&(this.handlers[e]=null)}},{key:"clear",value:function(){this.handlers&&(this.handlers=[])}},{key:"forEach",value:function(e){P.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}]),e}(),X={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},$="undefined"!=typeof URLSearchParams?URLSearchParams:M,Q=FormData,G=("undefined"==typeof navigator||"ReactNative"!==(W=navigator.product)&&"NativeScript"!==W&&"NS"!==W)&&"undefined"!=typeof window&&"undefined"!=typeof document,Y={isBrowser:!0,classes:{URLSearchParams:$,FormData:Q,Blob:Blob},isStandardBrowserEnv:G,protocols:["http","https","file","blob","url","data"]};function Z(e){function t(e,n,r,o){var i=e[o++],s=Number.isFinite(+i),a=o>=e.length;return i=!i&&P.isArray(r)?r.length:i,a?(P.hasOwnProp(r,i)?r[i]=[r[i],n]:r[i]=n,!s):(r[i]&&P.isObject(r[i])||(r[i]=[]),t(e,n,r[i],o)&&P.isArray(r[i])&&(r[i]=function(e){var t,n,r={},o=Object.keys(e),i=o.length;for(t=0;t<i;t++)r[n=o[t]]=e[n];return r}(r[i])),!s)}if(P.isFormData(e)&&P.isFunction(e.entries)){var n={};return P.forEachEntry(e,(function(e,r){t(function(e){return P.matchAll(/\w+|\[(\w*)]/g,e).map((function(e){return"[]"===e[0]?"":e[1]||e[0]}))}(e),r,n,0)})),n}return null}var ee=Y.isStandardBrowserEnv?{write:function(e,t,n,r,o,i){var s=[];s.push(e+"="+encodeURIComponent(t)),P.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),P.isString(r)&&s.push("path="+r),P.isString(o)&&s.push("domain="+o),!0===i&&s.push("secure"),document.cookie=s.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}};function te(e,t){return e&&!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}var ne=Y.isStandardBrowserEnv?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");function r(e){var r=e;return t&&(n.setAttribute("href",r),r=n.href),n.setAttribute("href",r),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}return e=r(window.location.href),function(t){var n=P.isString(t)?r(t):t;return n.protocol===e.protocol&&n.host===e.host}}():function(){return!0};function re(e,t,n){_.call(this,null==e?"canceled":e,_.ERR_CANCELED,t,n),this.name="CanceledError"}P.inherits(re,_,{__CANCEL__:!0});var oe=P.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ie=Symbol("internals"),se=Symbol("defaults");function ae(e){return e&&String(e).trim().toLowerCase()}function ue(e){return!1===e||null==e?e:String(e)}function ce(e,t,n,r){return P.isFunction(r)?r.call(this,t,n):P.isString(t)?P.isString(r)?-1!==t.indexOf(r):P.isRegExp(r)?r.test(t):void 0:void 0}function fe(e,t){t=t.toLowerCase();for(var n,r=Object.keys(e),o=r.length;o-- >0;)if(t===(n=r[o]).toLowerCase())return n;return null}function le(e,t){e&&this.set(e),this[se]=t||null}function de(e,t){var n=0,r=function(e,t){e=e||10;var n,r=new Array(e),o=new Array(e),i=0,s=0;return t=void 0!==t?t:1e3,function(a){var u=Date.now(),c=o[s];n||(n=u),r[i]=a,o[i]=u;for(var f=s,l=0;f!==i;)l+=r[f++],f%=e;if((i=(i+1)%e)===s&&(s=(s+1)%e),!(u-n<t)){var d=c&&u-c;return d?Math.round(1e3*l/d):void 0}}}(50,250);return function(o){var i=o.loaded,s=o.lengthComputable?o.total:void 0,a=i-n,u=r(a);n=i;var c={loaded:i,total:s,progress:s?i/s:void 0,bytes:a,rate:u||void 0,estimated:u&&s&&i<=s?(s-i)/u:void 0};c[t?"download":"upload"]=!0,e(c)}}function he(e){return new Promise((function(t,n){var r,o=e.data,i=le.from(e.headers).normalize(),s=e.responseType;function a(){e.cancelToken&&e.cancelToken.unsubscribe(r),e.signal&&e.signal.removeEventListener("abort",r)}P.isFormData(o)&&Y.isStandardBrowserEnv&&i.setContentType(!1);var u=new XMLHttpRequest;if(e.auth){var c=e.auth.username||"",f=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(c+":"+f))}var l=te(e.baseURL,e.url);function d(){if(u){var r=le.from("getAllResponseHeaders"in u&&u.getAllResponseHeaders());!function(e,t,n){var r=n.config.validateStatus;n.status&&r&&!r(n.status)?t(new _("Request failed with status code "+n.status,[_.ERR_BAD_REQUEST,_.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}((function(e){t(e),a()}),(function(e){n(e),a()}),{data:s&&"text"!==s&&"json"!==s?u.response:u.responseText,status:u.status,statusText:u.statusText,headers:r,config:e,request:u}),u=null}}if(u.open(e.method.toUpperCase(),V(l,e.params,e.paramsSerializer),!0),u.timeout=e.timeout,"onloadend"in u?u.onloadend=d:u.onreadystatechange=function(){u&&4===u.readyState&&(0!==u.status||u.responseURL&&0===u.responseURL.indexOf("file:"))&&setTimeout(d)},u.onabort=function(){u&&(n(new _("Request aborted",_.ECONNABORTED,e,u)),u=null)},u.onerror=function(){n(new _("Network Error",_.ERR_NETWORK,e,u)),u=null},u.ontimeout=function(){var t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",r=e.transitional||X;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),n(new _(t,r.clarifyTimeoutError?_.ETIMEDOUT:_.ECONNABORTED,e,u)),u=null},Y.isStandardBrowserEnv){var h=(e.withCredentials||ne(l))&&e.xsrfCookieName&&ee.read(e.xsrfCookieName);h&&i.set(e.xsrfHeaderName,h)}void 0===o&&i.setContentType(null),"setRequestHeader"in u&&P.forEach(i.toJSON(),(function(e,t){u.setRequestHeader(t,e)})),P.isUndefined(e.withCredentials)||(u.withCredentials=!!e.withCredentials),s&&"json"!==s&&(u.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&u.addEventListener("progress",de(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&u.upload&&u.upload.addEventListener("progress",de(e.onUploadProgress)),(e.cancelToken||e.signal)&&(r=function(t){u&&(n(!t||t.type?new re(null,e,u):t),u.abort(),u=null)},e.cancelToken&&e.cancelToken.subscribe(r),e.signal&&(e.signal.aborted?r():e.signal.addEventListener("abort",r)));var p,m=(p=/^([-+\w]{1,25})(:?\/\/|:)/.exec(l))&&p[1]||"";m&&-1===Y.protocols.indexOf(m)?n(new _("Unsupported protocol "+m+":",_.ERR_BAD_REQUEST,e)):u.send(o||null)}))}Object.assign(le.prototype,{set:function(e,t,n){var r=this;function o(e,t,n){var o=ae(t);if(!o)throw new Error("header name must be a non-empty string");var i=fe(r,o);(!i||!0===n||!1!==r[i]&&!1!==n)&&(e=P.isArray(e)?e.map(ue):ue(e),r[i||t]=e)}return P.isPlainObject(e)?P.forEach(e,(function(e,n){o(e,n,t)})):o(t,e,n),this},get:function(e,t){if(e=ae(e)){var n=fe(this,e);if(n){var r=this[n];if(!t)return r;if(!0===t)return function(e){for(var t,n=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;t=r.exec(e);)n[t[1]]=t[2];return n}(r);if(P.isFunction(t))return t.call(this,r,n);if(P.isRegExp(t))return t.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}},has:function(e,t){if(e=ae(e)){var n=fe(this,e);return!(!n||t&&!ce(0,this[n],n,t))}return!1},delete:function(e,t){var n=this,r=!1;function o(e){if(e=ae(e)){var o=fe(n,e);!o||t&&!ce(0,n[o],o,t)||(delete n[o],r=!0)}}return P.isArray(e)?e.forEach(o):o(e),r},clear:function(){return Object.keys(this).forEach(this.delete.bind(this))},normalize:function(e){var t=this,n={};return P.forEach(this,(function(r,o){var i=fe(n,o);if(i)return t[i]=ue(r),void delete t[o];var s=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(function(e,t,n){return t.toUpperCase()+n}))}(o):String(o).trim();s!==o&&delete t[o],t[s]=ue(r),n[s]=!0})),this},toJSON:function(){var e=Object.create(null);return P.forEach(Object.assign({},this[se]||null,this),(function(t,n){null!=t&&!1!==t&&(e[n]=P.isArray(t)?t.join(", "):t)})),e}}),Object.assign(le,{from:function(e){return P.isString(e)?new this((i={},(t=e)&&t.split("\n").forEach((function(e){o=e.indexOf(":"),n=e.substring(0,o).trim().toLowerCase(),r=e.substring(o+1).trim(),!n||i[n]&&oe[n]||("set-cookie"===n?i[n]?i[n].push(r):i[n]=[r]:i[n]=i[n]?i[n]+", "+r:r)})),i)):e instanceof this?e:new this(e);var t,n,r,o,i},accessor:function(e){var t=(this[ie]=this[ie]={accessors:{}}).accessors,n=this.prototype;function r(e){var r=ae(e);t[r]||(!function(e,t){var n=P.toCamelCase(" "+t);["get","set","has"].forEach((function(r){Object.defineProperty(e,r+n,{value:function(e,n,o){return this[r].call(this,t,e,n,o)},configurable:!0})}))}(n,e),t[r]=!0)}return P.isArray(e)?e.forEach(r):r(e),this}}),le.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]),P.freezeMethods(le.prototype),P.freezeMethods(le);var pe={http:he,xhr:he},me=function(e){if(P.isString(e)){var t=pe[e];if(!e)throw Error(P.hasOwnProp(e)?"Adapter '".concat(e,"' is not available in the build"):"Can not resolve adapter '".concat(e,"'"));return t}if(!P.isFunction(e))throw new TypeError("adapter is not a function");return e},ve={"Content-Type":"application/x-www-form-urlencoded"};var ye,be={transitional:X,adapter:("undefined"!=typeof XMLHttpRequest?ye=me("xhr"):"undefined"!=typeof process&&"process"===P.kindOf(process)&&(ye=me("http")),ye),transformRequest:[function(e,t){var n,r=t.getContentType()||"",o=r.indexOf("application/json")>-1,i=P.isObject(e);if(i&&P.isHTMLForm(e)&&(e=new FormData(e)),P.isFormData(e))return o&&o?JSON.stringify(Z(e)):e;if(P.isArrayBuffer(e)||P.isBuffer(e)||P.isStream(e)||P.isFile(e)||P.isBlob(e))return e;if(P.isArrayBufferView(e))return e.buffer;if(P.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return z(e,new Y.classes.URLSearchParams,Object.assign({visitor:function(e,t,n,r){return Y.isNode&&P.isBuffer(e)?(this.append(t,e.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((n=P.isFileList(e))||r.indexOf("multipart/form-data")>-1){var s=this.env&&this.env.FormData;return z(n?{"files[]":e}:e,s&&new s,this.formSerializer)}}return i||o?(t.setContentType("application/json",!1),function(e,t,n){if(P.isString(e))try{return(t||JSON.parse)(e),P.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||be.transitional,n=t&&t.forcedJSONParsing,r="json"===this.responseType;if(e&&P.isString(e)&&(n&&!this.responseType||r)){var o=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e)}catch(e){if(o){if("SyntaxError"===e.name)throw _.from(e,_.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Y.classes.FormData,Blob:Y.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};function ge(e,t){var n=this||be,r=t||n,o=le.from(r.headers),i=r.data;return P.forEach(e,(function(e){i=e.call(n,i,o.normalize(),t?t.status:void 0)})),o.normalize(),i}function Ee(e){return!(!e||!e.__CANCEL__)}function we(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new re}function Oe(e){return we(e),e.headers=le.from(e.headers),e.data=ge.call(e,e.transformRequest),(e.adapter||be.adapter)(e).then((function(t){return we(e),t.data=ge.call(e,e.transformResponse,t),t.headers=le.from(t.headers),t}),(function(t){return Ee(t)||(we(e),t&&t.response&&(t.response.data=ge.call(e,e.transformResponse,t.response),t.response.headers=le.from(t.response.headers))),Promise.reject(t)}))}function Re(e,t){t=t||{};var n={};function r(e,t){return P.isPlainObject(e)&&P.isPlainObject(t)?P.merge(e,t):P.isPlainObject(t)?P.merge({},t):P.isArray(t)?t.slice():t}function o(n){return P.isUndefined(t[n])?P.isUndefined(e[n])?void 0:r(void 0,e[n]):r(e[n],t[n])}function i(e){if(!P.isUndefined(t[e]))return r(void 0,t[e])}function s(n){return P.isUndefined(t[n])?P.isUndefined(e[n])?void 0:r(void 0,e[n]):r(void 0,t[n])}function a(n){return n in t?r(e[n],t[n]):n in e?r(void 0,e[n]):void 0}var u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a};return P.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=u[e]||o,r=t(e);P.isUndefined(r)&&t!==a||(n[e]=r)})),n}P.forEach(["delete","get","head"],(function(e){be.headers[e]={}})),P.forEach(["post","put","patch"],(function(e){be.headers[e]=P.merge(ve)}));var Se="1.1.2",Ae={};["object","boolean","number","function","string","symbol"].forEach((function(t,n){Ae[t]=function(r){return e(r)===t||"a"+(n<1?"n ":" ")+t}}));var je={};Ae.transitional=function(e,t,n){function r(e,t){return"[Axios v1.1.2] Transitional option '"+e+"'"+t+(n?". "+n:"")}return function(n,o,i){if(!1===e)throw new _(r(o," has been removed"+(t?" in "+t:"")),_.ERR_DEPRECATED);return t&&!je[o]&&(je[o]=!0,console.warn(r(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,o,i)}};var Te={assertOptions:function(t,n,r){if("object"!==e(t))throw new _("options must be an object",_.ERR_BAD_OPTION_VALUE);for(var o=Object.keys(t),i=o.length;i-- >0;){var s=o[i],a=n[s];if(a){var u=t[s],c=void 0===u||a(u,s,t);if(!0!==c)throw new _("option "+s+" must be "+c,_.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new _("Unknown option "+s,_.ERR_BAD_OPTION)}},validators:Ae},xe=Te.validators,Ce=function(){function e(n){t(this,e),this.defaults=n,this.interceptors={request:new K,response:new K}}return r(e,[{key:"request",value:function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{};var n=(t=Re(this.defaults,t)).transitional;void 0!==n&&Te.assertOptions(n,{silentJSONParsing:xe.transitional(xe.boolean),forcedJSONParsing:xe.transitional(xe.boolean),clarifyTimeoutError:xe.transitional(xe.boolean)},!1),t.method=(t.method||this.defaults.method||"get").toLowerCase();var r=t.headers&&P.merge(t.headers.common,t.headers[t.method]);r&&P.forEach(["delete","get","head","post","put","patch","common"],(function(e){delete t.headers[e]})),t.headers=new le(t.headers,r);var o=[],i=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(i=i&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));var s,a=[];this.interceptors.response.forEach((function(e){a.push(e.fulfilled,e.rejected)}));var u,c=0;if(!i){var f=[Oe.bind(this),void 0];for(f.unshift.apply(f,o),f.push.apply(f,a),u=f.length,s=Promise.resolve(t);c<u;)s=s.then(f[c++],f[c++]);return s}u=o.length;var l=t;for(c=0;c<u;){var d=o[c++],h=o[c++];try{l=d(l)}catch(e){h.call(this,e);break}}try{s=Oe.call(this,l)}catch(e){return Promise.reject(e)}for(c=0,u=a.length;c<u;)s=s.then(a[c++],a[c++]);return s}},{key:"getUri",value:function(e){return V(te((e=Re(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}}]),e}();P.forEach(["delete","get","head","options"],(function(e){Ce.prototype[e]=function(t,n){return this.request(Re(n||{},{method:e,url:t,data:(n||{}).data}))}})),P.forEach(["post","put","patch"],(function(e){function t(t){return function(n,r,o){return this.request(Re(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}Ce.prototype[e]=t(),Ce.prototype[e+"Form"]=t(!0)}));var Ne=function(){function e(n){if(t(this,e),"function"!=typeof n)throw new TypeError("executor must be a function.");var r;this.promise=new Promise((function(e){r=e}));var o=this;this.promise.then((function(e){if(o._listeners){for(var t=o._listeners.length;t-- >0;)o._listeners[t](e);o._listeners=null}})),this.promise.then=function(e){var t,n=new Promise((function(e){o.subscribe(e),t=e})).then(e);return n.cancel=function(){o.unsubscribe(t)},n},n((function(e,t,n){o.reason||(o.reason=new re(e,t,n),r(o.reason))}))}return r(e,[{key:"throwIfRequested",value:function(){if(this.reason)throw this.reason}},{key:"subscribe",value:function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}},{key:"unsubscribe",value:function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}}}],[{key:"source",value:function(){var t;return{token:new e((function(e){t=e})),cancel:t}}}]),e}();var Pe=function e(t){var n=new Ce(t),r=o(Ce.prototype.request,n);return P.extend(r,Ce.prototype,n,{allOwnKeys:!0}),P.extend(r,n,null,{allOwnKeys:!0}),r.create=function(n){return e(Re(t,n))},r}(be);return Pe.Axios=Ce,Pe.CanceledError=re,Pe.CancelToken=Ne,Pe.isCancel=Ee,Pe.VERSION=Se,Pe.toFormData=z,Pe.AxiosError=_,Pe.Cancel=Pe.CanceledError,Pe.all=function(e){return Promise.all(e)},Pe.spread=function(e){return function(t){return e.apply(null,t)}},Pe.isAxiosError=function(e){return P.isObject(e)&&!0===e.isAxiosError},Pe.formToJSON=function(e){return Z(P.isHTMLForm(e)?new FormData(e):e)},Pe})); //# sourceMappingURL=axios.min.js.map
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/web/web_channel.py
Python
import sys import time import web import json import uuid import io from queue import Queue, Empty from bridge.context import * from bridge.reply import Reply, ReplyType from channel.chat_channel import ChatChannel, check_prefix from channel.chat_message import ChatMessage from common.log import logger from common.singleton import singleton from config import conf import os import mimetypes # 添加这行来处理MIME类型 import threading import logging class WebMessage(ChatMessage): def __init__( self, msg_id, content, ctype=ContextType.TEXT, from_user_id="User", to_user_id="Chatgpt", other_user_id="Chatgpt", ): self.msg_id = msg_id self.ctype = ctype self.content = content self.from_user_id = from_user_id self.to_user_id = to_user_id self.other_user_id = other_user_id @singleton class WebChannel(ChatChannel): NOT_SUPPORT_REPLYTYPE = [ReplyType.VOICE] _instance = None # def __new__(cls): # if cls._instance is None: # cls._instance = super(WebChannel, cls).__new__(cls) # return cls._instance def __init__(self): super().__init__() self.msg_id_counter = 0 # 添加消息ID计数器 self.session_queues = {} # 存储session_id到队列的映射 self.request_to_session = {} # 存储request_id到session_id的映射 def _generate_msg_id(self): """生成唯一的消息ID""" self.msg_id_counter += 1 return str(int(time.time())) + str(self.msg_id_counter) def _generate_request_id(self): """生成唯一的请求ID""" return str(uuid.uuid4()) def send(self, reply: Reply, context: Context): try: if reply.type in self.NOT_SUPPORT_REPLYTYPE: logger.warning(f"Web channel doesn't support {reply.type} yet") return if reply.type == ReplyType.IMAGE_URL: time.sleep(0.5) # 获取请求ID和会话ID request_id = context.get("request_id", None) if not request_id: logger.error("No request_id found in context, cannot send message") return # 通过request_id获取session_id session_id = self.request_to_session.get(request_id) if not session_id: logger.error(f"No session_id found for request {request_id}") return # 检查是否有会话队列 if session_id in self.session_queues: # 创建响应数据,包含请求ID以区分不同请求的响应 response_data = { "type": str(reply.type), "content": reply.content, "timestamp": time.time(), "request_id": request_id } self.session_queues[session_id].put(response_data) logger.debug(f"Response sent to queue for session {session_id}, request {request_id}") else: logger.warning(f"No response queue found for session {session_id}, response dropped") except Exception as e: logger.error(f"Error in send method: {e}") def post_message(self): """ Handle incoming messages from users via POST request. Returns a request_id for tracking this specific request. """ try: data = web.data() # 获取原始POST数据 json_data = json.loads(data) session_id = json_data.get('session_id', f'session_{int(time.time())}') prompt = json_data.get('message', '') # 生成请求ID request_id = self._generate_request_id() # 将请求ID与会话ID关联 self.request_to_session[request_id] = session_id # 确保会话队列存在 if session_id not in self.session_queues: self.session_queues[session_id] = Queue() # Web channel 不需要前缀,确保消息能通过前缀检查 trigger_prefixs = conf().get("single_chat_prefix", [""]) if check_prefix(prompt, trigger_prefixs) is None: # 如果没有匹配到前缀,给消息加上第一个前缀 if trigger_prefixs: prompt = trigger_prefixs[0] + prompt logger.debug(f"[WebChannel] Added prefix to message: {prompt}") # 创建消息对象 msg = WebMessage(self._generate_msg_id(), prompt) msg.from_user_id = session_id # 使用会话ID作为用户ID # 创建上下文,明确指定 isgroup=False context = self._compose_context(ContextType.TEXT, prompt, msg=msg, isgroup=False) # 检查 context 是否为 None(可能被插件过滤等) if context is None: logger.warning(f"[WebChannel] Context is None for session {session_id}, message may be filtered") return json.dumps({"status": "error", "message": "Message was filtered"}) # 覆盖必要的字段(_compose_context 会设置默认值,但我们需要使用实际的 session_id) context["session_id"] = session_id context["receiver"] = session_id context["request_id"] = request_id # 异步处理消息 - 只传递上下文 threading.Thread(target=self.produce, args=(context,)).start() # 返回请求ID return json.dumps({"status": "success", "request_id": request_id}) except Exception as e: logger.error(f"Error processing message: {e}") return json.dumps({"status": "error", "message": str(e)}) def poll_response(self): """ Poll for responses using the session_id. """ try: data = web.data() json_data = json.loads(data) session_id = json_data.get('session_id') if not session_id or session_id not in self.session_queues: return json.dumps({"status": "error", "message": "Invalid session ID"}) # 尝试从队列获取响应,不等待 try: # 使用peek而不是get,这样如果前端没有成功处理,下次还能获取到 response = self.session_queues[session_id].get(block=False) # 返回响应,包含请求ID以区分不同请求 return json.dumps({ "status": "success", "has_content": True, "content": response["content"], "request_id": response["request_id"], "timestamp": response["timestamp"] }) except Empty: # 没有新响应 return json.dumps({"status": "success", "has_content": False}) except Exception as e: logger.error(f"Error polling response: {e}") return json.dumps({"status": "error", "message": str(e)}) def chat_page(self): """Serve the chat HTML page.""" file_path = os.path.join(os.path.dirname(__file__), 'chat.html') # 使用绝对路径 with open(file_path, 'r', encoding='utf-8') as f: return f.read() def startup(self): port = conf().get("web_port", 9899) # 打印可用渠道类型提示 logger.info("[WebChannel] 当前channel为web,可修改 config.json 配置文件中的 channel_type 字段进行切换。全部可用类型为:") logger.info("[WebChannel] 1. web - 网页") logger.info("[WebChannel] 2. terminal - 终端") logger.info("[WebChannel] 3. feishu - 飞书") logger.info("[WebChannel] 4. dingtalk - 钉钉") logger.info("[WebChannel] 5. wechatcom_app - 企微自建应用") logger.info("[WebChannel] 6. wechatmp - 个人公众号") logger.info("[WebChannel] 7. wechatmp_service - 企业公众号") logger.info(f"[WebChannel] 🌐 本地访问: http://localhost:{port}/chat") logger.info(f"[WebChannel] 🌍 服务器访问: http://YOUR_IP:{port}/chat (请将YOUR_IP替换为服务器IP)") logger.info("[WebChannel] ✅ Web对话网页已运行") # 确保静态文件目录存在 static_dir = os.path.join(os.path.dirname(__file__), 'static') if not os.path.exists(static_dir): os.makedirs(static_dir) logger.debug(f"[WebChannel] Created static directory: {static_dir}") urls = ( '/', 'RootHandler', '/message', 'MessageHandler', '/poll', 'PollHandler', '/chat', 'ChatHandler', '/config', 'ConfigHandler', '/assets/(.*)', 'AssetsHandler', ) app = web.application(urls, globals(), autoreload=False) # 完全禁用web.py的HTTP日志输出 web.httpserver.LogMiddleware.log = lambda self, status, environ: None # 配置web.py的日志级别为ERROR logging.getLogger("web").setLevel(logging.ERROR) logging.getLogger("web.httpserver").setLevel(logging.ERROR) # 抑制 web.py 默认的服务器启动消息 old_stdout = sys.stdout sys.stdout = io.StringIO() try: web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", port)) finally: sys.stdout = old_stdout class RootHandler: def GET(self): # 重定向到/chat raise web.seeother('/chat') class MessageHandler: def POST(self): return WebChannel().post_message() class PollHandler: def POST(self): return WebChannel().poll_response() class ChatHandler: def GET(self): # 正常返回聊天页面 file_path = os.path.join(os.path.dirname(__file__), 'chat.html') with open(file_path, 'r', encoding='utf-8') as f: return f.read() class ConfigHandler: def GET(self): """返回前端需要的配置信息""" try: use_agent = conf().get("agent", False) if use_agent: title = "CowAgent" subtitle = "我可以帮你解答问题、管理计算机、创造和执行技能,并通过长期记忆不断成长" else: title = "AI 助手" subtitle = "我可以回答问题、提供信息或者帮助您完成各种任务" return json.dumps({ "status": "success", "use_agent": use_agent, "title": title, "subtitle": subtitle }) except Exception as e: logger.error(f"Error getting config: {e}") return json.dumps({"status": "error", "message": str(e)}) class AssetsHandler: def GET(self, file_path): # 修改默认参数 try: # 如果请求是/static/,需要处理 if file_path == '': # 返回目录列表... pass # 获取当前文件的绝对路径 current_dir = os.path.dirname(os.path.abspath(__file__)) static_dir = os.path.join(current_dir, 'static') full_path = os.path.normpath(os.path.join(static_dir, file_path)) # 安全检查:确保请求的文件在static目录内 if not os.path.abspath(full_path).startswith(os.path.abspath(static_dir)): logger.error(f"Security check failed for path: {full_path}") raise web.notfound() if not os.path.exists(full_path) or not os.path.isfile(full_path): logger.error(f"File not found: {full_path}") raise web.notfound() # 设置正确的Content-Type content_type = mimetypes.guess_type(full_path)[0] if content_type: web.header('Content-Type', content_type) else: # 默认为二进制流 web.header('Content-Type', 'application/octet-stream') # 读取并返回文件内容 with open(full_path, 'rb') as f: return f.read() except Exception as e: logger.error(f"Error serving static file: {e}", exc_info=True) # 添加更详细的错误信息 raise web.notfound()
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechat/wcf_channel.py
Python
# encoding:utf-8 """ wechat channel """ import io import json import os import threading import time from queue import Empty from typing import Any from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel.wechat.wcf_message import WechatfMessage from common.log import logger from common.singleton import singleton from common.utils import * from config import conf, get_appdata_dir from wcferry import Wcf, WxMsg @singleton class WechatfChannel(ChatChannel): NOT_SUPPORT_REPLYTYPE = [] def __init__(self): super().__init__() self.NOT_SUPPORT_REPLYTYPE = [] # 使用字典存储最近消息,用于去重 self.received_msgs = {} # 初始化wcferry客户端 self.wcf = Wcf() self.wxid = None # 登录后会被设置为当前登录用户的wxid def startup(self): """ 启动通道 """ try: # wcferry会自动唤起微信并登录 self.wxid = self.wcf.get_self_wxid() self.name = self.wcf.get_user_info().get("name") logger.info(f"微信登录成功,当前用户ID: {self.wxid}, 用户名:{self.name}") self.contact_cache = ContactCache(self.wcf) self.contact_cache.update() # 启动消息接收 self.wcf.enable_receiving_msg() # 创建消息处理线程 t = threading.Thread(target=self._process_messages, name="WeChatThread", daemon=True) t.start() except Exception as e: logger.error(f"微信通道启动失败: {e}") raise e def _process_messages(self): """ 处理消息队列 """ while True: try: msg = self.wcf.get_msg() if msg: self._handle_message(msg) except Empty: continue except Exception as e: logger.error(f"处理消息失败: {e}") continue def _handle_message(self, msg: WxMsg): """ 处理单条消息 """ try: # 构造消息对象 cmsg = WechatfMessage(self, msg) # 消息去重 if cmsg.msg_id in self.received_msgs: return self.received_msgs[cmsg.msg_id] = time.time() # 清理过期消息ID self._clean_expired_msgs() logger.debug(f"收到消息: {msg}") context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=cmsg.is_group, msg=cmsg) if context: self.produce(context) except Exception as e: logger.error(f"处理消息失败: {e}") def _clean_expired_msgs(self, expire_time: float = 60): """ 清理过期的消息ID """ now = time.time() for msg_id in list(self.received_msgs.keys()): if now - self.received_msgs[msg_id] > expire_time: del self.received_msgs[msg_id] def send(self, reply: Reply, context: Context): """ 发送消息 """ receiver = context["receiver"] if not receiver: logger.error("receiver is empty") return try: if reply.type == ReplyType.TEXT: # 处理@信息 at_list = [] if context.get("isgroup"): if context["msg"].actual_user_id: at_list = [context["msg"].actual_user_id] at_str = ",".join(at_list) if at_list else "" self.wcf.send_text(reply.content, receiver, at_str) elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO: self.wcf.send_text(reply.content, receiver) else: logger.error(f"暂不支持的消息类型: {reply.type}") except Exception as e: logger.error(f"发送消息失败: {e}") def close(self): """ 关闭通道 """ try: self.wcf.cleanup() except Exception as e: logger.error(f"关闭通道失败: {e}") class ContactCache: def __init__(self, wcf): """ wcf: 一个 wcfferry.client.Wcf 实例 """ self.wcf = wcf self._contact_map = {} # 形如 {wxid: {完整联系人信息}} def update(self): """ 更新缓存:调用 get_contacts(), 再把 wcf.contacts 构建成 {wxid: {完整信息}} 的字典 """ self.wcf.get_contacts() self._contact_map.clear() for item in self.wcf.contacts: wxid = item.get('wxid') if wxid: # 确保有 wxid 字段 self._contact_map[wxid] = item def get_contact(self, wxid: str) -> dict: """ 返回该 wxid 对应的完整联系人 dict, 如果没找到就返回 None """ return self._contact_map.get(wxid) def get_name_by_wxid(self, wxid: str) -> str: """ 通过wxid,获取成员/群名称 """ contact = self.get_contact(wxid) if contact: return contact.get('name', '') return ''
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechat/wcf_message.py
Python
# encoding:utf-8 """ wechat channel message """ from bridge.context import ContextType from channel.chat_message import ChatMessage from common.log import logger from wcferry import WxMsg class WechatfMessage(ChatMessage): """ 微信消息封装类 """ def __init__(self, channel, wcf_msg: WxMsg, is_group=False): """ 初始化消息对象 :param wcf_msg: wcferry消息对象 :param is_group: 是否是群消息 """ super().__init__(wcf_msg) self.msg_id = wcf_msg.id self.create_time = wcf_msg.ts # 使用消息时间戳 self.is_group = is_group or wcf_msg._is_group self.wxid = channel.wxid self.name = channel.name # 解析消息类型 if wcf_msg.is_text(): self.ctype = ContextType.TEXT self.content = wcf_msg.content else: raise NotImplementedError(f"Unsupported message type: {wcf_msg.type}") # 设置发送者和接收者信息 self.from_user_id = self.wxid if wcf_msg.sender == self.wxid else wcf_msg.sender self.from_user_nickname = self.name if wcf_msg.sender == self.wxid else channel.contact_cache.get_name_by_wxid(wcf_msg.sender) self.to_user_id = self.wxid self.to_user_nickname = self.name self.other_user_id = wcf_msg.sender self.other_user_nickname = channel.contact_cache.get_name_by_wxid(wcf_msg.sender) # 群消息特殊处理 if self.is_group: self.other_user_id = wcf_msg.roomid self.other_user_nickname = channel.contact_cache.get_name_by_wxid(wcf_msg.roomid) self.actual_user_id = wcf_msg.sender self.actual_user_nickname = channel.wcf.get_alias_in_chatroom(wcf_msg.sender, wcf_msg.roomid) if not self.actual_user_nickname: # 群聊获取不到企微号成员昵称,这里尝试从联系人缓存去获取 self.actual_user_nickname = channel.contact_cache.get_name_by_wxid(wcf_msg.sender) self.room_id = wcf_msg.roomid self.is_at = wcf_msg.is_at(self.wxid) # 是否被@当前登录用户 # 判断是否是自己发送的消息 self.my_msg = wcf_msg.from_self()
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechat/wechat_channel.py
Python
# encoding:utf-8 """ wechat channel """ import io import json import os import threading import time import requests from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel import chat_channel from channel.wechat.wechat_message import * from common.expired_dict import ExpiredDict from common.log import logger from common.singleton import singleton from common.time_check import time_checker from common.utils import convert_webp_to_png, remove_markdown_symbol from config import conf, get_appdata_dir from lib import itchat from lib.itchat.content import * @itchat.msg_register([TEXT, VOICE, PICTURE, NOTE, ATTACHMENT, SHARING]) def handler_single_msg(msg): try: cmsg = WechatMessage(msg, False) except NotImplementedError as e: logger.debug("[WX]single message {} skipped: {}".format(msg["MsgId"], e)) return None WechatChannel().handle_single(cmsg) return None @itchat.msg_register([TEXT, VOICE, PICTURE, NOTE, ATTACHMENT, SHARING], isGroupChat=True) def handler_group_msg(msg): try: cmsg = WechatMessage(msg, True) except NotImplementedError as e: logger.debug("[WX]group message {} skipped: {}".format(msg["MsgId"], e)) return None WechatChannel().handle_group(cmsg) return None def _check(func): def wrapper(self, cmsg: ChatMessage): msgId = cmsg.msg_id if msgId in self.receivedMsgs: logger.info("Wechat message {} already received, ignore".format(msgId)) return self.receivedMsgs[msgId] = True create_time = cmsg.create_time # 消息时间戳 if conf().get("hot_reload") == True and int(create_time) < int(time.time()) - 60: # 跳过1分钟前的历史消息 logger.debug("[WX]history message {} skipped".format(msgId)) return if cmsg.my_msg and not cmsg.is_group: logger.debug("[WX]my message {} skipped".format(msgId)) return return func(self, cmsg) return wrapper # 可用的二维码生成接口 # https://api.qrserver.com/v1/create-qr-code/?size=400×400&data=https://www.abc.com # https://api.isoyu.com/qr/?m=1&e=L&p=20&url=https://www.abc.com def qrCallback(uuid, status, qrcode): # logger.debug("qrCallback: {} {}".format(uuid,status)) if status == "0": try: from PIL import Image img = Image.open(io.BytesIO(qrcode)) _thread = threading.Thread(target=img.show, args=("QRCode",)) _thread.setDaemon(True) _thread.start() except Exception as e: pass import qrcode url = f"https://login.weixin.qq.com/l/{uuid}" qr_api1 = "https://api.isoyu.com/qr/?m=1&e=L&p=20&url={}".format(url) qr_api2 = "https://api.qrserver.com/v1/create-qr-code/?size=400×400&data={}".format(url) qr_api3 = "https://api.pwmqr.com/qrcode/create/?url={}".format(url) qr_api4 = "https://my.tv.sohu.com/user/a/wvideo/getQRCode.do?text={}".format(url) print("You can also scan QRCode in any website below:") print(qr_api3) print(qr_api4) print(qr_api2) print(qr_api1) _send_qr_code([qr_api3, qr_api4, qr_api2, qr_api1]) qr = qrcode.QRCode(border=1) qr.add_data(url) qr.make(fit=True) try: qr.print_ascii(invert=True) except UnicodeEncodeError: print("ASCII QR code printing failed due to encoding issues.") @singleton class WechatChannel(ChatChannel): NOT_SUPPORT_REPLYTYPE = [] def __init__(self): super().__init__() self.receivedMsgs = ExpiredDict(conf().get("expires_in_seconds", 3600)) self.auto_login_times = 0 def startup(self): try: time.sleep(3) logger.error("""[WechatChannel] 当前channel暂不可用,目前支持的channel有: 1. terminal: 终端 2. wechatmp: 个人公众号 3. wechatmp_service: 企业公众号 4. wechatcom_app: 企微自建应用 5. dingtalk: 钉钉 6. feishu: 飞书 7. web: 网页 8. wcf: wechat (需Windows环境,参考 https://github.com/zhayujie/chatgpt-on-wechat/pull/2562 ) 可修改 config.json 配置文件的 channel_type 字段进行切换""") # itchat.instance.receivingRetryCount = 600 # 修改断线超时时间 # # login by scan QRCode # hotReload = conf().get("hot_reload", False) # status_path = os.path.join(get_appdata_dir(), "itchat.pkl") # itchat.auto_login( # enableCmdQR=2, # hotReload=hotReload, # statusStorageDir=status_path, # qrCallback=qrCallback, # exitCallback=self.exitCallback, # loginCallback=self.loginCallback # ) # self.user_id = itchat.instance.storageClass.userName # self.name = itchat.instance.storageClass.nickName # logger.info("Wechat login success, user_id: {}, nickname: {}".format(self.user_id, self.name)) # # start message listener # itchat.run() except Exception as e: logger.exception(e) def exitCallback(self): try: from common.linkai_client import chat_client if chat_client.client_id and conf().get("use_linkai"): _send_logout() time.sleep(2) self.auto_login_times += 1 if self.auto_login_times < 100: chat_channel.handler_pool._shutdown = False self.startup() except Exception as e: pass def loginCallback(self): logger.debug("Login success") _send_login_success() # handle_* 系列函数处理收到的消息后构造Context,然后传入produce函数中处理Context和发送回复 # Context包含了消息的所有信息,包括以下属性 # type 消息类型, 包括TEXT、VOICE、IMAGE_CREATE # content 消息内容,如果是TEXT类型,content就是文本内容,如果是VOICE类型,content就是语音文件名,如果是IMAGE_CREATE类型,content就是图片生成命令 # kwargs 附加参数字典,包含以下的key: # session_id: 会话id # isgroup: 是否是群聊 # receiver: 需要回复的对象 # msg: ChatMessage消息对象 # origin_ctype: 原始消息类型,语音转文字后,私聊时如果匹配前缀失败,会根据初始消息是否是语音来放宽触发规则 # desire_rtype: 希望回复类型,默认是文本回复,设置为ReplyType.VOICE是语音回复 @time_checker @_check def handle_single(self, cmsg: ChatMessage): # filter system message if cmsg.other_user_id in ["weixin"]: return if cmsg.ctype == ContextType.VOICE: if conf().get("speech_recognition") != True: return logger.debug("[WX]receive voice msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.IMAGE: logger.debug("[WX]receive image msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.PATPAT: logger.debug("[WX]receive patpat msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.TEXT: logger.debug("[WX]receive text msg: {}, cmsg={}".format(json.dumps(cmsg._rawmsg, ensure_ascii=False), cmsg)) else: logger.debug("[WX]receive msg: {}, cmsg={}".format(cmsg.content, cmsg)) context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=False, msg=cmsg) if context: self.produce(context) @time_checker @_check def handle_group(self, cmsg: ChatMessage): if cmsg.ctype == ContextType.VOICE: if conf().get("group_speech_recognition") != True: return logger.debug("[WX]receive voice for group msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.IMAGE: logger.debug("[WX]receive image for group msg: {}".format(cmsg.content)) elif cmsg.ctype in [ContextType.JOIN_GROUP, ContextType.PATPAT, ContextType.ACCEPT_FRIEND, ContextType.EXIT_GROUP]: logger.debug("[WX]receive note msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.TEXT: # logger.debug("[WX]receive group msg: {}, cmsg={}".format(json.dumps(cmsg._rawmsg, ensure_ascii=False), cmsg)) pass elif cmsg.ctype == ContextType.FILE: logger.debug(f"[WX]receive attachment msg, file_name={cmsg.content}") else: logger.debug("[WX]receive group msg: {}".format(cmsg.content)) context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=True, msg=cmsg, no_need_at=conf().get("no_need_at", False)) if context: self.produce(context) # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息 def send(self, reply: Reply, context: Context): receiver = context["receiver"] if reply.type == ReplyType.TEXT: reply.content = remove_markdown_symbol(reply.content) itchat.send(reply.content, toUserName=receiver) logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver)) elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO: reply.content = remove_markdown_symbol(reply.content) itchat.send(reply.content, toUserName=receiver) logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver)) elif reply.type == ReplyType.VOICE: itchat.send_file(reply.content, toUserName=receiver) logger.info("[WX] sendFile={}, receiver={}".format(reply.content, receiver)) elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片 img_url = reply.content logger.debug(f"[WX] start download image, img_url={img_url}") pic_res = requests.get(img_url, stream=True) image_storage = io.BytesIO() size = 0 for block in pic_res.iter_content(1024): size += len(block) image_storage.write(block) logger.info(f"[WX] download image success, size={size}, img_url={img_url}") image_storage.seek(0) if ".webp" in img_url: try: image_storage = convert_webp_to_png(image_storage) except Exception as e: logger.error(f"Failed to convert image: {e}") return itchat.send_image(image_storage, toUserName=receiver) logger.info("[WX] sendImage url={}, receiver={}".format(img_url, receiver)) elif reply.type == ReplyType.IMAGE: # 从文件读取图片 image_storage = reply.content image_storage.seek(0) itchat.send_image(image_storage, toUserName=receiver) logger.info("[WX] sendImage, receiver={}".format(receiver)) elif reply.type == ReplyType.FILE: # 新增文件回复类型 file_storage = reply.content itchat.send_file(file_storage, toUserName=receiver) logger.info("[WX] sendFile, receiver={}".format(receiver)) elif reply.type == ReplyType.VIDEO: # 新增视频回复类型 video_storage = reply.content itchat.send_video(video_storage, toUserName=receiver) logger.info("[WX] sendFile, receiver={}".format(receiver)) elif reply.type == ReplyType.VIDEO_URL: # 新增视频URL回复类型 video_url = reply.content logger.debug(f"[WX] start download video, video_url={video_url}") video_res = requests.get(video_url, stream=True) video_storage = io.BytesIO() size = 0 for block in video_res.iter_content(1024): size += len(block) video_storage.write(block) logger.info(f"[WX] download video success, size={size}, video_url={video_url}") video_storage.seek(0) itchat.send_video(video_storage, toUserName=receiver) logger.info("[WX] sendVideo url={}, receiver={}".format(video_url, receiver)) def _send_login_success(): try: from common.linkai_client import chat_client if chat_client.client_id: chat_client.send_login_success() except Exception as e: pass def _send_logout(): try: from common.linkai_client import chat_client if chat_client.client_id: chat_client.send_logout() except Exception as e: pass def _send_qr_code(qrcode_list: list): try: from common.linkai_client import chat_client if chat_client.client_id: chat_client.send_qrcode(qrcode_list) except Exception as e: pass
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechat/wechat_message.py
Python
import re from bridge.context import ContextType from channel.chat_message import ChatMessage from common.log import logger from common.tmp_dir import TmpDir from lib import itchat from lib.itchat.content import * class WechatMessage(ChatMessage): def __init__(self, itchat_msg, is_group=False): super().__init__(itchat_msg) self.msg_id = itchat_msg["MsgId"] self.create_time = itchat_msg["CreateTime"] self.is_group = is_group notes_join_group = ["加入群聊", "加入了群聊", "invited", "joined"] # 可通过添加对应语言的加入群聊通知中的关键词适配更多 notes_bot_join_group = ["邀请你", "invited you", "You've joined", "你通过扫描"] notes_exit_group = ["移出了群聊", "removed"] # 可通过添加对应语言的踢出群聊通知中的关键词适配更多 notes_patpat = ["拍了拍我", "tickled my", "tickled me"] # 可通过添加对应语言的拍一拍通知中的关键词适配更多 if itchat_msg["Type"] == TEXT: self.ctype = ContextType.TEXT self.content = itchat_msg["Text"] elif itchat_msg["Type"] == VOICE: self.ctype = ContextType.VOICE self.content = TmpDir().path() + itchat_msg["FileName"] # content直接存临时目录路径 self._prepare_fn = lambda: itchat_msg.download(self.content) elif itchat_msg["Type"] == PICTURE and itchat_msg["MsgType"] == 3: self.ctype = ContextType.IMAGE self.content = TmpDir().path() + itchat_msg["FileName"] # content直接存临时目录路径 self._prepare_fn = lambda: itchat_msg.download(self.content) elif itchat_msg["Type"] == NOTE and itchat_msg["MsgType"] == 10000: if is_group: if any(note_bot_join_group in itchat_msg["Content"] for note_bot_join_group in notes_bot_join_group): # 邀请机器人加入群聊 logger.warn("机器人加入群聊消息,不处理~") pass elif any(note_join_group in itchat_msg["Content"] for note_join_group in notes_join_group): # 若有任何在notes_join_group列表中的字符串出现在NOTE中 # 这里只能得到nickname, actual_user_id还是机器人的id if "加入群聊" not in itchat_msg["Content"]: self.ctype = ContextType.JOIN_GROUP self.content = itchat_msg["Content"] if "invited" in itchat_msg["Content"]: # 匹配英文信息 self.actual_user_nickname = re.findall(r'invited\s+(.+?)\s+to\s+the\s+group\s+chat', itchat_msg["Content"])[0] elif "joined" in itchat_msg["Content"]: # 匹配通过二维码加入的英文信息 self.actual_user_nickname = re.findall(r'"(.*?)" joined the group chat via the QR Code shared by', itchat_msg["Content"])[0] elif "加入了群聊" in itchat_msg["Content"]: self.actual_user_nickname = re.findall(r"\"(.*?)\"", itchat_msg["Content"])[-1] elif "加入群聊" in itchat_msg["Content"]: self.ctype = ContextType.JOIN_GROUP self.content = itchat_msg["Content"] self.actual_user_nickname = re.findall(r"\"(.*?)\"", itchat_msg["Content"])[0] elif any(note_exit_group in itchat_msg["Content"] for note_exit_group in notes_exit_group): # 若有任何在notes_exit_group列表中的字符串出现在NOTE中 self.ctype = ContextType.EXIT_GROUP self.content = itchat_msg["Content"] self.actual_user_nickname = re.findall(r"\"(.*?)\"", itchat_msg["Content"])[0] elif any(note_patpat in itchat_msg["Content"] for note_patpat in notes_patpat): # 若有任何在notes_patpat列表中的字符串出现在NOTE中: self.ctype = ContextType.PATPAT self.content = itchat_msg["Content"] if "拍了拍我" in itchat_msg["Content"]: # 识别中文 self.actual_user_nickname = re.findall(r"\"(.*?)\"", itchat_msg["Content"])[0] elif "tickled my" in itchat_msg["Content"] or "tickled me" in itchat_msg["Content"]: self.actual_user_nickname = re.findall(r'^(.*?)(?:tickled my|tickled me)', itchat_msg["Content"])[0] else: raise NotImplementedError("Unsupported note message: " + itchat_msg["Content"]) elif "你已添加了" in itchat_msg["Content"]: #通过好友请求 self.ctype = ContextType.ACCEPT_FRIEND self.content = itchat_msg["Content"] elif any(note_patpat in itchat_msg["Content"] for note_patpat in notes_patpat): # 若有任何在notes_patpat列表中的字符串出现在NOTE中: self.ctype = ContextType.PATPAT self.content = itchat_msg["Content"] else: raise NotImplementedError("Unsupported note message: " + itchat_msg["Content"]) elif itchat_msg["Type"] == ATTACHMENT: self.ctype = ContextType.FILE self.content = TmpDir().path() + itchat_msg["FileName"] # content直接存临时目录路径 self._prepare_fn = lambda: itchat_msg.download(self.content) elif itchat_msg["Type"] == SHARING: self.ctype = ContextType.SHARING self.content = itchat_msg.get("Url") else: raise NotImplementedError("Unsupported message type: Type:{} MsgType:{}".format(itchat_msg["Type"], itchat_msg["MsgType"])) self.from_user_id = itchat_msg["FromUserName"] self.to_user_id = itchat_msg["ToUserName"] user_id = itchat.instance.storageClass.userName nickname = itchat.instance.storageClass.nickName # 虽然from_user_id和to_user_id用的少,但是为了保持一致性,还是要填充一下 # 以下很繁琐,一句话总结:能填的都填了。 if self.from_user_id == user_id: self.from_user_nickname = nickname if self.to_user_id == user_id: self.to_user_nickname = nickname try: # 陌生人时候, User字段可能不存在 # my_msg 为True是表示是自己发送的消息 self.my_msg = itchat_msg["ToUserName"] == itchat_msg["User"]["UserName"] and \ itchat_msg["ToUserName"] != itchat_msg["FromUserName"] self.other_user_id = itchat_msg["User"]["UserName"] self.other_user_nickname = itchat_msg["User"]["NickName"] if self.other_user_id == self.from_user_id: self.from_user_nickname = self.other_user_nickname if self.other_user_id == self.to_user_id: self.to_user_nickname = self.other_user_nickname if itchat_msg["User"].get("Self"): # 自身的展示名,当设置了群昵称时,该字段表示群昵称 self.self_display_name = itchat_msg["User"].get("Self").get("DisplayName") except KeyError as e: # 处理偶尔没有对方信息的情况 logger.warn("[WX]get other_user_id failed: " + str(e)) if self.from_user_id == user_id: self.other_user_id = self.to_user_id else: self.other_user_id = self.from_user_id if self.is_group: self.is_at = itchat_msg["IsAt"] self.actual_user_id = itchat_msg["ActualUserName"] if self.ctype not in [ContextType.JOIN_GROUP, ContextType.PATPAT, ContextType.EXIT_GROUP]: self.actual_user_nickname = itchat_msg["ActualNickName"]
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechat/wechaty_channel.py
Python
# encoding:utf-8 """ wechaty channel Python Wechaty - https://github.com/wechaty/python-wechaty """ import asyncio import base64 import os import time from wechaty import Contact, Wechaty from wechaty.user import Message from wechaty_puppet import FileBox from bridge.context import * from bridge.context import Context from bridge.reply import * from channel.chat_channel import ChatChannel from channel.wechat.wechaty_message import WechatyMessage from common.log import logger from common.singleton import singleton from config import conf try: from voice.audio_convert import any_to_sil except Exception as e: pass @singleton class WechatyChannel(ChatChannel): NOT_SUPPORT_REPLYTYPE = [] def __init__(self): super().__init__() def startup(self): config = conf() token = config.get("wechaty_puppet_service_token") os.environ["WECHATY_PUPPET_SERVICE_TOKEN"] = token asyncio.run(self.main()) async def main(self): loop = asyncio.get_event_loop() # 将asyncio的loop传入处理线程 self.handler_pool._initializer = lambda: asyncio.set_event_loop(loop) self.bot = Wechaty() self.bot.on("login", self.on_login) self.bot.on("message", self.on_message) await self.bot.start() async def on_login(self, contact: Contact): self.user_id = contact.contact_id self.name = contact.name logger.info("[WX] login user={}".format(contact)) # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息 def send(self, reply: Reply, context: Context): receiver_id = context["receiver"] loop = asyncio.get_event_loop() if context["isgroup"]: receiver = asyncio.run_coroutine_threadsafe(self.bot.Room.find(receiver_id), loop).result() else: receiver = asyncio.run_coroutine_threadsafe(self.bot.Contact.find(receiver_id), loop).result() msg = None if reply.type == ReplyType.TEXT: msg = reply.content asyncio.run_coroutine_threadsafe(receiver.say(msg), loop).result() logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver)) elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO: msg = reply.content asyncio.run_coroutine_threadsafe(receiver.say(msg), loop).result() logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver)) elif reply.type == ReplyType.VOICE: voiceLength = None file_path = reply.content sil_file = os.path.splitext(file_path)[0] + ".sil" voiceLength = int(any_to_sil(file_path, sil_file)) if voiceLength >= 60000: voiceLength = 60000 logger.info("[WX] voice too long, length={}, set to 60s".format(voiceLength)) # 发送语音 t = int(time.time()) msg = FileBox.from_file(sil_file, name=str(t) + ".sil") if voiceLength is not None: msg.metadata["voiceLength"] = voiceLength asyncio.run_coroutine_threadsafe(receiver.say(msg), loop).result() try: os.remove(file_path) if sil_file != file_path: os.remove(sil_file) except Exception as e: pass logger.info("[WX] sendVoice={}, receiver={}".format(reply.content, receiver)) elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片 img_url = reply.content t = int(time.time()) msg = FileBox.from_url(url=img_url, name=str(t) + ".png") asyncio.run_coroutine_threadsafe(receiver.say(msg), loop).result() logger.info("[WX] sendImage url={}, receiver={}".format(img_url, receiver)) elif reply.type == ReplyType.IMAGE: # 从文件读取图片 image_storage = reply.content image_storage.seek(0) t = int(time.time()) msg = FileBox.from_base64(base64.b64encode(image_storage.read()), str(t) + ".png") asyncio.run_coroutine_threadsafe(receiver.say(msg), loop).result() logger.info("[WX] sendImage, receiver={}".format(receiver)) async def on_message(self, msg: Message): """ listen for message event """ try: cmsg = await WechatyMessage(msg) except NotImplementedError as e: logger.debug("[WX] {}".format(e)) return except Exception as e: logger.exception("[WX] {}".format(e)) return logger.debug("[WX] message:{}".format(cmsg)) room = msg.room() # 获取消息来自的群聊. 如果消息不是来自群聊, 则返回None isgroup = room is not None ctype = cmsg.ctype context = self._compose_context(ctype, cmsg.content, isgroup=isgroup, msg=cmsg) if context: logger.info("[WX] receiveMsg={}, context={}".format(cmsg, context)) self.produce(context)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechat/wechaty_message.py
Python
import asyncio import re from wechaty import MessageType from wechaty.user import Message from bridge.context import ContextType from channel.chat_message import ChatMessage from common.log import logger from common.tmp_dir import TmpDir class aobject(object): """Inheriting this class allows you to define an async __init__. So you can create objects by doing something like `await MyClass(params)` """ async def __new__(cls, *a, **kw): instance = super().__new__(cls) await instance.__init__(*a, **kw) return instance async def __init__(self): pass class WechatyMessage(ChatMessage, aobject): async def __init__(self, wechaty_msg: Message): super().__init__(wechaty_msg) room = wechaty_msg.room() self.msg_id = wechaty_msg.message_id self.create_time = wechaty_msg.payload.timestamp self.is_group = room is not None if wechaty_msg.type() == MessageType.MESSAGE_TYPE_TEXT: self.ctype = ContextType.TEXT self.content = wechaty_msg.text() elif wechaty_msg.type() == MessageType.MESSAGE_TYPE_AUDIO: self.ctype = ContextType.VOICE voice_file = await wechaty_msg.to_file_box() self.content = TmpDir().path() + voice_file.name # content直接存临时目录路径 def func(): loop = asyncio.get_event_loop() asyncio.run_coroutine_threadsafe(voice_file.to_file(self.content), loop).result() self._prepare_fn = func else: raise NotImplementedError("Unsupported message type: {}".format(wechaty_msg.type())) from_contact = wechaty_msg.talker() # 获取消息的发送者 self.from_user_id = from_contact.contact_id self.from_user_nickname = from_contact.name # group中的from和to,wechaty跟itchat含义不一样 # wecahty: from是消息实际发送者, to:所在群 # itchat: 如果是你发送群消息,from和to是你自己和所在群,如果是别人发群消息,from和to是所在群和你自己 # 但这个差别不影响逻辑,group中只使用到:1.用from来判断是否是自己发的,2.actual_user_id来判断实际发送用户 if self.is_group: self.to_user_id = room.room_id self.to_user_nickname = await room.topic() else: to_contact = wechaty_msg.to() self.to_user_id = to_contact.contact_id self.to_user_nickname = to_contact.name if self.is_group or wechaty_msg.is_self(): # 如果是群消息,other_user设置为群,如果是私聊消息,而且自己发的,就设置成对方。 self.other_user_id = self.to_user_id self.other_user_nickname = self.to_user_nickname else: self.other_user_id = self.from_user_id self.other_user_nickname = self.from_user_nickname if self.is_group: # wechaty群聊中,实际发送用户就是from_user self.is_at = await wechaty_msg.mention_self() if not self.is_at: # 有时候复制粘贴的消息,不算做@,但是内容里面会有@xxx,这里做一下兼容 name = wechaty_msg.wechaty.user_self().name pattern = f"@{re.escape(name)}(\u2005|\u0020)" if re.search(pattern, self.content): logger.debug(f"wechaty message {self.msg_id} include at") self.is_at = True self.actual_user_id = self.from_user_id self.actual_user_nickname = self.from_user_nickname
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechatcom/wechatcomapp_channel.py
Python
# -*- coding=utf-8 -*- import io import os import sys import time import requests import web from wechatpy.enterprise import create_reply, parse_message from wechatpy.enterprise.crypto import WeChatCrypto from wechatpy.enterprise.exceptions import InvalidCorpIdException from wechatpy.exceptions import InvalidSignatureException, WeChatClientException from bridge.context import Context from bridge.reply import Reply, ReplyType from channel.chat_channel import ChatChannel from channel.wechatcom.wechatcomapp_client import WechatComAppClient from channel.wechatcom.wechatcomapp_message import WechatComAppMessage from common.log import logger from common.singleton import singleton from common.utils import compress_imgfile, fsize, split_string_by_utf8_length, convert_webp_to_png, remove_markdown_symbol from config import conf, subscribe_msg from voice.audio_convert import any_to_amr, split_audio MAX_UTF8_LEN = 2048 @singleton class WechatComAppChannel(ChatChannel): NOT_SUPPORT_REPLYTYPE = [] def __init__(self): super().__init__() self.corp_id = conf().get("wechatcom_corp_id") self.secret = conf().get("wechatcomapp_secret") self.agent_id = conf().get("wechatcomapp_agent_id") self.token = conf().get("wechatcomapp_token") self.aes_key = conf().get("wechatcomapp_aes_key") logger.info( "[wechatcom] Initializing WeCom app channel, corp_id: {}, agent_id: {}".format(self.corp_id, self.agent_id) ) self.crypto = WeChatCrypto(self.token, self.aes_key, self.corp_id) self.client = WechatComAppClient(self.corp_id, self.secret) def startup(self): # start message listener urls = ("/wxcomapp/?", "channel.wechatcom.wechatcomapp_channel.Query") app = web.application(urls, globals(), autoreload=False) port = conf().get("wechatcomapp_port", 9898) logger.info("[wechatcom] ✅ WeCom app channel started successfully") logger.info("[wechatcom] 📡 Listening on http://0.0.0.0:{}/wxcomapp/".format(port)) logger.info("[wechatcom] 🤖 Ready to receive messages") # Suppress web.py's default server startup message old_stdout = sys.stdout sys.stdout = io.StringIO() try: web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", port)) finally: sys.stdout = old_stdout def send(self, reply: Reply, context: Context): receiver = context["receiver"] if reply.type in [ReplyType.TEXT, ReplyType.ERROR, ReplyType.INFO]: reply_text = remove_markdown_symbol(reply.content) texts = split_string_by_utf8_length(reply_text, MAX_UTF8_LEN) if len(texts) > 1: logger.info("[wechatcom] text too long, split into {} parts".format(len(texts))) for i, text in enumerate(texts): self.client.message.send_text(self.agent_id, receiver, text) if i != len(texts) - 1: time.sleep(0.5) # 休眠0.5秒,防止发送过快乱序 logger.info("[wechatcom] Do send text to {}: {}".format(receiver, reply_text)) elif reply.type == ReplyType.VOICE: try: media_ids = [] file_path = reply.content amr_file = os.path.splitext(file_path)[0] + ".amr" any_to_amr(file_path, amr_file) duration, files = split_audio(amr_file, 60 * 1000) if len(files) > 1: logger.info("[wechatcom] voice too long {}s > 60s , split into {} parts".format(duration / 1000.0, len(files))) for path in files: response = self.client.media.upload("voice", open(path, "rb")) logger.debug("[wechatcom] upload voice response: {}".format(response)) media_ids.append(response["media_id"]) except ImportError as e: logger.error("[wechatcom] voice conversion failed: {}".format(e)) logger.error("[wechatcom] please install pydub: pip install pydub") return except WeChatClientException as e: logger.error("[wechatcom] upload voice failed: {}".format(e)) return try: os.remove(file_path) if amr_file != file_path: os.remove(amr_file) except Exception: pass for media_id in media_ids: self.client.message.send_voice(self.agent_id, receiver, media_id) time.sleep(1) logger.info("[wechatcom] sendVoice={}, receiver={}".format(reply.content, receiver)) elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片 img_url = reply.content pic_res = requests.get(img_url, stream=True) image_storage = io.BytesIO() for block in pic_res.iter_content(1024): image_storage.write(block) sz = fsize(image_storage) if sz >= 10 * 1024 * 1024: logger.info("[wechatcom] image too large, ready to compress, sz={}".format(sz)) image_storage = compress_imgfile(image_storage, 10 * 1024 * 1024 - 1) logger.info("[wechatcom] image compressed, sz={}".format(fsize(image_storage))) image_storage.seek(0) if ".webp" in img_url: try: image_storage = convert_webp_to_png(image_storage) except Exception as e: logger.error(f"Failed to convert image: {e}") return try: response = self.client.media.upload("image", image_storage) logger.debug("[wechatcom] upload image response: {}".format(response)) except WeChatClientException as e: logger.error("[wechatcom] upload image failed: {}".format(e)) return self.client.message.send_image(self.agent_id, receiver, response["media_id"]) logger.info("[wechatcom] sendImage url={}, receiver={}".format(img_url, receiver)) elif reply.type == ReplyType.IMAGE: # 从文件读取图片 image_storage = reply.content sz = fsize(image_storage) if sz >= 10 * 1024 * 1024: logger.info("[wechatcom] image too large, ready to compress, sz={}".format(sz)) image_storage = compress_imgfile(image_storage, 10 * 1024 * 1024 - 1) logger.info("[wechatcom] image compressed, sz={}".format(fsize(image_storage))) image_storage.seek(0) try: response = self.client.media.upload("image", image_storage) logger.debug("[wechatcom] upload image response: {}".format(response)) except WeChatClientException as e: logger.error("[wechatcom] upload image failed: {}".format(e)) return self.client.message.send_image(self.agent_id, receiver, response["media_id"]) logger.info("[wechatcom] sendImage, receiver={}".format(receiver)) class Query: def GET(self): channel = WechatComAppChannel() params = web.input() logger.info("[wechatcom] receive params: {}".format(params)) try: signature = params.msg_signature timestamp = params.timestamp nonce = params.nonce echostr = params.echostr echostr = channel.crypto.check_signature(signature, timestamp, nonce, echostr) except InvalidSignatureException: raise web.Forbidden() return echostr def POST(self): channel = WechatComAppChannel() params = web.input() logger.info("[wechatcom] receive params: {}".format(params)) try: signature = params.msg_signature timestamp = params.timestamp nonce = params.nonce message = channel.crypto.decrypt_message(web.data(), signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): raise web.Forbidden() msg = parse_message(message) logger.debug("[wechatcom] receive message: {}, msg= {}".format(message, msg)) if msg.type == "event": if msg.event == "subscribe": pass # reply_content = subscribe_msg() # if reply_content: # reply = create_reply(reply_content, msg).render() # res = channel.crypto.encrypt_message(reply, nonce, timestamp) # return res else: try: wechatcom_msg = WechatComAppMessage(msg, client=channel.client) except NotImplementedError as e: logger.debug("[wechatcom] " + str(e)) return "success" context = channel._compose_context( wechatcom_msg.ctype, wechatcom_msg.content, isgroup=False, msg=wechatcom_msg, ) if context: channel.produce(context) return "success"
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechatcom/wechatcomapp_client.py
Python
# wechatcomapp_client.py import threading import time from wechatpy.enterprise import WeChatClient class WechatComAppClient(WeChatClient): def __init__(self, corp_id, secret, access_token=None, session=None, timeout=None, auto_retry=True): super(WechatComAppClient, self).__init__(corp_id, secret, access_token, session, timeout, auto_retry) self.fetch_access_token_lock = threading.Lock() self._active_refresh() def _active_refresh(self): """启动主动刷新的后台线程""" def refresh_loop(): while True: now = time.time() expires_at = self.session.get(f"{self.corp_id}_expires_at", 0) # 提前10分钟刷新(600秒) if expires_at - now < 600: with self.fetch_access_token_lock: # 双重检查避免重复刷新 if self.session.get(f"{self.corp_id}_expires_at", 0) - time.time() < 600: super(WechatComAppClient, self).fetch_access_token() # 每次检查间隔60秒 time.sleep(60) # 启动守护线程 refresh_thread = threading.Thread( target=refresh_loop, daemon=True, name="wechatcom_token_refresh_thread" ) refresh_thread.start() def fetch_access_token(self): with self.fetch_access_token_lock: access_token = self.session.get(self.access_token_key) expires_at = self.session.get(f"{self.corp_id}_expires_at", 0) if access_token and expires_at > time.time() + 60: return access_token return super().fetch_access_token()
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechatcom/wechatcomapp_message.py
Python
from wechatpy.enterprise import WeChatClient from bridge.context import ContextType from channel.chat_message import ChatMessage from common.log import logger from common.tmp_dir import TmpDir class WechatComAppMessage(ChatMessage): def __init__(self, msg, client: WeChatClient, is_group=False): super().__init__(msg) self.msg_id = msg.id self.create_time = msg.time self.is_group = is_group if msg.type == "text": self.ctype = ContextType.TEXT self.content = msg.content elif msg.type == "voice": self.ctype = ContextType.VOICE self.content = TmpDir().path() + msg.media_id + "." + msg.format # content直接存临时目录路径 def download_voice(): # 如果响应状态码是200,则将响应内容写入本地文件 response = client.media.download(msg.media_id) if response.status_code == 200: with open(self.content, "wb") as f: f.write(response.content) else: logger.info(f"[wechatcom] Failed to download voice file, {response.content}") self._prepare_fn = download_voice elif msg.type == "image": self.ctype = ContextType.IMAGE self.content = TmpDir().path() + msg.media_id + ".png" # content直接存临时目录路径 def download_image(): # 如果响应状态码是200,则将响应内容写入本地文件 response = client.media.download(msg.media_id) if response.status_code == 200: with open(self.content, "wb") as f: f.write(response.content) else: logger.info(f"[wechatcom] Failed to download image file, {response.content}") self._prepare_fn = download_image else: raise NotImplementedError("Unsupported message type: Type:{} ".format(msg.type)) self.from_user_id = msg.source self.to_user_id = msg.target self.other_user_id = msg.source
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechatmp/active_reply.py
Python
import time import web from wechatpy import parse_message from wechatpy.replies import create_reply from bridge.context import * from bridge.reply import * from channel.wechatmp.common import * from channel.wechatmp.wechatmp_channel import WechatMPChannel from channel.wechatmp.wechatmp_message import WeChatMPMessage from common.log import logger from config import conf, subscribe_msg # This class is instantiated once per query class Query: def GET(self): return verify_server(web.input()) def POST(self): # Make sure to return the instance that first created, @singleton will do that. try: args = web.input() verify_server(args) channel = WechatMPChannel() message = web.data() encrypt_func = lambda x: x if args.get("encrypt_type") == "aes": logger.debug("[wechatmp] Receive encrypted post data:\n" + message.decode("utf-8")) if not channel.crypto: raise Exception("Crypto not initialized, Please set wechatmp_aes_key in config.json") message = channel.crypto.decrypt_message(message, args.msg_signature, args.timestamp, args.nonce) encrypt_func = lambda x: channel.crypto.encrypt_message(x, args.nonce, args.timestamp) else: logger.debug("[wechatmp] Receive post data:\n" + message.decode("utf-8")) msg = parse_message(message) if msg.type in ["text", "voice", "image"]: wechatmp_msg = WeChatMPMessage(msg, client=channel.client) from_user = wechatmp_msg.from_user_id content = wechatmp_msg.content message_id = wechatmp_msg.msg_id logger.info( "[wechatmp] {}:{} Receive post query {} {}: {}".format( web.ctx.env.get("REMOTE_ADDR"), web.ctx.env.get("REMOTE_PORT"), from_user, message_id, content, ) ) if msg.type == "voice" and wechatmp_msg.ctype == ContextType.TEXT and conf().get("voice_reply_voice", False): context = channel._compose_context(wechatmp_msg.ctype, content, isgroup=False, desire_rtype=ReplyType.VOICE, msg=wechatmp_msg) else: context = channel._compose_context(wechatmp_msg.ctype, content, isgroup=False, msg=wechatmp_msg) if context: channel.produce(context) # The reply will be sent by channel.send() in another thread return "success" elif msg.type == "event": logger.info("[wechatmp] Event {} from {}".format(msg.event, msg.source)) if msg.event in ["subscribe", "subscribe_scan"]: reply_text = subscribe_msg() if reply_text: replyPost = create_reply(reply_text, msg) return encrypt_func(replyPost.render()) else: return "success" else: logger.info("暂且不处理") return "success" except Exception as exc: logger.exception(exc) return exc
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechatmp/common.py
Python
import web from wechatpy.crypto import WeChatCrypto from wechatpy.exceptions import InvalidSignatureException from wechatpy.utils import check_signature from config import conf MAX_UTF8_LEN = 2048 class WeChatAPIException(Exception): pass def verify_server(data): try: signature = data.signature timestamp = data.timestamp nonce = data.nonce echostr = data.get("echostr", None) token = conf().get("wechatmp_token") # 请按照公众平台官网\基本配置中信息填写 check_signature(token, signature, timestamp, nonce) return echostr except InvalidSignatureException: raise web.Forbidden("Invalid signature") except Exception as e: raise web.Forbidden(str(e))
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechatmp/passive_reply.py
Python
import asyncio import time import web from wechatpy import parse_message from wechatpy.replies import ImageReply, VoiceReply, create_reply import textwrap from bridge.context import * from bridge.reply import * from channel.wechatmp.common import * from channel.wechatmp.wechatmp_channel import WechatMPChannel from channel.wechatmp.wechatmp_message import WeChatMPMessage from common.log import logger from common.utils import split_string_by_utf8_length from config import conf, subscribe_msg # This class is instantiated once per query class Query: def GET(self): return verify_server(web.input()) def POST(self): try: args = web.input() verify_server(args) request_time = time.time() channel = WechatMPChannel() message = web.data() encrypt_func = lambda x: x if args.get("encrypt_type") == "aes": logger.debug("[wechatmp] Receive encrypted post data:\n" + message.decode("utf-8")) if not channel.crypto: raise Exception("Crypto not initialized, Please set wechatmp_aes_key in config.json") message = channel.crypto.decrypt_message(message, args.msg_signature, args.timestamp, args.nonce) encrypt_func = lambda x: channel.crypto.encrypt_message(x, args.nonce, args.timestamp) else: logger.debug("[wechatmp] Receive post data:\n" + message.decode("utf-8")) msg = parse_message(message) if msg.type in ["text", "voice", "image"]: wechatmp_msg = WeChatMPMessage(msg, client=channel.client) from_user = wechatmp_msg.from_user_id content = wechatmp_msg.content message_id = wechatmp_msg.msg_id supported = True if "【收到不支持的消息类型,暂无法显示】" in content: supported = False # not supported, used to refresh # New request if ( channel.cache_dict.get(from_user) is None and from_user not in channel.running or content.startswith("#") and message_id not in channel.request_cnt # insert the godcmd ): # The first query begin if msg.type == "voice" and wechatmp_msg.ctype == ContextType.TEXT and conf().get("voice_reply_voice", False): context = channel._compose_context(wechatmp_msg.ctype, content, isgroup=False, desire_rtype=ReplyType.VOICE, msg=wechatmp_msg) else: context = channel._compose_context(wechatmp_msg.ctype, content, isgroup=False, msg=wechatmp_msg) logger.debug("[wechatmp] context: {} {} {}".format(context, wechatmp_msg, supported)) if supported and context: channel.running.add(from_user) channel.produce(context) else: trigger_prefix = conf().get("single_chat_prefix", [""])[0] if trigger_prefix or not supported: if trigger_prefix: reply_text = textwrap.dedent( f"""\ 请输入'{trigger_prefix}'接你想说的话跟我说话。 例如: {trigger_prefix}你好,很高兴见到你。""" ) else: reply_text = textwrap.dedent( """\ 你好,很高兴见到你。 请跟我说话吧。""" ) else: logger.error(f"[wechatmp] unknown error") reply_text = textwrap.dedent( """\ 未知错误,请稍后再试""" ) replyPost = create_reply(reply_text, msg) return encrypt_func(replyPost.render()) # Wechat official server will request 3 times (5 seconds each), with the same message_id. # Because the interval is 5 seconds, here assumed that do not have multithreading problems. request_cnt = channel.request_cnt.get(message_id, 0) + 1 channel.request_cnt[message_id] = request_cnt logger.info( "[wechatmp] Request {} from {} {} {}:{}\n{}".format( request_cnt, from_user, message_id, web.ctx.env.get("REMOTE_ADDR"), web.ctx.env.get("REMOTE_PORT"), content ) ) task_running = True waiting_until = request_time + 4 while time.time() < waiting_until: if from_user in channel.running: time.sleep(0.1) else: task_running = False break reply_text = "" if task_running: if request_cnt < 3: # waiting for timeout (the POST request will be closed by Wechat official server) time.sleep(2) # and do nothing, waiting for the next request return "success" else: # request_cnt == 3: # return timeout message reply_text = "【正在思考中,回复任意文字尝试获取回复】" replyPost = create_reply(reply_text, msg) return encrypt_func(replyPost.render()) # reply is ready channel.request_cnt.pop(message_id) # no return because of bandwords or other reasons if from_user not in channel.cache_dict and from_user not in channel.running: return "success" # Only one request can access to the cached data try: (reply_type, reply_content) = channel.cache_dict[from_user].pop(0) if not channel.cache_dict[from_user]: # If popping the message makes the list empty, delete the user entry from cache del channel.cache_dict[from_user] except IndexError: return "success" if reply_type == "text": if len(reply_content.encode("utf8")) <= MAX_UTF8_LEN: reply_text = reply_content else: continue_text = "\n【未完待续,回复任意文字以继续】" splits = split_string_by_utf8_length( reply_content, MAX_UTF8_LEN - len(continue_text.encode("utf-8")), max_split=1, ) reply_text = splits[0] + continue_text channel.cache_dict[from_user].append(("text", splits[1])) logger.info( "[wechatmp] Request {} do send to {} {}: {}\n{}".format( request_cnt, from_user, message_id, content, reply_text, ) ) replyPost = create_reply(reply_text, msg) return encrypt_func(replyPost.render()) elif reply_type == "voice": media_id = reply_content asyncio.run_coroutine_threadsafe(channel.delete_media(media_id), channel.delete_media_loop) logger.info( "[wechatmp] Request {} do send to {} {}: {} voice media_id {}".format( request_cnt, from_user, message_id, content, media_id, ) ) replyPost = VoiceReply(message=msg) replyPost.media_id = media_id return encrypt_func(replyPost.render()) elif reply_type == "image": media_id = reply_content asyncio.run_coroutine_threadsafe(channel.delete_media(media_id), channel.delete_media_loop) logger.info( "[wechatmp] Request {} do send to {} {}: {} image media_id {}".format( request_cnt, from_user, message_id, content, media_id, ) ) replyPost = ImageReply(message=msg) replyPost.media_id = media_id return encrypt_func(replyPost.render()) elif msg.type == "event": logger.info("[wechatmp] Event {} from {}".format(msg.event, msg.source)) if msg.event in ["subscribe", "subscribe_scan"]: reply_text = subscribe_msg() if reply_text: replyPost = create_reply(reply_text, msg) return encrypt_func(replyPost.render()) else: return "success" else: logger.info("暂且不处理") return "success" except Exception as exc: logger.exception(exc) return exc
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechatmp/wechatmp_channel.py
Python
# -*- coding: utf-8 -*- import asyncio import imghdr import io import os import threading import time import requests import web from wechatpy.crypto import WeChatCrypto from wechatpy.exceptions import WeChatClientException from collections import defaultdict from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel.wechatmp.common import * from channel.wechatmp.wechatmp_client import WechatMPClient from common.log import logger from common.singleton import singleton from common.utils import split_string_by_utf8_length, remove_markdown_symbol from config import conf try: from voice.audio_convert import any_to_mp3, split_audio except ImportError as e: logger.debug("import voice.audio_convert failed, voice features will not be supported: {}".format(e)) # If using SSL, uncomment the following lines, and modify the certificate path. # from cheroot.server import HTTPServer # from cheroot.ssl.builtin import BuiltinSSLAdapter # HTTPServer.ssl_adapter = BuiltinSSLAdapter( # certificate='/ssl/cert.pem', # private_key='/ssl/cert.key') @singleton class WechatMPChannel(ChatChannel): def __init__(self, passive_reply=True): super().__init__() self.passive_reply = passive_reply self.NOT_SUPPORT_REPLYTYPE = [] appid = conf().get("wechatmp_app_id") secret = conf().get("wechatmp_app_secret") token = conf().get("wechatmp_token") aes_key = conf().get("wechatmp_aes_key") self.client = WechatMPClient(appid, secret) self.crypto = None if aes_key: self.crypto = WeChatCrypto(token, aes_key, appid) if self.passive_reply: # Cache the reply to the user's first message self.cache_dict = defaultdict(list) # Record whether the current message is being processed self.running = set() # Count the request from wechat official server by message_id self.request_cnt = dict() # The permanent media need to be deleted to avoid media number limit self.delete_media_loop = asyncio.new_event_loop() t = threading.Thread(target=self.start_loop, args=(self.delete_media_loop,)) t.setDaemon(True) t.start() def startup(self): if self.passive_reply: urls = ("/wx", "channel.wechatmp.passive_reply.Query") else: urls = ("/wx", "channel.wechatmp.active_reply.Query") app = web.application(urls, globals(), autoreload=False) port = conf().get("wechatmp_port", 8080) web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", port)) def start_loop(self, loop): asyncio.set_event_loop(loop) loop.run_forever() async def delete_media(self, media_id): logger.debug("[wechatmp] permanent media {} will be deleted in 10s".format(media_id)) await asyncio.sleep(10) self.client.material.delete(media_id) logger.info("[wechatmp] permanent media {} has been deleted".format(media_id)) def send(self, reply: Reply, context: Context): receiver = context["receiver"] if self.passive_reply: if reply.type == ReplyType.TEXT or reply.type == ReplyType.INFO or reply.type == ReplyType.ERROR: reply_text = remove_markdown_symbol(reply.content) logger.info("[wechatmp] text cached, receiver {}\n{}".format(receiver, reply_text)) self.cache_dict[receiver].append(("text", reply_text)) elif reply.type == ReplyType.VOICE: try: voice_file_path = reply.content duration, files = split_audio(voice_file_path, 60 * 1000) if len(files) > 1: logger.info("[wechatmp] voice too long {}s > 60s , split into {} parts".format(duration / 1000.0, len(files))) for path in files: # support: <2M, <60s, mp3/wma/wav/amr try: with open(path, "rb") as f: response = self.client.material.add("voice", f) logger.debug("[wechatmp] upload voice response: {}".format(response)) f_size = os.fstat(f.fileno()).st_size time.sleep(1.0 + 2 * f_size / 1024 / 1024) # todo check media_id except WeChatClientException as e: logger.error("[wechatmp] upload voice failed: {}".format(e)) return media_id = response["media_id"] logger.info("[wechatmp] voice uploaded, receiver {}, media_id {}".format(receiver, media_id)) self.cache_dict[receiver].append(("voice", media_id)) except ImportError as e: logger.error("[wechatmp] voice conversion failed: {}".format(e)) logger.error("[wechatmp] please install pydub: pip install pydub") return elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片 img_url = reply.content pic_res = requests.get(img_url, stream=True) image_storage = io.BytesIO() for block in pic_res.iter_content(1024): image_storage.write(block) image_storage.seek(0) image_type = imghdr.what(image_storage) filename = receiver + "-" + str(context["msg"].msg_id) + "." + image_type content_type = "image/" + image_type try: response = self.client.material.add("image", (filename, image_storage, content_type)) logger.debug("[wechatmp] upload image response: {}".format(response)) except WeChatClientException as e: logger.error("[wechatmp] upload image failed: {}".format(e)) return media_id = response["media_id"] logger.info("[wechatmp] image uploaded, receiver {}, media_id {}".format(receiver, media_id)) self.cache_dict[receiver].append(("image", media_id)) elif reply.type == ReplyType.IMAGE: # 从文件读取图片 image_storage = reply.content image_storage.seek(0) image_type = imghdr.what(image_storage) filename = receiver + "-" + str(context["msg"].msg_id) + "." + image_type content_type = "image/" + image_type try: response = self.client.material.add("image", (filename, image_storage, content_type)) logger.debug("[wechatmp] upload image response: {}".format(response)) except WeChatClientException as e: logger.error("[wechatmp] upload image failed: {}".format(e)) return media_id = response["media_id"] logger.info("[wechatmp] image uploaded, receiver {}, media_id {}".format(receiver, media_id)) self.cache_dict[receiver].append(("image", media_id)) elif reply.type == ReplyType.VIDEO_URL: # 从网络下载视频 video_url = reply.content video_res = requests.get(video_url, stream=True) video_storage = io.BytesIO() for block in video_res.iter_content(1024): video_storage.write(block) video_storage.seek(0) video_type = 'mp4' filename = receiver + "-" + str(context["msg"].msg_id) + "." + video_type content_type = "video/" + video_type try: response = self.client.material.add("video", (filename, video_storage, content_type)) logger.debug("[wechatmp] upload video response: {}".format(response)) except WeChatClientException as e: logger.error("[wechatmp] upload video failed: {}".format(e)) return media_id = response["media_id"] logger.info("[wechatmp] video uploaded, receiver {}, media_id {}".format(receiver, media_id)) self.cache_dict[receiver].append(("video", media_id)) elif reply.type == ReplyType.VIDEO: # 从文件读取视频 video_storage = reply.content video_storage.seek(0) video_type = 'mp4' filename = receiver + "-" + str(context["msg"].msg_id) + "." + video_type content_type = "video/" + video_type try: response = self.client.material.add("video", (filename, video_storage, content_type)) logger.debug("[wechatmp] upload video response: {}".format(response)) except WeChatClientException as e: logger.error("[wechatmp] upload video failed: {}".format(e)) return media_id = response["media_id"] logger.info("[wechatmp] video uploaded, receiver {}, media_id {}".format(receiver, media_id)) self.cache_dict[receiver].append(("video", media_id)) else: if reply.type == ReplyType.TEXT or reply.type == ReplyType.INFO or reply.type == ReplyType.ERROR: reply_text = reply.content texts = split_string_by_utf8_length(reply_text, MAX_UTF8_LEN) if len(texts) > 1: logger.info("[wechatmp] text too long, split into {} parts".format(len(texts))) for i, text in enumerate(texts): self.client.message.send_text(receiver, text) if i != len(texts) - 1: time.sleep(0.5) # 休眠0.5秒,防止发送过快乱序 logger.info("[wechatmp] Do send text to {}: {}".format(receiver, reply_text)) elif reply.type == ReplyType.VOICE: try: file_path = reply.content file_name = os.path.basename(file_path) file_type = os.path.splitext(file_name)[1] if file_type == ".mp3": file_type = "audio/mpeg" elif file_type == ".amr": file_type = "audio/amr" else: mp3_file = os.path.splitext(file_path)[0] + ".mp3" any_to_mp3(file_path, mp3_file) file_path = mp3_file file_name = os.path.basename(file_path) file_type = "audio/mpeg" logger.info("[wechatmp] file_name: {}, file_type: {} ".format(file_name, file_type)) media_ids = [] duration, files = split_audio(file_path, 60 * 1000) if len(files) > 1: logger.info("[wechatmp] voice too long {}s > 60s , split into {} parts".format(duration / 1000.0, len(files))) for path in files: # support: <2M, <60s, AMR\MP3 response = self.client.media.upload("voice", (os.path.basename(path), open(path, "rb"), file_type)) logger.debug("[wechatcom] upload voice response: {}".format(response)) media_ids.append(response["media_id"]) os.remove(path) except ImportError as e: logger.error("[wechatmp] voice conversion failed: {}".format(e)) logger.error("[wechatmp] please install pydub: pip install pydub") return except WeChatClientException as e: logger.error("[wechatmp] upload voice failed: {}".format(e)) return try: os.remove(file_path) except Exception: pass for media_id in media_ids: self.client.message.send_voice(receiver, media_id) time.sleep(1) logger.info("[wechatmp] Do send voice to {}".format(receiver)) elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片 img_url = reply.content pic_res = requests.get(img_url, stream=True) image_storage = io.BytesIO() for block in pic_res.iter_content(1024): image_storage.write(block) image_storage.seek(0) image_type = imghdr.what(image_storage) filename = receiver + "-" + str(context["msg"].msg_id) + "." + image_type content_type = "image/" + image_type try: response = self.client.media.upload("image", (filename, image_storage, content_type)) logger.debug("[wechatmp] upload image response: {}".format(response)) except WeChatClientException as e: logger.error("[wechatmp] upload image failed: {}".format(e)) return self.client.message.send_image(receiver, response["media_id"]) logger.info("[wechatmp] Do send image to {}".format(receiver)) elif reply.type == ReplyType.IMAGE: # 从文件读取图片 image_storage = reply.content image_storage.seek(0) image_type = imghdr.what(image_storage) filename = receiver + "-" + str(context["msg"].msg_id) + "." + image_type content_type = "image/" + image_type try: response = self.client.media.upload("image", (filename, image_storage, content_type)) logger.debug("[wechatmp] upload image response: {}".format(response)) except WeChatClientException as e: logger.error("[wechatmp] upload image failed: {}".format(e)) return self.client.message.send_image(receiver, response["media_id"]) logger.info("[wechatmp] Do send image to {}".format(receiver)) elif reply.type == ReplyType.VIDEO_URL: # 从网络下载视频 video_url = reply.content video_res = requests.get(video_url, stream=True) video_storage = io.BytesIO() for block in video_res.iter_content(1024): video_storage.write(block) video_storage.seek(0) video_type = 'mp4' filename = receiver + "-" + str(context["msg"].msg_id) + "." + video_type content_type = "video/" + video_type try: response = self.client.media.upload("video", (filename, video_storage, content_type)) logger.debug("[wechatmp] upload video response: {}".format(response)) except WeChatClientException as e: logger.error("[wechatmp] upload video failed: {}".format(e)) return self.client.message.send_video(receiver, response["media_id"]) logger.info("[wechatmp] Do send video to {}".format(receiver)) elif reply.type == ReplyType.VIDEO: # 从文件读取视频 video_storage = reply.content video_storage.seek(0) video_type = 'mp4' filename = receiver + "-" + str(context["msg"].msg_id) + "." + video_type content_type = "video/" + video_type try: response = self.client.media.upload("video", (filename, video_storage, content_type)) logger.debug("[wechatmp] upload video response: {}".format(response)) except WeChatClientException as e: logger.error("[wechatmp] upload video failed: {}".format(e)) return self.client.message.send_video(receiver, response["media_id"]) logger.info("[wechatmp] Do send video to {}".format(receiver)) return def _success_callback(self, session_id, context, **kwargs): # 线程异常结束时的回调函数 logger.debug("[wechatmp] Success to generate reply, msgId={}".format(context["msg"].msg_id)) if self.passive_reply: self.running.remove(session_id) def _fail_callback(self, session_id, exception, context, **kwargs): # 线程异常结束时的回调函数 logger.exception("[wechatmp] Fail to generate reply to user, msgId={}, exception={}".format(context["msg"].msg_id, exception)) if self.passive_reply: assert session_id not in self.cache_dict self.running.remove(session_id)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechatmp/wechatmp_client.py
Python
import threading import time from wechatpy.client import WeChatClient from wechatpy.exceptions import APILimitedException from channel.wechatmp.common import * from common.log import logger class WechatMPClient(WeChatClient): def __init__(self, appid, secret, access_token=None, session=None, timeout=None, auto_retry=True): super(WechatMPClient, self).__init__(appid, secret, access_token, session, timeout, auto_retry) self.fetch_access_token_lock = threading.Lock() self.clear_quota_lock = threading.Lock() self.last_clear_quota_time = -1 def clear_quota(self): return self.post("clear_quota", data={"appid": self.appid}) def clear_quota_v2(self): return self.post("clear_quota/v2", params={"appid": self.appid, "appsecret": self.secret}) def fetch_access_token(self): # 重载父类方法,加锁避免多线程重复获取access_token with self.fetch_access_token_lock: access_token = self.session.get(self.access_token_key) if access_token: if not self.expires_at: return access_token timestamp = time.time() if self.expires_at - timestamp > 60: return access_token return super().fetch_access_token() def _request(self, method, url_or_endpoint, **kwargs): # 重载父类方法,遇到API限流时,清除quota后重试 try: return super()._request(method, url_or_endpoint, **kwargs) except APILimitedException as e: logger.error("[wechatmp] API quata has been used up. {}".format(e)) if self.last_clear_quota_time == -1 or time.time() - self.last_clear_quota_time > 60: with self.clear_quota_lock: if self.last_clear_quota_time == -1 or time.time() - self.last_clear_quota_time > 60: self.last_clear_quota_time = time.time() response = self.clear_quota_v2() logger.debug("[wechatmp] API quata has been cleard, {}".format(response)) return super()._request(method, url_or_endpoint, **kwargs) else: logger.error("[wechatmp] last clear quota time is {}, less than 60s, skip clear quota") raise e
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wechatmp/wechatmp_message.py
Python
# -*- coding: utf-8 -*-# from bridge.context import ContextType from channel.chat_message import ChatMessage from common.log import logger from common.tmp_dir import TmpDir class WeChatMPMessage(ChatMessage): def __init__(self, msg, client=None): super().__init__(msg) self.msg_id = msg.id self.create_time = msg.time self.is_group = False if msg.type == "text": self.ctype = ContextType.TEXT self.content = msg.content elif msg.type == "voice": if msg.recognition == None: self.ctype = ContextType.VOICE self.content = TmpDir().path() + msg.media_id + "." + msg.format # content直接存临时目录路径 def download_voice(): # 如果响应状态码是200,则将响应内容写入本地文件 response = client.media.download(msg.media_id) if response.status_code == 200: with open(self.content, "wb") as f: f.write(response.content) else: logger.info(f"[wechatmp] Failed to download voice file, {response.content}") self._prepare_fn = download_voice else: self.ctype = ContextType.TEXT self.content = msg.recognition elif msg.type == "image": self.ctype = ContextType.IMAGE self.content = TmpDir().path() + msg.media_id + ".png" # content直接存临时目录路径 def download_image(): # 如果响应状态码是200,则将响应内容写入本地文件 response = client.media.download(msg.media_id) if response.status_code == 200: with open(self.content, "wb") as f: f.write(response.content) else: logger.info(f"[wechatmp] Failed to download image file, {response.content}") self._prepare_fn = download_image else: raise NotImplementedError("Unsupported message type: Type:{} ".format(msg.type)) self.from_user_id = msg.source self.to_user_id = msg.target self.other_user_id = msg.source
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wework/run.py
Python
import os import time os.environ['ntwork_LOG'] = "ERROR" import ntwork wework = ntwork.WeWork() def forever(): try: while True: time.sleep(0.1) except KeyboardInterrupt: ntwork.exit_() os._exit(0)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wework/wework_channel.py
Python
import io import os import random import tempfile import threading os.environ['ntwork_LOG'] = "ERROR" import ntwork import requests import uuid from bridge.context import * from bridge.reply import * from channel.chat_channel import ChatChannel from channel.wework.wework_message import * from channel.wework.wework_message import WeworkMessage from common.singleton import singleton from common.log import logger from common.time_check import time_checker from common.utils import compress_imgfile, fsize from config import conf from channel.wework.run import wework from channel.wework import run def get_wxid_by_name(room_members, group_wxid, name): if group_wxid in room_members: for member in room_members[group_wxid]['member_list']: if member['room_nickname'] == name or member['username'] == name: return member['user_id'] return None # 如果没有找到对应的group_wxid或name,则返回None def download_and_compress_image(url, filename, quality=30): # 确定保存图片的目录 directory = os.path.join(os.getcwd(), "tmp") # 如果目录不存在,则创建目录 if not os.path.exists(directory): os.makedirs(directory) # 下载图片 pic_res = requests.get(url, stream=True) image_storage = io.BytesIO() for block in pic_res.iter_content(1024): image_storage.write(block) # 检查图片大小并可能进行压缩 sz = fsize(image_storage) if sz >= 10 * 1024 * 1024: # 如果图片大于 10 MB logger.info("[wework] image too large, ready to compress, sz={}".format(sz)) image_storage = compress_imgfile(image_storage, 10 * 1024 * 1024 - 1) logger.info("[wework] image compressed, sz={}".format(fsize(image_storage))) # 将内存缓冲区的指针重置到起始位置 image_storage.seek(0) # 读取并保存图片 from PIL import Image image = Image.open(image_storage) image_path = os.path.join(directory, f"{filename}.png") image.save(image_path, "png") return image_path def download_video(url, filename): # 确定保存视频的目录 directory = os.path.join(os.getcwd(), "tmp") # 如果目录不存在,则创建目录 if not os.path.exists(directory): os.makedirs(directory) # 下载视频 response = requests.get(url, stream=True) total_size = 0 video_path = os.path.join(directory, f"{filename}.mp4") with open(video_path, 'wb') as f: for block in response.iter_content(1024): total_size += len(block) # 如果视频的总大小超过30MB (30 * 1024 * 1024 bytes),则停止下载并返回 if total_size > 30 * 1024 * 1024: logger.info("[WX] Video is larger than 30MB, skipping...") return None f.write(block) return video_path def create_message(wework_instance, message, is_group): logger.debug(f"正在为{'群聊' if is_group else '单聊'}创建 WeworkMessage") cmsg = WeworkMessage(message, wework=wework_instance, is_group=is_group) logger.debug(f"cmsg:{cmsg}") return cmsg def handle_message(cmsg, is_group): logger.debug(f"准备用 WeworkChannel 处理{'群聊' if is_group else '单聊'}消息") if is_group: WeworkChannel().handle_group(cmsg) else: WeworkChannel().handle_single(cmsg) logger.debug(f"已用 WeworkChannel 处理完{'群聊' if is_group else '单聊'}消息") def _check(func): def wrapper(self, cmsg: ChatMessage): msgId = cmsg.msg_id create_time = cmsg.create_time # 消息时间戳 if create_time is None: return func(self, cmsg) if int(create_time) < int(time.time()) - 60: # 跳过1分钟前的历史消息 logger.debug("[WX]history message {} skipped".format(msgId)) return return func(self, cmsg) return wrapper @wework.msg_register( [ntwork.MT_RECV_TEXT_MSG, ntwork.MT_RECV_IMAGE_MSG, 11072, ntwork.MT_RECV_LINK_CARD_MSG,ntwork.MT_RECV_FILE_MSG, ntwork.MT_RECV_VOICE_MSG]) def all_msg_handler(wework_instance: ntwork.WeWork, message): logger.debug(f"收到消息: {message}") if 'data' in message: # 首先查找conversation_id,如果没有找到,则查找room_conversation_id conversation_id = message['data'].get('conversation_id', message['data'].get('room_conversation_id')) if conversation_id is not None: is_group = "R:" in conversation_id try: cmsg = create_message(wework_instance=wework_instance, message=message, is_group=is_group) except NotImplementedError as e: logger.error(f"[WX]{message.get('MsgId', 'unknown')} 跳过: {e}") return None delay = random.randint(1, 2) timer = threading.Timer(delay, handle_message, args=(cmsg, is_group)) timer.start() else: logger.debug("消息数据中无 conversation_id") return None return None def accept_friend_with_retries(wework_instance, user_id, corp_id): result = wework_instance.accept_friend(user_id, corp_id) logger.debug(f'result:{result}') # @wework.msg_register(ntwork.MT_RECV_FRIEND_MSG) # def friend(wework_instance: ntwork.WeWork, message): # data = message["data"] # user_id = data["user_id"] # corp_id = data["corp_id"] # logger.info(f"接收到好友请求,消息内容:{data}") # delay = random.randint(1, 180) # threading.Timer(delay, accept_friend_with_retries, args=(wework_instance, user_id, corp_id)).start() # # return None def get_with_retry(get_func, max_retries=5, delay=5): retries = 0 result = None while retries < max_retries: result = get_func() if result: break logger.warning(f"获取数据失败,重试第{retries + 1}次······") retries += 1 time.sleep(delay) # 等待一段时间后重试 return result @singleton class WeworkChannel(ChatChannel): NOT_SUPPORT_REPLYTYPE = [] def __init__(self): super().__init__() def startup(self): smart = conf().get("wework_smart", True) wework.open(smart) logger.info("等待登录······") wework.wait_login() login_info = wework.get_login_info() self.user_id = login_info['user_id'] self.name = login_info['nickname'] logger.info(f"登录信息:>>>user_id:{self.user_id}>>>>>>>>name:{self.name}") logger.info("静默延迟60s,等待客户端刷新数据,请勿进行任何操作······") time.sleep(60) contacts = get_with_retry(wework.get_external_contacts) rooms = get_with_retry(wework.get_rooms) directory = os.path.join(os.getcwd(), "tmp") if not contacts or not rooms: logger.error("获取contacts或rooms失败,程序退出") ntwork.exit_() os.exit(0) if not os.path.exists(directory): os.makedirs(directory) # 将contacts保存到json文件中 with open(os.path.join(directory, 'wework_contacts.json'), 'w', encoding='utf-8') as f: json.dump(contacts, f, ensure_ascii=False, indent=4) with open(os.path.join(directory, 'wework_rooms.json'), 'w', encoding='utf-8') as f: json.dump(rooms, f, ensure_ascii=False, indent=4) # 创建一个空字典来保存结果 result = {} # 遍历列表中的每个字典 for room in rooms['room_list']: # 获取聊天室ID room_wxid = room['conversation_id'] # 获取聊天室成员 room_members = wework.get_room_members(room_wxid) # 将聊天室成员保存到结果字典中 result[room_wxid] = room_members # 将结果保存到json文件中 with open(os.path.join(directory, 'wework_room_members.json'), 'w', encoding='utf-8') as f: json.dump(result, f, ensure_ascii=False, indent=4) logger.info("wework程序初始化完成········") run.forever() @time_checker @_check def handle_single(self, cmsg: ChatMessage): if cmsg.from_user_id == cmsg.to_user_id: # ignore self reply return if cmsg.ctype == ContextType.VOICE: if not conf().get("speech_recognition"): return logger.debug("[WX]receive voice msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.IMAGE: logger.debug("[WX]receive image msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.PATPAT: logger.debug("[WX]receive patpat msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.TEXT: logger.debug("[WX]receive text msg: {}, cmsg={}".format(json.dumps(cmsg._rawmsg, ensure_ascii=False), cmsg)) else: logger.debug("[WX]receive msg: {}, cmsg={}".format(cmsg.content, cmsg)) context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=False, msg=cmsg) if context: self.produce(context) @time_checker @_check def handle_group(self, cmsg: ChatMessage): if cmsg.ctype == ContextType.VOICE: if not conf().get("speech_recognition"): return logger.debug("[WX]receive voice for group msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.IMAGE: logger.debug("[WX]receive image for group msg: {}".format(cmsg.content)) elif cmsg.ctype in [ContextType.JOIN_GROUP, ContextType.PATPAT]: logger.debug("[WX]receive note msg: {}".format(cmsg.content)) elif cmsg.ctype == ContextType.TEXT: pass else: logger.debug("[WX]receive group msg: {}".format(cmsg.content)) context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=True, msg=cmsg) if context: self.produce(context) # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息 def send(self, reply: Reply, context: Context): logger.debug(f"context: {context}") receiver = context["receiver"] actual_user_id = context["msg"].actual_user_id if reply.type == ReplyType.TEXT or reply.type == ReplyType.TEXT_: match = re.search(r"^@(.*?)\n", reply.content) logger.debug(f"match: {match}") if match: new_content = re.sub(r"^@(.*?)\n", "\n", reply.content) at_list = [actual_user_id] logger.debug(f"new_content: {new_content}") wework.send_room_at_msg(receiver, new_content, at_list) else: wework.send_text(receiver, reply.content) logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver)) elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO: wework.send_text(receiver, reply.content) logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver)) elif reply.type == ReplyType.IMAGE: # 从文件读取图片 image_storage = reply.content image_storage.seek(0) # Read data from image_storage data = image_storage.read() # Create a temporary file with tempfile.NamedTemporaryFile(delete=False) as temp: temp_path = temp.name temp.write(data) # Send the image wework.send_image(receiver, temp_path) logger.info("[WX] sendImage, receiver={}".format(receiver)) # Remove the temporary file os.remove(temp_path) elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片 img_url = reply.content filename = str(uuid.uuid4()) # 调用你的函数,下载图片并保存为本地文件 image_path = download_and_compress_image(img_url, filename) wework.send_image(receiver, file_path=image_path) logger.info("[WX] sendImage url={}, receiver={}".format(img_url, receiver)) elif reply.type == ReplyType.VIDEO_URL: video_url = reply.content filename = str(uuid.uuid4()) video_path = download_video(video_url, filename) if video_path is None: # 如果视频太大,下载可能会被跳过,此时 video_path 将为 None wework.send_text(receiver, "抱歉,视频太大了!!!") else: wework.send_video(receiver, video_path) logger.info("[WX] sendVideo, receiver={}".format(receiver)) elif reply.type == ReplyType.VOICE: current_dir = os.getcwd() voice_file = reply.content.split("/")[-1] reply.content = os.path.join(current_dir, "tmp", voice_file) wework.send_file(receiver, reply.content) logger.info("[WX] sendFile={}, receiver={}".format(reply.content, receiver))
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
channel/wework/wework_message.py
Python
import datetime import json import os import re import time import pilk from bridge.context import ContextType from channel.chat_message import ChatMessage from common.log import logger from ntwork.const import send_type def get_with_retry(get_func, max_retries=5, delay=5): retries = 0 result = None while retries < max_retries: result = get_func() if result: break logger.warning(f"获取数据失败,重试第{retries + 1}次······") retries += 1 time.sleep(delay) # 等待一段时间后重试 return result def get_room_info(wework, conversation_id): logger.debug(f"传入的 conversation_id: {conversation_id}") rooms = wework.get_rooms() if not rooms or 'room_list' not in rooms: logger.error(f"获取群聊信息失败: {rooms}") return None time.sleep(1) logger.debug(f"获取到的群聊信息: {rooms}") for room in rooms['room_list']: if room['conversation_id'] == conversation_id: return room return None def cdn_download(wework, message, file_name): data = message["data"] aes_key = data["cdn"]["aes_key"] file_size = data["cdn"]["size"] # 获取当前工作目录,然后与文件名拼接得到保存路径 current_dir = os.getcwd() save_path = os.path.join(current_dir, "tmp", file_name) # 下载保存图片到本地 if "url" in data["cdn"].keys() and "auth_key" in data["cdn"].keys(): url = data["cdn"]["url"] auth_key = data["cdn"]["auth_key"] # result = wework.wx_cdn_download(url, auth_key, aes_key, file_size, save_path) # ntwork库本身接口有问题,缺失了aes_key这个参数 """ 下载wx类型的cdn文件,以https开头 """ data = { 'url': url, 'auth_key': auth_key, 'aes_key': aes_key, 'size': file_size, 'save_path': save_path } result = wework._WeWork__send_sync(send_type.MT_WXCDN_DOWNLOAD_MSG, data) # 直接用wx_cdn_download的接口内部实现来调用 elif "file_id" in data["cdn"].keys(): if message["type"] == 11042: file_type = 2 elif message["type"] == 11045: file_type = 5 file_id = data["cdn"]["file_id"] result = wework.c2c_cdn_download(file_id, aes_key, file_size, file_type, save_path) else: logger.error(f"something is wrong, data: {data}") return # 输出下载结果 logger.debug(f"result: {result}") def c2c_download_and_convert(wework, message, file_name): data = message["data"] aes_key = data["cdn"]["aes_key"] file_size = data["cdn"]["size"] file_type = 5 file_id = data["cdn"]["file_id"] current_dir = os.getcwd() save_path = os.path.join(current_dir, "tmp", file_name) result = wework.c2c_cdn_download(file_id, aes_key, file_size, file_type, save_path) logger.debug(result) # 在下载完SILK文件之后,立即将其转换为WAV文件 base_name, _ = os.path.splitext(save_path) wav_file = base_name + ".wav" pilk.silk_to_wav(save_path, wav_file, rate=24000) # 删除SILK文件 try: os.remove(save_path) except Exception as e: pass class WeworkMessage(ChatMessage): def __init__(self, wework_msg, wework, is_group=False): try: super().__init__(wework_msg) self.msg_id = wework_msg['data'].get('conversation_id', wework_msg['data'].get('room_conversation_id')) # 使用.get()防止 'send_time' 键不存在时抛出错误 self.create_time = wework_msg['data'].get("send_time") self.is_group = is_group self.wework = wework if wework_msg["type"] == 11041: # 文本消息类型 if any(substring in wework_msg['data']['content'] for substring in ("该消息类型暂不能展示", "不支持的消息类型")): return self.ctype = ContextType.TEXT self.content = wework_msg['data']['content'] elif wework_msg["type"] == 11044: # 语音消息类型,需要缓存文件 file_name = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + ".silk" base_name, _ = os.path.splitext(file_name) file_name_2 = base_name + ".wav" current_dir = os.getcwd() self.ctype = ContextType.VOICE self.content = os.path.join(current_dir, "tmp", file_name_2) self._prepare_fn = lambda: c2c_download_and_convert(wework, wework_msg, file_name) elif wework_msg["type"] == 11042: # 图片消息类型,需要下载文件 file_name = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + ".jpg" current_dir = os.getcwd() self.ctype = ContextType.IMAGE self.content = os.path.join(current_dir, "tmp", file_name) self._prepare_fn = lambda: cdn_download(wework, wework_msg, file_name) elif wework_msg["type"] == 11045: # 文件消息 print("文件消息") print(wework_msg) file_name = datetime.datetime.now().strftime('%Y%m%d%H%M%S') file_name = file_name + wework_msg['data']['cdn']['file_name'] current_dir = os.getcwd() self.ctype = ContextType.FILE self.content = os.path.join(current_dir, "tmp", file_name) self._prepare_fn = lambda: cdn_download(wework, wework_msg, file_name) elif wework_msg["type"] == 11047: # 链接消息 self.ctype = ContextType.SHARING self.content = wework_msg['data']['url'] elif wework_msg["type"] == 11072: # 新成员入群通知 self.ctype = ContextType.JOIN_GROUP member_list = wework_msg['data']['member_list'] self.actual_user_nickname = member_list[0]['name'] self.actual_user_id = member_list[0]['user_id'] self.content = f"{self.actual_user_nickname}加入了群聊!" directory = os.path.join(os.getcwd(), "tmp") rooms = get_with_retry(wework.get_rooms) if not rooms: logger.error("更新群信息失败···") else: result = {} for room in rooms['room_list']: # 获取聊天室ID room_wxid = room['conversation_id'] # 获取聊天室成员 room_members = wework.get_room_members(room_wxid) # 将聊天室成员保存到结果字典中 result[room_wxid] = room_members with open(os.path.join(directory, 'wework_room_members.json'), 'w', encoding='utf-8') as f: json.dump(result, f, ensure_ascii=False, indent=4) logger.info("有新成员加入,已自动更新群成员列表缓存!") else: raise NotImplementedError( "Unsupported message type: Type:{} MsgType:{}".format(wework_msg["type"], wework_msg["MsgType"])) data = wework_msg['data'] login_info = self.wework.get_login_info() logger.debug(f"login_info: {login_info}") nickname = f"{login_info['username']}({login_info['nickname']})" if login_info['nickname'] else login_info['username'] user_id = login_info['user_id'] sender_id = data.get('sender') conversation_id = data.get('conversation_id') sender_name = data.get("sender_name") self.from_user_id = user_id if sender_id == user_id else conversation_id self.from_user_nickname = nickname if sender_id == user_id else sender_name self.to_user_id = user_id self.to_user_nickname = nickname self.other_user_nickname = sender_name self.other_user_id = conversation_id if self.is_group: conversation_id = data.get('conversation_id') or data.get('room_conversation_id') self.other_user_id = conversation_id if conversation_id: room_info = get_room_info(wework=wework, conversation_id=conversation_id) self.other_user_nickname = room_info.get('nickname', None) if room_info else None self.from_user_nickname = room_info.get('nickname', None) if room_info else None at_list = data.get('at_list', []) tmp_list = [] for at in at_list: tmp_list.append(at['nickname']) at_list = tmp_list logger.debug(f"at_list: {at_list}") logger.debug(f"nickname: {nickname}") self.is_at = False if nickname in at_list or login_info['nickname'] in at_list or login_info['username'] in at_list: self.is_at = True self.at_list = at_list # 检查消息内容是否包含@用户名。处理复制粘贴的消息,这类消息可能不会触发@通知,但内容中可能包含 "@用户名"。 content = data.get('content', '') name = nickname pattern = f"@{re.escape(name)}(\u2005|\u0020)" if re.search(pattern, content): logger.debug(f"Wechaty message {self.msg_id} includes at") self.is_at = True if not self.actual_user_id: self.actual_user_id = data.get("sender") self.actual_user_nickname = sender_name if self.ctype != ContextType.JOIN_GROUP else self.actual_user_nickname else: logger.error("群聊消息中没有找到 conversation_id 或 room_conversation_id") logger.debug(f"WeworkMessage has been successfully instantiated with message id: {self.msg_id}") except Exception as e: logger.error(f"在 WeworkMessage 的初始化过程中出现错误:{e}") raise e
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/const.py
Python
# 厂商类型 OPEN_AI = "openAI" CHATGPT = "chatGPT" BAIDU = "baidu" XUNFEI = "xunfei" CHATGPTONAZURE = "chatGPTOnAzure" LINKAI = "linkai" CLAUDEAPI= "claudeAPI" QWEN = "qwen" # 旧版千问接入 QWEN_DASHSCOPE = "dashscope" # 新版千问接入(百炼) GEMINI = "gemini" ZHIPU_AI = "glm-4" MOONSHOT = "moonshot" MiniMax = "minimax" MODELSCOPE = "modelscope" # 模型列表 # Claude (Anthropic) CLAUDE3 = "claude-3-opus-20240229" CLAUDE_3_OPUS = "claude-3-opus-latest" CLAUDE_3_OPUS_0229 = "claude-3-opus-20240229" CLAUDE_3_SONNET = "claude-3-sonnet-20240229" CLAUDE_3_HAIKU = "claude-3-haiku-20240307" CLAUDE_35_SONNET = "claude-3-5-sonnet-latest" # 带 latest 标签的模型名称,会不断更新指向最新发布的模型 CLAUDE_35_SONNET_1022 = "claude-3-5-sonnet-20241022" # 带具体日期的模型名称,会固定为该日期发布的模型 CLAUDE_35_SONNET_0620 = "claude-3-5-sonnet-20240620" CLAUDE_4_OPUS = "claude-opus-4-0" CLAUDE_4_6_OPUS = "claude-opus-4-6" # Claude Opus 4.6 - Agent推荐模型 CLAUDE_4_SONNET = "claude-sonnet-4-0" # Claude Sonnet 4.0 - Agent推荐模型 CLAUDE_4_5_SONNET = "claude-sonnet-4-5" # Claude Sonnet 4.5 - Agent推荐模型 # Gemini (Google) GEMINI_PRO = "gemini-1.0-pro" GEMINI_15_flash = "gemini-1.5-flash" GEMINI_15_PRO = "gemini-1.5-pro" GEMINI_20_flash_exp = "gemini-2.0-flash-exp" # exp结尾为实验模型,会逐步不再支持 GEMINI_20_FLASH = "gemini-2.0-flash" # 正式版模型 GEMINI_25_FLASH_PRE = "gemini-2.5-flash-preview-05-20" # preview为预览版模型,主要是新能力体验 GEMINI_25_PRO_PRE = "gemini-2.5-pro-preview-05-06" GEMINI_3_FLASH_PRE = "gemini-3-flash-preview" # Gemini 3 Flash Preview - Agent推荐模型 GEMINI_3_PRO_PRE = "gemini-3-pro-preview" # Gemini 3 Pro Preview - Agent推荐模型 # OpenAI GPT35 = "gpt-3.5-turbo" GPT35_0125 = "gpt-3.5-turbo-0125" GPT35_1106 = "gpt-3.5-turbo-1106" GPT4 = "gpt-4" GPT4_06_13 = "gpt-4-0613" GPT4_32k = "gpt-4-32k" GPT4_32k_06_13 = "gpt-4-32k-0613" GPT4_TURBO = "gpt-4-turbo" GPT4_TURBO_PREVIEW = "gpt-4-turbo-preview" GPT4_TURBO_01_25 = "gpt-4-0125-preview" GPT4_TURBO_11_06 = "gpt-4-1106-preview" GPT4_TURBO_04_09 = "gpt-4-turbo-2024-04-09" GPT4_VISION_PREVIEW = "gpt-4-vision-preview" GPT_4o = "gpt-4o" GPT_4O_0806 = "gpt-4o-2024-08-06" GPT_4o_MINI = "gpt-4o-mini" GPT_41 = "gpt-4.1" GPT_41_MINI = "gpt-4.1-mini" GPT_41_NANO = "gpt-4.1-nano" GPT_5 = "gpt-5" GPT_5_MINI = "gpt-5-mini" GPT_5_NANO = "gpt-5-nano" O1 = "o1-preview" O1_MINI = "o1-mini" WHISPER_1 = "whisper-1" TTS_1 = "tts-1" TTS_1_HD = "tts-1-hd" # DeepSeek DEEPSEEK_CHAT = "deepseek-chat" # DeepSeek-V3对话模型 DEEPSEEK_REASONER = "deepseek-reasoner" # DeepSeek-R1模型 # Qwen (通义千问 - 阿里云) QWEN = "qwen" QWEN_TURBO = "qwen-turbo" QWEN_PLUS = "qwen-plus" QWEN_MAX = "qwen-max" QWEN_LONG = "qwen-long" QWEN3_MAX = "qwen3-max" # Qwen3 Max - Agent推荐模型 QWQ_PLUS = "qwq-plus" # MiniMax MINIMAX_M2_5 = "MiniMax-M2.5" # MiniMax M2.5 - Latest MINIMAX_M2_1 = "MiniMax-M2.1" # MiniMax M2.1 - Agent推荐模型 MINIMAX_M2_1_LIGHTNING = "MiniMax-M2.1-lightning" # MiniMax M2.1 极速版 MINIMAX_M2 = "MiniMax-M2" # MiniMax M2 MINIMAX_ABAB6_5 = "abab6.5-chat" # MiniMax abab6.5 # GLM (智谱AI) GLM_5 = "glm-5" # 智谱 GLM-5 - Latest GLM_4 = "glm-4" GLM_4_PLUS = "glm-4-plus" GLM_4_flash = "glm-4-flash" GLM_4_LONG = "glm-4-long" GLM_4_ALLTOOLS = "glm-4-alltools" GLM_4_0520 = "glm-4-0520" GLM_4_AIR = "glm-4-air" GLM_4_AIRX = "glm-4-airx" GLM_4_7 = "glm-4.7" # 智谱 GLM-4.7 - Agent推荐模型 # Kimi (Moonshot) MOONSHOT = "moonshot" KIMI_K2 = "kimi-k2" KIMI_K2_5 = "kimi-k2.5" # Doubao (Volcengine Ark) DOUBAO = "doubao" DOUBAO_SEED_2_CODE = "doubao-seed-2-0-code-preview-260215" DOUBAO_SEED_2_PRO = "doubao-seed-2-0-pro-260215" DOUBAO_SEED_2_LITE = "doubao-seed-2-0-lite-260215" DOUBAO_SEED_2_MINI = "doubao-seed-2-0-mini-260215" # 其他模型 WEN_XIN = "wenxin" WEN_XIN_4 = "wenxin-4" XUNFEI = "xunfei" LINKAI_35 = "linkai-3.5" LINKAI_4_TURBO = "linkai-4-turbo" LINKAI_4o = "linkai-4o" MODELSCOPE = "modelscope" GITEE_AI_MODEL_LIST = ["Yi-34B-Chat", "InternVL2-8B", "deepseek-coder-33B-instruct", "InternVL2.5-26B", "Qwen2-VL-72B", "Qwen2.5-32B-Instruct", "glm-4-9b-chat", "codegeex4-all-9b", "Qwen2.5-Coder-32B-Instruct", "Qwen2.5-72B-Instruct", "Qwen2.5-7B-Instruct", "Qwen2-72B-Instruct", "Qwen2-7B-Instruct", "code-raccoon-v1", "Qwen2.5-14B-Instruct"] MODELSCOPE_MODEL_LIST = ["LLM-Research/c4ai-command-r-plus-08-2024","mistralai/Mistral-Small-Instruct-2409","mistralai/Ministral-8B-Instruct-2410","mistralai/Mistral-Large-Instruct-2407", "Qwen/Qwen2.5-Coder-32B-Instruct","Qwen/Qwen2.5-Coder-14B-Instruct","Qwen/Qwen2.5-Coder-7B-Instruct","Qwen/Qwen2.5-72B-Instruct","Qwen/Qwen2.5-32B-Instruct","Qwen/Qwen2.5-14B-Instruct","Qwen/Qwen2.5-7B-Instruct","Qwen/QwQ-32B-Preview", "LLM-Research/Llama-3.3-70B-Instruct","opencompass/CompassJudger-1-32B-Instruct","Qwen/QVQ-72B-Preview","LLM-Research/Meta-Llama-3.1-405B-Instruct","LLM-Research/Meta-Llama-3.1-8B-Instruct","Qwen/Qwen2-VL-7B-Instruct","LLM-Research/Meta-Llama-3.1-70B-Instruct", "Qwen/Qwen2.5-14B-Instruct-1M","Qwen/Qwen2.5-7B-Instruct-1M","Qwen/Qwen2.5-VL-3B-Instruct","Qwen/Qwen2.5-VL-7B-Instruct","Qwen/Qwen2.5-VL-72B-Instruct","deepseek-ai/DeepSeek-R1-Distill-Llama-70B","deepseek-ai/DeepSeek-R1-Distill-Llama-8B","deepseek-ai/DeepSeek-R1-Distill-Qwen-32B", "deepseek-ai/DeepSeek-R1-Distill-Qwen-14B","deepseek-ai/DeepSeek-R1-Distill-Qwen-7B","deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B","deepseek-ai/DeepSeek-R1","deepseek-ai/DeepSeek-V3","Qwen/QwQ-32B"] MODEL_LIST = [ # Claude CLAUDE3, CLAUDE_4_6_OPUS, CLAUDE_4_OPUS, CLAUDE_4_5_SONNET, CLAUDE_4_SONNET, CLAUDE_3_OPUS, CLAUDE_3_OPUS_0229, CLAUDE_35_SONNET, CLAUDE_35_SONNET_1022, CLAUDE_35_SONNET_0620, CLAUDE_3_SONNET, CLAUDE_3_HAIKU, "claude", "claude-3-haiku", "claude-3-sonnet", "claude-3-opus", "claude-3.5-sonnet", # Gemini GEMINI_3_PRO_PRE, GEMINI_3_FLASH_PRE, GEMINI_25_PRO_PRE, GEMINI_25_FLASH_PRE, GEMINI_20_FLASH, GEMINI_20_flash_exp, GEMINI_15_PRO, GEMINI_15_flash, GEMINI_PRO, GEMINI, # OpenAI GPT35, GPT35_0125, GPT35_1106, "gpt-3.5-turbo-16k", GPT4, GPT4_06_13, GPT4_32k, GPT4_32k_06_13, GPT4_TURBO, GPT4_TURBO_PREVIEW, GPT4_TURBO_01_25, GPT4_TURBO_11_06, GPT4_TURBO_04_09, GPT_4o, GPT_4O_0806, GPT_4o_MINI, GPT_41, GPT_41_MINI, GPT_41_NANO, GPT_5, GPT_5_MINI, GPT_5_NANO, O1, O1_MINI, # DeepSeek DEEPSEEK_CHAT, DEEPSEEK_REASONER, # Qwen QWEN, QWEN_TURBO, QWEN_PLUS, QWEN_MAX, QWEN_LONG, QWEN3_MAX, # MiniMax MiniMax, MINIMAX_M2_5, MINIMAX_M2_1, MINIMAX_M2_1_LIGHTNING, MINIMAX_M2, MINIMAX_ABAB6_5, # GLM ZHIPU_AI, GLM_5, GLM_4, GLM_4_PLUS, GLM_4_flash, GLM_4_LONG, GLM_4_ALLTOOLS, GLM_4_0520, GLM_4_AIR, GLM_4_AIRX, GLM_4_7, # Kimi MOONSHOT, "moonshot-v1-8k", "moonshot-v1-32k", "moonshot-v1-128k", KIMI_K2, KIMI_K2_5, # Doubao DOUBAO, DOUBAO_SEED_2_CODE, DOUBAO_SEED_2_PRO, DOUBAO_SEED_2_LITE, DOUBAO_SEED_2_MINI, # 其他模型 WEN_XIN, WEN_XIN_4, XUNFEI, LINKAI_35, LINKAI_4_TURBO, LINKAI_4o, MODELSCOPE ] MODEL_LIST = MODEL_LIST + GITEE_AI_MODEL_LIST + MODELSCOPE_MODEL_LIST # channel FEISHU = "feishu" DINGTALK = "dingtalk"
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/dequeue.py
Python
from queue import Full, Queue from time import monotonic as time # add implementation of putleft to Queue class Dequeue(Queue): def putleft(self, item, block=True, timeout=None): with self.not_full: if self.maxsize > 0: if not block: if self._qsize() >= self.maxsize: raise Full elif timeout is None: while self._qsize() >= self.maxsize: self.not_full.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time() + timeout while self._qsize() >= self.maxsize: remaining = endtime - time() if remaining <= 0.0: raise Full self.not_full.wait(remaining) self._putleft(item) self.unfinished_tasks += 1 self.not_empty.notify() def putleft_nowait(self, item): return self.putleft(item, block=False) def _putleft(self, item): self.queue.appendleft(item)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/expired_dict.py
Python
from datetime import datetime, timedelta class ExpiredDict(dict): def __init__(self, expires_in_seconds): super().__init__() self.expires_in_seconds = expires_in_seconds def __getitem__(self, key): value, expiry_time = super().__getitem__(key) if datetime.now() > expiry_time: del self[key] raise KeyError("expired {}".format(key)) self.__setitem__(key, value) return value def __setitem__(self, key, value): expiry_time = datetime.now() + timedelta(seconds=self.expires_in_seconds) super().__setitem__(key, (value, expiry_time)) def get(self, key, default=None): try: return self[key] except KeyError: return default def __contains__(self, key): try: self[key] return True except KeyError: return False def keys(self): keys = list(super().keys()) return [key for key in keys if key in self] def items(self): return [(key, self[key]) for key in self.keys()] def __iter__(self): return self.keys().__iter__()
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/linkai_client.py
Python
from bridge.context import Context, ContextType from bridge.reply import Reply, ReplyType from common.log import logger from linkai import LinkAIClient, PushMsg from config import conf, pconf, plugin_config, available_setting, write_plugin_config from plugins import PluginManager import time chat_client: LinkAIClient class ChatClient(LinkAIClient): def __init__(self, api_key, host, channel): super().__init__(api_key, host) self.channel = channel self.client_type = channel.channel_type def on_message(self, push_msg: PushMsg): session_id = push_msg.session_id msg_content = push_msg.msg_content logger.info(f"receive msg push, session_id={session_id}, msg_content={msg_content}") context = Context() context.type = ContextType.TEXT context["receiver"] = session_id context["isgroup"] = push_msg.is_group self.channel.send(Reply(ReplyType.TEXT, content=msg_content), context) def on_config(self, config: dict): if not self.client_id: return logger.info(f"[LinkAI] 从客户端管理加载远程配置: {config}") if config.get("enabled") != "Y": return local_config = conf() for key in config.keys(): if key in available_setting and config.get(key) is not None: local_config[key] = config.get(key) # 语音配置 reply_voice_mode = config.get("reply_voice_mode") if reply_voice_mode: if reply_voice_mode == "voice_reply_voice": local_config["voice_reply_voice"] = True local_config["always_reply_voice"] = False elif reply_voice_mode == "always_reply_voice": local_config["always_reply_voice"] = True local_config["voice_reply_voice"] = True elif reply_voice_mode == "no_reply_voice": local_config["always_reply_voice"] = False local_config["voice_reply_voice"] = False if config.get("admin_password"): if not pconf("Godcmd"): write_plugin_config({"Godcmd": {"password": config.get("admin_password"), "admin_users": []} }) else: pconf("Godcmd")["password"] = config.get("admin_password") PluginManager().instances["GODCMD"].reload() if config.get("group_app_map") and pconf("linkai"): local_group_map = {} for mapping in config.get("group_app_map"): local_group_map[mapping.get("group_name")] = mapping.get("app_code") pconf("linkai")["group_app_map"] = local_group_map PluginManager().instances["LINKAI"].reload() if config.get("text_to_image") and config.get("text_to_image") == "midjourney" and pconf("linkai"): if pconf("linkai")["midjourney"]: pconf("linkai")["midjourney"]["enabled"] = True pconf("linkai")["midjourney"]["use_image_create_prefix"] = True elif config.get("text_to_image") and config.get("text_to_image") in ["dall-e-2", "dall-e-3"]: if pconf("linkai")["midjourney"]: pconf("linkai")["midjourney"]["use_image_create_prefix"] = False def start(channel): global chat_client chat_client = ChatClient(api_key=conf().get("linkai_api_key"), host="", channel=channel) chat_client.config = _build_config() chat_client.start() time.sleep(1.5) if chat_client.client_id: logger.info("[LinkAI] 可前往控制台进行线上登录和配置:https://link-ai.tech/console/clients") def _build_config(): local_conf = conf() config = { "linkai_app_code": local_conf.get("linkai_app_code"), "single_chat_prefix": local_conf.get("single_chat_prefix"), "single_chat_reply_prefix": local_conf.get("single_chat_reply_prefix"), "single_chat_reply_suffix": local_conf.get("single_chat_reply_suffix"), "group_chat_prefix": local_conf.get("group_chat_prefix"), "group_chat_reply_prefix": local_conf.get("group_chat_reply_prefix"), "group_chat_reply_suffix": local_conf.get("group_chat_reply_suffix"), "group_name_white_list": local_conf.get("group_name_white_list"), "nick_name_black_list": local_conf.get("nick_name_black_list"), "speech_recognition": "Y" if local_conf.get("speech_recognition") else "N", "text_to_image": local_conf.get("text_to_image"), "image_create_prefix": local_conf.get("image_create_prefix") } if local_conf.get("always_reply_voice"): config["reply_voice_mode"] = "always_reply_voice" elif local_conf.get("voice_reply_voice"): config["reply_voice_mode"] = "voice_reply_voice" if pconf("linkai"): config["group_app_map"] = pconf("linkai").get("group_app_map") if plugin_config.get("Godcmd"): config["admin_password"] = plugin_config.get("Godcmd").get("password") return config
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/log.py
Python
import logging import sys def _reset_logger(log): for handler in log.handlers: handler.close() log.removeHandler(handler) del handler log.handlers.clear() log.propagate = False console_handle = logging.StreamHandler(sys.stdout) console_handle.setFormatter( logging.Formatter( "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) ) file_handle = logging.FileHandler("run.log", encoding="utf-8") file_handle.setFormatter( logging.Formatter( "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) ) log.addHandler(file_handle) log.addHandler(console_handle) def _get_logger(): log = logging.getLogger("log") _reset_logger(log) log.setLevel(logging.INFO) return log # 日志句柄 logger = _get_logger()
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/memory.py
Python
from common.expired_dict import ExpiredDict USER_IMAGE_CACHE = ExpiredDict(60 * 3)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/package_manager.py
Python
import time import pip from pip._internal import main as pipmain from common.log import _reset_logger, logger def install(package): pipmain(["install", package]) def install_requirements(file): pipmain(["install", "-r", file, "--upgrade"]) _reset_logger(logger) def check_dulwich(): needwait = False for i in range(2): if needwait: time.sleep(3) needwait = False try: import dulwich return except ImportError: try: install("dulwich") except: needwait = True try: import dulwich except ImportError: raise ImportError("Unable to import dulwich")
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/singleton.py
Python
def singleton(cls): instances = {} def get_instance(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return get_instance
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/sorted_dict.py
Python
import heapq class SortedDict(dict): def __init__(self, sort_func=lambda k, v: k, init_dict=None, reverse=False): if init_dict is None: init_dict = [] if isinstance(init_dict, dict): init_dict = init_dict.items() self.sort_func = sort_func self.sorted_keys = None self.reverse = reverse self.heap = [] for k, v in init_dict: self[k] = v def __setitem__(self, key, value): if key in self: super().__setitem__(key, value) for i, (priority, k) in enumerate(self.heap): if k == key: self.heap[i] = (self.sort_func(key, value), key) heapq.heapify(self.heap) break self.sorted_keys = None else: super().__setitem__(key, value) heapq.heappush(self.heap, (self.sort_func(key, value), key)) self.sorted_keys = None def __delitem__(self, key): super().__delitem__(key) for i, (priority, k) in enumerate(self.heap): if k == key: del self.heap[i] heapq.heapify(self.heap) break self.sorted_keys = None def keys(self): if self.sorted_keys is None: self.sorted_keys = [k for _, k in sorted(self.heap, reverse=self.reverse)] return self.sorted_keys def items(self): if self.sorted_keys is None: self.sorted_keys = [k for _, k in sorted(self.heap, reverse=self.reverse)] sorted_items = [(k, self[k]) for k in self.sorted_keys] return sorted_items def _update_heap(self, key): for i, (priority, k) in enumerate(self.heap): if k == key: new_priority = self.sort_func(key, self[key]) if new_priority != priority: self.heap[i] = (new_priority, key) heapq.heapify(self.heap) self.sorted_keys = None break def __iter__(self): return iter(self.keys()) def __repr__(self): return f"{type(self).__name__}({dict(self)}, sort_func={self.sort_func.__name__}, reverse={self.reverse})"
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/time_check.py
Python
import re import time import config from common.log import logger def time_checker(f): def _time_checker(self, *args, **kwargs): _config = config.conf() chat_time_module = _config.get("chat_time_module", False) if chat_time_module: chat_start_time = _config.get("chat_start_time", "00:00") chat_stop_time = _config.get("chat_stop_time", "24:00") time_regex = re.compile(r"^([01]?[0-9]|2[0-4])(:)([0-5][0-9])$") if not (time_regex.match(chat_start_time) and time_regex.match(chat_stop_time)): logger.warning("时间格式不正确,请在config.json中修改CHAT_START_TIME/CHAT_STOP_TIME。") return None now_time = time.strptime(time.strftime("%H:%M"), "%H:%M") chat_start_time = time.strptime(chat_start_time, "%H:%M") chat_stop_time = time.strptime(chat_stop_time, "%H:%M") # 结束时间小于开始时间,跨天了 if chat_stop_time < chat_start_time and (chat_start_time <= now_time or now_time <= chat_stop_time): f(self, *args, **kwargs) # 结束大于开始时间代表,没有跨天 elif chat_start_time < chat_stop_time and chat_start_time <= now_time <= chat_stop_time: f(self, *args, **kwargs) else: # 定义匹配规则,如果以 #reconf 或者 #更新配置 结尾, 非服务时间可以修改开始/结束时间并重载配置 pattern = re.compile(r"^.*#(?:reconf|更新配置)$") if args and pattern.match(args[0].content): f(self, *args, **kwargs) else: logger.info("非服务时间内,不接受访问") return None else: f(self, *args, **kwargs) # 未开启时间模块则直接回答 return _time_checker
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/tmp_dir.py
Python
import os import pathlib from config import conf class TmpDir(object): """A temporary directory that is deleted when the object is destroyed.""" tmpFilePath = pathlib.Path("./tmp/") def __init__(self): pathExists = os.path.exists(self.tmpFilePath) if not pathExists: os.makedirs(self.tmpFilePath) def path(self): return str(self.tmpFilePath) + "/"
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/token_bucket.py
Python
import threading import time class TokenBucket: def __init__(self, tpm, timeout=None): self.capacity = int(tpm) # 令牌桶容量 self.tokens = 0 # 初始令牌数为0 self.rate = int(tpm) / 60 # 令牌每秒生成速率 self.timeout = timeout # 等待令牌超时时间 self.cond = threading.Condition() # 条件变量 self.is_running = True # 开启令牌生成线程 threading.Thread(target=self._generate_tokens).start() def _generate_tokens(self): """生成令牌""" while self.is_running: with self.cond: if self.tokens < self.capacity: self.tokens += 1 self.cond.notify() # 通知获取令牌的线程 time.sleep(1 / self.rate) def get_token(self): """获取令牌""" with self.cond: while self.tokens <= 0: flag = self.cond.wait(self.timeout) if not flag: # 超时 return False self.tokens -= 1 return True def close(self): self.is_running = False if __name__ == "__main__": token_bucket = TokenBucket(20, None) # 创建一个每分钟生产20个tokens的令牌桶 # token_bucket = TokenBucket(20, 0.1) for i in range(3): if token_bucket.get_token(): print(f"第{i+1}次请求成功") token_bucket.close()
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
common/utils.py
Python
import io import os import re from urllib.parse import urlparse from common.log import logger def fsize(file): if isinstance(file, io.BytesIO): return file.getbuffer().nbytes elif isinstance(file, str): return os.path.getsize(file) elif hasattr(file, "seek") and hasattr(file, "tell"): pos = file.tell() file.seek(0, os.SEEK_END) size = file.tell() file.seek(pos) return size else: raise TypeError("Unsupported type") def compress_imgfile(file, max_size): if fsize(file) <= max_size: return file from PIL import Image file.seek(0) img = Image.open(file) rgb_image = img.convert("RGB") quality = 95 while True: out_buf = io.BytesIO() rgb_image.save(out_buf, "JPEG", quality=quality) if fsize(out_buf) <= max_size: return out_buf quality -= 5 def split_string_by_utf8_length(string, max_length, max_split=0): encoded = string.encode("utf-8") start, end = 0, 0 result = [] while end < len(encoded): if max_split > 0 and len(result) >= max_split: result.append(encoded[start:].decode("utf-8")) break end = min(start + max_length, len(encoded)) # 如果当前字节不是 UTF-8 编码的开始字节,则向前查找直到找到开始字节为止 while end < len(encoded) and (encoded[end] & 0b11000000) == 0b10000000: end -= 1 result.append(encoded[start:end].decode("utf-8")) start = end return result def get_path_suffix(path): path = urlparse(path).path return os.path.splitext(path)[-1].lstrip('.') def convert_webp_to_png(webp_image): from PIL import Image try: webp_image.seek(0) img = Image.open(webp_image).convert("RGBA") png_image = io.BytesIO() img.save(png_image, format="PNG") png_image.seek(0) return png_image except Exception as e: logger.error(f"Failed to convert WEBP to PNG: {e}") raise def remove_markdown_symbol(text: str): # 移除markdown格式,目前先移除** if not text: return text return re.sub(r'\*\*(.*?)\*\*', r'\1', text) def expand_path(path: str) -> str: """ Expand user path with proper Windows support. On Windows, os.path.expanduser('~') may not work properly in some shells (like PowerShell). This function provides a more robust path expansion. Args: path: Path string that may contain ~ Returns: Expanded absolute path """ if not path: return path # Try standard expansion first expanded = os.path.expanduser(path) # If expansion didn't work (path still starts with ~), use HOME or USERPROFILE if expanded.startswith('~'): import platform if platform.system() == 'Windows': # On Windows, try USERPROFILE first, then HOME home = os.environ.get('USERPROFILE') or os.environ.get('HOME') else: # On Unix-like systems, use HOME home = os.environ.get('HOME') if home: # Replace ~ with home directory if path == '~': expanded = home elif path.startswith('~/') or path.startswith('~\\'): expanded = os.path.join(home, path[2:]) return expanded
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
config.py
Python
# encoding:utf-8 import copy import json import logging import os import pickle from common.log import logger # 将所有可用的配置项写在字典里, 请使用小写字母 # 此处的配置值无实际意义,程序不会读取此处的配置,仅用于提示格式,请将配置加入到config.json中 available_setting = { # openai api配置 "open_ai_api_key": "", # openai api key # openai apibase,当use_azure_chatgpt为true时,需要设置对应的api base "open_ai_api_base": "https://api.openai.com/v1", "claude_api_base": "https://api.anthropic.com/v1", # claude api base "gemini_api_base": "https://generativelanguage.googleapis.com", # gemini api base "proxy": "", # openai使用的代理 # chatgpt模型, 当use_azure_chatgpt为true时,其名称为Azure上model deployment名称 "model": "gpt-3.5-turbo", # 可选择: gpt-4o, pt-4o-mini, gpt-4-turbo, claude-3-sonnet, wenxin, moonshot, qwen-turbo, xunfei, glm-4, minimax, gemini等模型,全部可选模型详见common/const.py文件 "bot_type": "", # 可选配置,使用兼容openai格式的三方服务时候,需填"chatGPT"。bot具体名称详见common/const.py文件列出的bot_type,如不填根据model名称判断, "use_azure_chatgpt": False, # 是否使用azure的chatgpt "azure_deployment_id": "", # azure 模型部署名称 "azure_api_version": "", # azure api版本 # Bot触发配置 "single_chat_prefix": ["bot", "@bot"], # 私聊时文本需要包含该前缀才能触发机器人回复 "single_chat_reply_prefix": "[bot] ", # 私聊时自动回复的前缀,用于区分真人 "single_chat_reply_suffix": "", # 私聊时自动回复的后缀,\n 可以换行 "group_chat_prefix": ["@bot"], # 群聊时包含该前缀则会触发机器人回复 "no_need_at": False, # 群聊回复时是否不需要艾特 "group_chat_reply_prefix": "", # 群聊时自动回复的前缀 "group_chat_reply_suffix": "", # 群聊时自动回复的后缀,\n 可以换行 "group_chat_keyword": [], # 群聊时包含该关键词则会触发机器人回复 "group_at_off": False, # 是否关闭群聊时@bot的触发 "group_name_white_list": ["ChatGPT测试群", "ChatGPT测试群2"], # 开启自动回复的群名称列表 "group_name_keyword_white_list": [], # 开启自动回复的群名称关键词列表 "group_chat_in_one_session": ["ChatGPT测试群"], # 支持会话上下文共享的群名称 "group_shared_session": True, # 群聊是否共享会话上下文(所有成员共享),默认为True。False时每个用户在群内有独立会话 "nick_name_black_list": [], # 用户昵称黑名单 "group_welcome_msg": "", # 配置新人进群固定欢迎语,不配置则使用随机风格欢迎 "trigger_by_self": False, # 是否允许机器人触发 "text_to_image": "dall-e-2", # 图片生成模型,可选 dall-e-2, dall-e-3 # Azure OpenAI dall-e-3 配置 "dalle3_image_style": "vivid", # 图片生成dalle3的风格,可选有 vivid, natural "dalle3_image_quality": "hd", # 图片生成dalle3的质量,可选有 standard, hd # Azure OpenAI DALL-E API 配置, 当use_azure_chatgpt为true时,用于将文字回复的资源和Dall-E的资源分开. "azure_openai_dalle_api_base": "", # [可选] azure openai 用于回复图片的资源 endpoint,默认使用 open_ai_api_base "azure_openai_dalle_api_key": "", # [可选] azure openai 用于回复图片的资源 key,默认使用 open_ai_api_key "azure_openai_dalle_deployment_id":"", # [可选] azure openai 用于回复图片的资源 deployment id,默认使用 text_to_image "image_proxy": True, # 是否需要图片代理,国内访问LinkAI时需要 "image_create_prefix": ["画", "看", "找"], # 开启图片回复的前缀 "concurrency_in_session": 1, # 同一会话最多有多少条消息在处理中,大于1可能乱序 "image_create_size": "256x256", # 图片大小,可选有 256x256, 512x512, 1024x1024 (dall-e-3默认为1024x1024) "group_chat_exit_group": False, # chatgpt会话参数 "expires_in_seconds": 3600, # 无操作会话的过期时间 # 人格描述 "character_desc": "你是ChatGPT, 一个由OpenAI训练的大型语言模型, 你旨在回答并解决人们的任何问题,并且可以使用多种语言与人交流。", "conversation_max_tokens": 1000, # 支持上下文记忆的最多字符数 # chatgpt限流配置 "rate_limit_chatgpt": 20, # chatgpt的调用频率限制 "rate_limit_dalle": 50, # openai dalle的调用频率限制 # chatgpt api参数 参考https://platform.openai.com/docs/api-reference/chat/create "temperature": 0.9, "top_p": 1, "frequency_penalty": 0, "presence_penalty": 0, "request_timeout": 180, # chatgpt请求超时时间,openai接口默认设置为600,对于难问题一般需要较长时间 "timeout": 120, # chatgpt重试超时时间,在这个时间内,将会自动重试 # Baidu 文心一言参数 "baidu_wenxin_model": "eb-instant", # 默认使用ERNIE-Bot-turbo模型 "baidu_wenxin_api_key": "", # Baidu api key "baidu_wenxin_secret_key": "", # Baidu secret key "baidu_wenxin_prompt_enabled": False, # Enable prompt if you are using ernie character model # 讯飞星火API "xunfei_app_id": "", # 讯飞应用ID "xunfei_api_key": "", # 讯飞 API key "xunfei_api_secret": "", # 讯飞 API secret "xunfei_domain": "", # 讯飞模型对应的domain参数,Spark4.0 Ultra为 4.0Ultra,其他模型详见: https://www.xfyun.cn/doc/spark/Web.html "xunfei_spark_url": "", # 讯飞模型对应的请求地址,Spark4.0 Ultra为 wss://spark-api.xf-yun.com/v4.0/chat,其他模型参考详见: https://www.xfyun.cn/doc/spark/Web.html # claude 配置 "claude_api_cookie": "", "claude_uuid": "", # claude api key "claude_api_key": "", # 通义千问API, 获取方式查看文档 https://help.aliyun.com/document_detail/2587494.html "qwen_access_key_id": "", "qwen_access_key_secret": "", "qwen_agent_key": "", "qwen_app_id": "", "qwen_node_id": "", # 流程编排模型用到的id,如果没有用到qwen_node_id,请务必保持为空字符串 # 阿里灵积(通义新版sdk)模型api key "dashscope_api_key": "", # Google Gemini Api Key "gemini_api_key": "", # wework的通用配置 "wework_smart": True, # 配置wework是否使用已登录的企业微信,False为多开 # 语音设置 "speech_recognition": True, # 是否开启语音识别 "group_speech_recognition": False, # 是否开启群组语音识别 "voice_reply_voice": False, # 是否使用语音回复语音,需要设置对应语音合成引擎的api key "always_reply_voice": False, # 是否一直使用语音回复 "voice_to_text": "openai", # 语音识别引擎,支持openai,baidu,google,azure,xunfei,ali "text_to_voice": "openai", # 语音合成引擎,支持openai,baidu,google,azure,xunfei,ali,pytts(offline),elevenlabs,edge(online) "text_to_voice_model": "tts-1", "tts_voice_id": "alloy", # baidu 语音api配置, 使用百度语音识别和语音合成时需要 "baidu_app_id": "", "baidu_api_key": "", "baidu_secret_key": "", # 1536普通话(支持简单的英文识别) 1737英语 1637粤语 1837四川话 1936普通话远场 "baidu_dev_pid": 1536, # azure 语音api配置, 使用azure语音识别和语音合成时需要 "azure_voice_api_key": "", "azure_voice_region": "japaneast", # elevenlabs 语音api配置 "xi_api_key": "", # 获取ap的方法可以参考https://docs.elevenlabs.io/api-reference/quick-start/authentication "xi_voice_id": "", # ElevenLabs提供了9种英式、美式等英语发音id,分别是“Adam/Antoni/Arnold/Bella/Domi/Elli/Josh/Rachel/Sam” # 服务时间限制,目前支持itchat "chat_time_module": False, # 是否开启服务时间限制 "chat_start_time": "00:00", # 服务开始时间 "chat_stop_time": "24:00", # 服务结束时间 # 翻译api "translate": "baidu", # 翻译api,支持baidu # baidu翻译api的配置 "baidu_translate_app_id": "", # 百度翻译api的appid "baidu_translate_app_key": "", # 百度翻译api的秘钥 # itchat的配置 "hot_reload": False, # 是否开启热重载 # wechaty的配置 "wechaty_puppet_service_token": "", # wechaty的token # wechatmp的配置 "wechatmp_token": "", # 微信公众平台的Token "wechatmp_port": 8080, # 微信公众平台的端口,需要端口转发到80或443 "wechatmp_app_id": "", # 微信公众平台的appID "wechatmp_app_secret": "", # 微信公众平台的appsecret "wechatmp_aes_key": "", # 微信公众平台的EncodingAESKey,加密模式需要 # wechatcom的通用配置 "wechatcom_corp_id": "", # 企业微信公司的corpID # wechatcomapp的配置 "wechatcomapp_token": "", # 企业微信app的token "wechatcomapp_port": 9898, # 企业微信app的服务端口,不需要端口转发 "wechatcomapp_secret": "", # 企业微信app的secret "wechatcomapp_agent_id": "", # 企业微信app的agent_id "wechatcomapp_aes_key": "", # 企业微信app的aes_key # 飞书配置 "feishu_port": 80, # 飞书bot监听端口 "feishu_app_id": "", # 飞书机器人应用APP Id "feishu_app_secret": "", # 飞书机器人APP secret "feishu_token": "", # 飞书 verification token "feishu_bot_name": "", # 飞书机器人的名字 "feishu_event_mode": "websocket", # 飞书事件接收模式: webhook(HTTP服务器) 或 websocket(长连接) # 钉钉配置 "dingtalk_client_id": "", # 钉钉机器人Client ID "dingtalk_client_secret": "", # 钉钉机器人Client Secret "dingtalk_card_enabled": False, # chatgpt指令自定义触发词 "clear_memory_commands": ["#清除记忆"], # 重置会话指令,必须以#开头 # channel配置 "channel_type": "", # 通道类型,支持:{wx,wxy,terminal,wechatmp,wechatmp_service,wechatcom_app,dingtalk} "subscribe_msg": "", # 订阅消息, 支持: wechatmp, wechatmp_service, wechatcom_app "debug": False, # 是否开启debug模式,开启后会打印更多日志 "appdata_dir": "", # 数据目录 # 插件配置 "plugin_trigger_prefix": "$", # 规范插件提供聊天相关指令的前缀,建议不要和管理员指令前缀"#"冲突 # 是否使用全局插件配置 "use_global_plugin_config": False, "max_media_send_count": 3, # 单次最大发送媒体资源的个数 "media_send_interval": 1, # 发送图片的事件间隔,单位秒 # 智谱AI 平台配置 "zhipu_ai_api_key": "", "zhipu_ai_api_base": "https://open.bigmodel.cn/api/paas/v4", "moonshot_api_key": "", "moonshot_base_url": "https://api.moonshot.cn/v1", # 豆包(火山方舟) 平台配置 "ark_api_key": "", "ark_base_url": "https://ark.cn-beijing.volces.com/api/v3", #魔搭社区 平台配置 "modelscope_api_key": "", "modelscope_base_url": "https://api-inference.modelscope.cn/v1/chat/completions", # LinkAI平台配置 "use_linkai": False, "linkai_api_key": "", "linkai_app_code": "", "linkai_api_base": "https://api.link-ai.tech", # linkAI服务地址 "minimax_api_key": "", "Minimax_group_id": "", "Minimax_base_url": "", "web_port": 9899, "agent": True, # 是否开启Agent模式 "agent_workspace": "~/cow", # agent工作空间路径,用于存储skills、memory等 "agent_max_context_tokens": 50000, # Agent模式下最大上下文tokens "agent_max_context_turns": 30, # Agent模式下最大上下文记忆轮次 "agent_max_steps": 15, # Agent模式下单次运行最大决策步数 } class Config(dict): def __init__(self, d=None): super().__init__() if d is None: d = {} for k, v in d.items(): self[k] = v # user_datas: 用户数据,key为用户名,value为用户数据,也是dict self.user_datas = {} def __getitem__(self, key): # 跳过以下划线开头的注释字段 if not key.startswith("_") and key not in available_setting: logger.warning("[Config] key '{}' not in available_setting, may not take effect".format(key)) return super().__getitem__(key) def __setitem__(self, key, value): # 跳过以下划线开头的注释字段 if not key.startswith("_") and key not in available_setting: logger.warning("[Config] key '{}' not in available_setting, may not take effect".format(key)) return super().__setitem__(key, value) def get(self, key, default=None): # 跳过以下划线开头的注释字段 if key.startswith("_"): return super().get(key, default) # 如果key不在available_setting中,直接返回default if key not in available_setting: return super().get(key, default) try: return self[key] except KeyError as e: return default except Exception as e: raise e # Make sure to return a dictionary to ensure atomic def get_user_data(self, user) -> dict: if self.user_datas.get(user) is None: self.user_datas[user] = {} return self.user_datas[user] def load_user_datas(self): try: with open(os.path.join(get_appdata_dir(), "user_datas.pkl"), "rb") as f: self.user_datas = pickle.load(f) logger.debug("[Config] User datas loaded.") except FileNotFoundError as e: logger.debug("[Config] User datas file not found, ignore.") except Exception as e: logger.warning("[Config] User datas error: {}".format(e)) self.user_datas = {} def save_user_datas(self): try: with open(os.path.join(get_appdata_dir(), "user_datas.pkl"), "wb") as f: pickle.dump(self.user_datas, f) logger.info("[Config] User datas saved.") except Exception as e: logger.info("[Config] User datas error: {}".format(e)) config = Config() def drag_sensitive(config): try: if isinstance(config, str): conf_dict: dict = json.loads(config) conf_dict_copy = copy.deepcopy(conf_dict) for key in conf_dict_copy: if "key" in key or "secret" in key: if isinstance(conf_dict_copy[key], str): conf_dict_copy[key] = conf_dict_copy[key][0:3] + "*" * 5 + conf_dict_copy[key][-3:] return json.dumps(conf_dict_copy, indent=4) elif isinstance(config, dict): config_copy = copy.deepcopy(config) for key in config: if "key" in key or "secret" in key: if isinstance(config_copy[key], str): config_copy[key] = config_copy[key][0:3] + "*" * 5 + config_copy[key][-3:] return config_copy except Exception as e: logger.exception(e) return config return config def load_config(): global config # 打印 ASCII Logo logger.info(" ____ _ _ ") logger.info(" / ___|_____ __ / \\ __ _ ___ _ __ | |_ ") logger.info("| | / _ \\ \\ /\\ / // _ \\ / _` |/ _ \\ '_ \\| __|") logger.info("| |__| (_) \\ V V // ___ \\ (_| | __/ | | | |_ ") logger.info(" \\____\\___/ \\_/\\_//_/ \\_\\__, |\\___|_| |_|\\__|") logger.info(" |___/ ") logger.info("") config_path = "./config.json" if not os.path.exists(config_path): logger.info("配置文件不存在,将使用config-template.json模板") config_path = "./config-template.json" config_str = read_file(config_path) logger.debug("[INIT] config str: {}".format(drag_sensitive(config_str))) # 将json字符串反序列化为dict类型 config = Config(json.loads(config_str)) # override config with environment variables. # Some online deployment platforms (e.g. Railway) deploy project from github directly. So you shouldn't put your secrets like api key in a config file, instead use environment variables to override the default config. for name, value in os.environ.items(): name = name.lower() # 跳过以下划线开头的注释字段 if name.startswith("_"): continue if name in available_setting: logger.info("[INIT] override config by environ args: {}={}".format(name, value)) try: config[name] = eval(value) except: if value == "false": config[name] = False elif value == "true": config[name] = True else: config[name] = value if config.get("debug", False): logger.setLevel(logging.DEBUG) logger.debug("[INIT] set log level to DEBUG") logger.info("[INIT] load config: {}".format(drag_sensitive(config))) # 打印系统初始化信息 logger.info("[INIT] ========================================") logger.info("[INIT] System Initialization") logger.info("[INIT] ========================================") logger.info("[INIT] Channel: {}".format(config.get("channel_type", "unknown"))) logger.info("[INIT] Model: {}".format(config.get("model", "unknown"))) # Agent模式信息 if config.get("agent", False): workspace = config.get("agent_workspace", "~/cow") logger.info("[INIT] Mode: Agent (workspace: {})".format(workspace)) else: logger.info("[INIT] Mode: Chat (在config.json中设置 \"agent\":true 可启用Agent模式)") logger.info("[INIT] Debug: {}".format(config.get("debug", False))) logger.info("[INIT] ========================================") config.load_user_datas() def get_root(): return os.path.dirname(os.path.abspath(__file__)) def read_file(path): with open(path, mode="r", encoding="utf-8") as f: return f.read() def conf(): return config def get_appdata_dir(): data_path = os.path.join(get_root(), conf().get("appdata_dir", "")) if not os.path.exists(data_path): logger.info("[INIT] data path not exists, create it: {}".format(data_path)) os.makedirs(data_path) return data_path def subscribe_msg(): trigger_prefix = conf().get("single_chat_prefix", [""])[0] msg = conf().get("subscribe_msg", "") return msg.format(trigger_prefix=trigger_prefix) # global plugin config plugin_config = {} def write_plugin_config(pconf: dict): """ 写入插件全局配置 :param pconf: 全量插件配置 """ global plugin_config for k in pconf: plugin_config[k.lower()] = pconf[k] def remove_plugin_config(name: str): """ 移除待重新加载的插件全局配置 :param name: 待重载的插件名 """ global plugin_config plugin_config.pop(name.lower(), None) def pconf(plugin_name: str) -> dict: """ 根据插件名称获取配置 :param plugin_name: 插件名称 :return: 该插件的配置项 """ return plugin_config.get(plugin_name.lower()) # 全局配置,用于存放全局生效的状态 global_config = {"admin_users": []}
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
docker/build.latest.sh
Shell
#!/bin/bash unset KUBECONFIG cd .. && docker build -f docker/Dockerfile.latest \ -t zhayujie/chatgpt-on-wechat . docker tag zhayujie/chatgpt-on-wechat zhayujie/chatgpt-on-wechat:$(date +%y%m%d)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
docker/entrypoint.sh
Shell
#!/bin/bash set -e # build prefix CHATGPT_ON_WECHAT_PREFIX=${CHATGPT_ON_WECHAT_PREFIX:-""} # path to config.json CHATGPT_ON_WECHAT_CONFIG_PATH=${CHATGPT_ON_WECHAT_CONFIG_PATH:-""} # execution command line CHATGPT_ON_WECHAT_EXEC=${CHATGPT_ON_WECHAT_EXEC:-""} # use environment variables to pass parameters # if you have not defined environment variables, set them below # export OPEN_AI_API_KEY=${OPEN_AI_API_KEY:-'YOUR API KEY'} # export OPEN_AI_PROXY=${OPEN_AI_PROXY:-""} # export SINGLE_CHAT_PREFIX=${SINGLE_CHAT_PREFIX:-'["bot", "@bot"]'} # export SINGLE_CHAT_REPLY_PREFIX=${SINGLE_CHAT_REPLY_PREFIX:-'"[bot] "'} # export GROUP_CHAT_PREFIX=${GROUP_CHAT_PREFIX:-'["@bot"]'} # export GROUP_NAME_WHITE_LIST=${GROUP_NAME_WHITE_LIST:-'["ChatGPT测试群", "ChatGPT测试群2"]'} # export IMAGE_CREATE_PREFIX=${IMAGE_CREATE_PREFIX:-'["画", "看", "找"]'} # export CONVERSATION_MAX_TOKENS=${CONVERSATION_MAX_TOKENS:-"1000"} # export SPEECH_RECOGNITION=${SPEECH_RECOGNITION:-"False"} # export CHARACTER_DESC=${CHARACTER_DESC:-"你是ChatGPT, 一个由OpenAI训练的大型语言模型, 你旨在回答并解决人们的任何问题,并且可以使用多种语言与人交流。"} # export EXPIRES_IN_SECONDS=${EXPIRES_IN_SECONDS:-"3600"} # CHATGPT_ON_WECHAT_PREFIX is empty, use /app if [ "$CHATGPT_ON_WECHAT_PREFIX" == "" ] ; then CHATGPT_ON_WECHAT_PREFIX=/app fi # CHATGPT_ON_WECHAT_CONFIG_PATH is empty, use '/app/config.json' if [ "$CHATGPT_ON_WECHAT_CONFIG_PATH" == "" ] ; then CHATGPT_ON_WECHAT_CONFIG_PATH=$CHATGPT_ON_WECHAT_PREFIX/config.json fi # CHATGPT_ON_WECHAT_EXEC is empty, use ‘python app.py’ if [ "$CHATGPT_ON_WECHAT_EXEC" == "" ] ; then CHATGPT_ON_WECHAT_EXEC="python app.py" fi # modify content in config.json # if [ "$OPEN_AI_API_KEY" == "YOUR API KEY" ] || [ "$OPEN_AI_API_KEY" == "" ]; then # echo -e "\033[31m[Warning] You need to set OPEN_AI_API_KEY before running!\033[0m" # fi # go to prefix dir cd $CHATGPT_ON_WECHAT_PREFIX # excute $CHATGPT_ON_WECHAT_EXEC
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/__init__.py
Python
from .core import Core from .config import VERSION, ASYNC_COMPONENTS from .log import set_logging if ASYNC_COMPONENTS: from .async_components import load_components else: from .components import load_components __version__ = VERSION instanceList = [] def load_async_itchat() -> Core: """load async-based itchat instance Returns: Core: the abstract interface of itchat """ from .async_components import load_components load_components(Core) return Core() def load_sync_itchat() -> Core: """load sync-based itchat instance Returns: Core: the abstract interface of itchat """ from .components import load_components load_components(Core) return Core() if ASYNC_COMPONENTS: instance = load_async_itchat() else: instance = load_sync_itchat() instanceList = [instance] # I really want to use sys.modules[__name__] = originInstance # but it makes auto-fill a real mess, so forgive me for my following ** # actually it toke me less than 30 seconds, god bless Uganda # components.login login = instance.login get_QRuuid = instance.get_QRuuid get_QR = instance.get_QR check_login = instance.check_login web_init = instance.web_init show_mobile_login = instance.show_mobile_login start_receiving = instance.start_receiving get_msg = instance.get_msg logout = instance.logout # components.contact update_chatroom = instance.update_chatroom update_friend = instance.update_friend get_contact = instance.get_contact get_friends = instance.get_friends get_chatrooms = instance.get_chatrooms get_mps = instance.get_mps set_alias = instance.set_alias set_pinned = instance.set_pinned accept_friend = instance.accept_friend get_head_img = instance.get_head_img create_chatroom = instance.create_chatroom set_chatroom_name = instance.set_chatroom_name delete_member_from_chatroom = instance.delete_member_from_chatroom add_member_into_chatroom = instance.add_member_into_chatroom # components.messages send_raw_msg = instance.send_raw_msg send_msg = instance.send_msg upload_file = instance.upload_file send_file = instance.send_file send_image = instance.send_image send_video = instance.send_video send = instance.send revoke = instance.revoke # components.hotreload dump_login_status = instance.dump_login_status load_login_status = instance.load_login_status # components.register auto_login = instance.auto_login configured_reply = instance.configured_reply msg_register = instance.msg_register run = instance.run # other functions search_friends = instance.search_friends search_chatrooms = instance.search_chatrooms search_mps = instance.search_mps set_logging = set_logging
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/async_components/__init__.py
Python
from .contact import load_contact from .hotreload import load_hotreload from .login import load_login from .messages import load_messages from .register import load_register def load_components(core): load_contact(core) load_hotreload(core) load_login(core) load_messages(core) load_register(core)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/async_components/contact.py
Python
import time, re, io import json, copy import logging from .. import config, utils from ..components.contact import accept_friend from ..returnvalues import ReturnValue from ..storage import contact_change from ..utils import update_info_dict logger = logging.getLogger('itchat') def load_contact(core): core.update_chatroom = update_chatroom core.update_friend = update_friend core.get_contact = get_contact core.get_friends = get_friends core.get_chatrooms = get_chatrooms core.get_mps = get_mps core.set_alias = set_alias core.set_pinned = set_pinned core.accept_friend = accept_friend core.get_head_img = get_head_img core.create_chatroom = create_chatroom core.set_chatroom_name = set_chatroom_name core.delete_member_from_chatroom = delete_member_from_chatroom core.add_member_into_chatroom = add_member_into_chatroom def update_chatroom(self, userName, detailedMember=False): if not isinstance(userName, list): userName = [userName] url = '%s/webwxbatchgetcontact?type=ex&r=%s' % ( self.loginInfo['url'], int(time.time())) headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT } data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Count': len(userName), 'List': [{ 'UserName': u, 'ChatRoomId': '', } for u in userName], } chatroomList = json.loads(self.s.post(url, data=json.dumps(data), headers=headers ).content.decode('utf8', 'replace')).get('ContactList') if not chatroomList: return ReturnValue({'BaseResponse': { 'ErrMsg': 'No chatroom found', 'Ret': -1001, }}) if detailedMember: def get_detailed_member_info(encryChatroomId, memberList): url = '%s/webwxbatchgetcontact?type=ex&r=%s' % ( self.loginInfo['url'], int(time.time())) headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT, } data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Count': len(memberList), 'List': [{ 'UserName': member['UserName'], 'EncryChatRoomId': encryChatroomId} \ for member in memberList], } return json.loads(self.s.post(url, data=json.dumps(data), headers=headers ).content.decode('utf8', 'replace'))['ContactList'] MAX_GET_NUMBER = 50 for chatroom in chatroomList: totalMemberList = [] for i in range(int(len(chatroom['MemberList']) / MAX_GET_NUMBER + 1)): memberList = chatroom['MemberList'][i*MAX_GET_NUMBER: (i+1)*MAX_GET_NUMBER] totalMemberList += get_detailed_member_info(chatroom['EncryChatRoomId'], memberList) chatroom['MemberList'] = totalMemberList update_local_chatrooms(self, chatroomList) r = [self.storageClass.search_chatrooms(userName=c['UserName']) for c in chatroomList] return r if 1 < len(r) else r[0] def update_friend(self, userName): if not isinstance(userName, list): userName = [userName] url = '%s/webwxbatchgetcontact?type=ex&r=%s' % ( self.loginInfo['url'], int(time.time())) headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT } data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Count': len(userName), 'List': [{ 'UserName': u, 'EncryChatRoomId': '', } for u in userName], } friendList = json.loads(self.s.post(url, data=json.dumps(data), headers=headers ).content.decode('utf8', 'replace')).get('ContactList') update_local_friends(self, friendList) r = [self.storageClass.search_friends(userName=f['UserName']) for f in friendList] return r if len(r) != 1 else r[0] @contact_change def update_local_chatrooms(core, l): ''' get a list of chatrooms for updating local chatrooms return a list of given chatrooms with updated info ''' for chatroom in l: # format new chatrooms utils.emoji_formatter(chatroom, 'NickName') for member in chatroom['MemberList']: if 'NickName' in member: utils.emoji_formatter(member, 'NickName') if 'DisplayName' in member: utils.emoji_formatter(member, 'DisplayName') if 'RemarkName' in member: utils.emoji_formatter(member, 'RemarkName') # update it to old chatrooms oldChatroom = utils.search_dict_list( core.chatroomList, 'UserName', chatroom['UserName']) if oldChatroom: update_info_dict(oldChatroom, chatroom) # - update other values memberList = chatroom.get('MemberList', []) oldMemberList = oldChatroom['MemberList'] if memberList: for member in memberList: oldMember = utils.search_dict_list( oldMemberList, 'UserName', member['UserName']) if oldMember: update_info_dict(oldMember, member) else: oldMemberList.append(member) else: core.chatroomList.append(chatroom) oldChatroom = utils.search_dict_list( core.chatroomList, 'UserName', chatroom['UserName']) # delete useless members if len(chatroom['MemberList']) != len(oldChatroom['MemberList']) and \ chatroom['MemberList']: existsUserNames = [member['UserName'] for member in chatroom['MemberList']] delList = [] for i, member in enumerate(oldChatroom['MemberList']): if member['UserName'] not in existsUserNames: delList.append(i) delList.sort(reverse=True) for i in delList: del oldChatroom['MemberList'][i] # - update OwnerUin if oldChatroom.get('ChatRoomOwner') and oldChatroom.get('MemberList'): owner = utils.search_dict_list(oldChatroom['MemberList'], 'UserName', oldChatroom['ChatRoomOwner']) oldChatroom['OwnerUin'] = (owner or {}).get('Uin', 0) # - update IsAdmin if 'OwnerUin' in oldChatroom and oldChatroom['OwnerUin'] != 0: oldChatroom['IsAdmin'] = \ oldChatroom['OwnerUin'] == int(core.loginInfo['wxuin']) else: oldChatroom['IsAdmin'] = None # - update Self newSelf = utils.search_dict_list(oldChatroom['MemberList'], 'UserName', core.storageClass.userName) oldChatroom['Self'] = newSelf or copy.deepcopy(core.loginInfo['User']) return { 'Type' : 'System', 'Text' : [chatroom['UserName'] for chatroom in l], 'SystemInfo' : 'chatrooms', 'FromUserName' : core.storageClass.userName, 'ToUserName' : core.storageClass.userName, } @contact_change def update_local_friends(core, l): ''' get a list of friends or mps for updating local contact ''' fullList = core.memberList + core.mpList for friend in l: if 'NickName' in friend: utils.emoji_formatter(friend, 'NickName') if 'DisplayName' in friend: utils.emoji_formatter(friend, 'DisplayName') if 'RemarkName' in friend: utils.emoji_formatter(friend, 'RemarkName') oldInfoDict = utils.search_dict_list( fullList, 'UserName', friend['UserName']) if oldInfoDict is None: oldInfoDict = copy.deepcopy(friend) if oldInfoDict['VerifyFlag'] & 8 == 0: core.memberList.append(oldInfoDict) else: core.mpList.append(oldInfoDict) else: update_info_dict(oldInfoDict, friend) @contact_change def update_local_uin(core, msg): ''' content contains uins and StatusNotifyUserName contains username they are in same order, so what I do is to pair them together I caught an exception in this method while not knowing why but don't worry, it won't cause any problem ''' uins = re.search('<username>([^<]*?)<', msg['Content']) usernameChangedList = [] r = { 'Type': 'System', 'Text': usernameChangedList, 'SystemInfo': 'uins', } if uins: uins = uins.group(1).split(',') usernames = msg['StatusNotifyUserName'].split(',') if 0 < len(uins) == len(usernames): for uin, username in zip(uins, usernames): if not '@' in username: continue fullContact = core.memberList + core.chatroomList + core.mpList userDicts = utils.search_dict_list(fullContact, 'UserName', username) if userDicts: if userDicts.get('Uin', 0) == 0: userDicts['Uin'] = uin usernameChangedList.append(username) logger.debug('Uin fetched: %s, %s' % (username, uin)) else: if userDicts['Uin'] != uin: logger.debug('Uin changed: %s, %s' % ( userDicts['Uin'], uin)) else: if '@@' in username: core.storageClass.updateLock.release() update_chatroom(core, username) core.storageClass.updateLock.acquire() newChatroomDict = utils.search_dict_list( core.chatroomList, 'UserName', username) if newChatroomDict is None: newChatroomDict = utils.struct_friend_info({ 'UserName': username, 'Uin': uin, 'Self': copy.deepcopy(core.loginInfo['User'])}) core.chatroomList.append(newChatroomDict) else: newChatroomDict['Uin'] = uin elif '@' in username: core.storageClass.updateLock.release() update_friend(core, username) core.storageClass.updateLock.acquire() newFriendDict = utils.search_dict_list( core.memberList, 'UserName', username) if newFriendDict is None: newFriendDict = utils.struct_friend_info({ 'UserName': username, 'Uin': uin, }) core.memberList.append(newFriendDict) else: newFriendDict['Uin'] = uin usernameChangedList.append(username) logger.debug('Uin fetched: %s, %s' % (username, uin)) else: logger.debug('Wrong length of uins & usernames: %s, %s' % ( len(uins), len(usernames))) else: logger.debug('No uins in 51 message') logger.debug(msg['Content']) return r def get_contact(self, update=False): if not update: return utils.contact_deep_copy(self, self.chatroomList) def _get_contact(seq=0): url = '%s/webwxgetcontact?r=%s&seq=%s&skey=%s' % (self.loginInfo['url'], int(time.time()), seq, self.loginInfo['skey']) headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT, } try: r = self.s.get(url, headers=headers) except: logger.info('Failed to fetch contact, that may because of the amount of your chatrooms') for chatroom in self.get_chatrooms(): self.update_chatroom(chatroom['UserName'], detailedMember=True) return 0, [] j = json.loads(r.content.decode('utf-8', 'replace')) return j.get('Seq', 0), j.get('MemberList') seq, memberList = 0, [] while 1: seq, batchMemberList = _get_contact(seq) memberList.extend(batchMemberList) if seq == 0: break chatroomList, otherList = [], [] for m in memberList: if m['Sex'] != 0: otherList.append(m) elif '@@' in m['UserName']: chatroomList.append(m) elif '@' in m['UserName']: # mp will be dealt in update_local_friends as well otherList.append(m) if chatroomList: update_local_chatrooms(self, chatroomList) if otherList: update_local_friends(self, otherList) return utils.contact_deep_copy(self, chatroomList) def get_friends(self, update=False): if update: self.get_contact(update=True) return utils.contact_deep_copy(self, self.memberList) def get_chatrooms(self, update=False, contactOnly=False): if contactOnly: return self.get_contact(update=True) else: if update: self.get_contact(True) return utils.contact_deep_copy(self, self.chatroomList) def get_mps(self, update=False): if update: self.get_contact(update=True) return utils.contact_deep_copy(self, self.mpList) def set_alias(self, userName, alias): oldFriendInfo = utils.search_dict_list( self.memberList, 'UserName', userName) if oldFriendInfo is None: return ReturnValue({'BaseResponse': { 'Ret': -1001, }}) url = '%s/webwxoplog?lang=%s&pass_ticket=%s' % ( self.loginInfo['url'], 'zh_CN', self.loginInfo['pass_ticket']) data = { 'UserName' : userName, 'CmdId' : 2, 'RemarkName' : alias, 'BaseRequest' : self.loginInfo['BaseRequest'], } headers = { 'User-Agent' : config.USER_AGENT} r = self.s.post(url, json.dumps(data, ensure_ascii=False).encode('utf8'), headers=headers) r = ReturnValue(rawResponse=r) if r: oldFriendInfo['RemarkName'] = alias return r def set_pinned(self, userName, isPinned=True): url = '%s/webwxoplog?pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket']) data = { 'UserName' : userName, 'CmdId' : 3, 'OP' : int(isPinned), 'BaseRequest' : self.loginInfo['BaseRequest'], } headers = { 'User-Agent' : config.USER_AGENT} r = self.s.post(url, json=data, headers=headers) return ReturnValue(rawResponse=r) def accept_friend(self, userName, v4= '', autoUpdate=True): url = f"{self.loginInfo['url']}/webwxverifyuser?r={int(time.time())}&pass_ticket={self.loginInfo['pass_ticket']}" data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Opcode': 3, # 3 'VerifyUserListSize': 1, 'VerifyUserList': [{ 'Value': userName, 'VerifyUserTicket': v4, }], 'VerifyContent': '', 'SceneListCount': 1, 'SceneList': [33], 'skey': self.loginInfo['skey'], } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8', 'replace')) if autoUpdate: self.update_friend(userName) return ReturnValue(rawResponse=r) def get_head_img(self, userName=None, chatroomUserName=None, picDir=None): ''' get head image * if you want to get chatroom header: only set chatroomUserName * if you want to get friend header: only set userName * if you want to get chatroom member header: set both ''' params = { 'userName': userName or chatroomUserName or self.storageClass.userName, 'skey': self.loginInfo['skey'], 'type': 'big', } url = '%s/webwxgeticon' % self.loginInfo['url'] if chatroomUserName is None: infoDict = self.storageClass.search_friends(userName=userName) if infoDict is None: return ReturnValue({'BaseResponse': { 'ErrMsg': 'No friend found', 'Ret': -1001, }}) else: if userName is None: url = '%s/webwxgetheadimg' % self.loginInfo['url'] else: chatroom = self.storageClass.search_chatrooms(userName=chatroomUserName) if chatroomUserName is None: return ReturnValue({'BaseResponse': { 'ErrMsg': 'No chatroom found', 'Ret': -1001, }}) if 'EncryChatRoomId' in chatroom: params['chatroomid'] = chatroom['EncryChatRoomId'] params['chatroomid'] = params.get('chatroomid') or chatroom['UserName'] headers = { 'User-Agent' : config.USER_AGENT} r = self.s.get(url, params=params, stream=True, headers=headers) tempStorage = io.BytesIO() for block in r.iter_content(1024): tempStorage.write(block) if picDir is None: return tempStorage.getvalue() with open(picDir, 'wb') as f: f.write(tempStorage.getvalue()) tempStorage.seek(0) return ReturnValue({'BaseResponse': { 'ErrMsg': 'Successfully downloaded', 'Ret': 0, }, 'PostFix': utils.get_image_postfix(tempStorage.read(20)), }) def create_chatroom(self, memberList, topic=''): url = '%s/webwxcreatechatroom?pass_ticket=%s&r=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket'], int(time.time())) data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'MemberCount': len(memberList.split(',')), 'MemberList': [{'UserName': member} for member in memberList.split(',')], 'Topic': topic, } headers = { 'content-type': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8', 'ignore')) return ReturnValue(rawResponse=r) def set_chatroom_name(self, chatroomUserName, name): url = '%s/webwxupdatechatroom?fun=modtopic&pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket']) data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'ChatRoomName': chatroomUserName, 'NewTopic': name, } headers = { 'content-type': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8', 'ignore')) return ReturnValue(rawResponse=r) def delete_member_from_chatroom(self, chatroomUserName, memberList): url = '%s/webwxupdatechatroom?fun=delmember&pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket']) data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'ChatRoomName': chatroomUserName, 'DelMemberList': ','.join([member['UserName'] for member in memberList]), } headers = { 'content-type': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT} r = self.s.post(url, data=json.dumps(data),headers=headers) return ReturnValue(rawResponse=r) def add_member_into_chatroom(self, chatroomUserName, memberList, useInvitation=False): ''' add or invite member into chatroom * there are two ways to get members into chatroom: invite or directly add * but for chatrooms with more than 40 users, you can only use invite * but don't worry we will auto-force userInvitation for you when necessary ''' if not useInvitation: chatroom = self.storageClass.search_chatrooms(userName=chatroomUserName) if not chatroom: chatroom = self.update_chatroom(chatroomUserName) if len(chatroom['MemberList']) > self.loginInfo['InviteStartCount']: useInvitation = True if useInvitation: fun, memberKeyName = 'invitemember', 'InviteMemberList' else: fun, memberKeyName = 'addmember', 'AddMemberList' url = '%s/webwxupdatechatroom?fun=%s&pass_ticket=%s' % ( self.loginInfo['url'], fun, self.loginInfo['pass_ticket']) params = { 'BaseRequest' : self.loginInfo['BaseRequest'], 'ChatRoomName' : chatroomUserName, memberKeyName : memberList, } headers = { 'content-type': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT} r = self.s.post(url, data=json.dumps(params),headers=headers) return ReturnValue(rawResponse=r)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/async_components/hotreload.py
Python
import pickle, os import logging import requests # type: ignore from ..config import VERSION from ..returnvalues import ReturnValue from ..storage import templates from .contact import update_local_chatrooms, update_local_friends from .messages import produce_msg logger = logging.getLogger('itchat') def load_hotreload(core): core.dump_login_status = dump_login_status core.load_login_status = load_login_status async def dump_login_status(self, fileDir=None): fileDir = fileDir or self.hotReloadDir try: with open(fileDir, 'w') as f: f.write('itchat - DELETE THIS') os.remove(fileDir) except: raise Exception('Incorrect fileDir') status = { 'version' : VERSION, 'loginInfo' : self.loginInfo, 'cookies' : self.s.cookies.get_dict(), 'storage' : self.storageClass.dumps()} with open(fileDir, 'wb') as f: pickle.dump(status, f) logger.debug('Dump login status for hot reload successfully.') async def load_login_status(self, fileDir, loginCallback=None, exitCallback=None): try: with open(fileDir, 'rb') as f: j = pickle.load(f) except Exception as e: logger.debug('No such file, loading login status failed.') return ReturnValue({'BaseResponse': { 'ErrMsg': 'No such file, loading login status failed.', 'Ret': -1002, }}) if j.get('version', '') != VERSION: logger.debug(('you have updated itchat from %s to %s, ' + 'so cached status is ignored') % ( j.get('version', 'old version'), VERSION)) return ReturnValue({'BaseResponse': { 'ErrMsg': 'cached status ignored because of version', 'Ret': -1005, }}) self.loginInfo = j['loginInfo'] self.loginInfo['User'] = templates.User(self.loginInfo['User']) self.loginInfo['User'].core = self self.s.cookies = requests.utils.cookiejar_from_dict(j['cookies']) self.storageClass.loads(j['storage']) try: msgList, contactList = self.get_msg() except: msgList = contactList = None if (msgList or contactList) is None: self.logout() await load_last_login_status(self.s, j['cookies']) logger.debug('server refused, loading login status failed.') return ReturnValue({'BaseResponse': { 'ErrMsg': 'server refused, loading login status failed.', 'Ret': -1003, }}) else: if contactList: for contact in contactList: if '@@' in contact['UserName']: update_local_chatrooms(self, [contact]) else: update_local_friends(self, [contact]) if msgList: msgList = produce_msg(self, msgList) for msg in msgList: self.msgList.put(msg) await self.start_receiving(exitCallback) logger.debug('loading login status succeeded.') if hasattr(loginCallback, '__call__'): await loginCallback(self.storageClass.userName) return ReturnValue({'BaseResponse': { 'ErrMsg': 'loading login status succeeded.', 'Ret': 0, }}) async def load_last_login_status(session, cookiesDict): try: session.cookies = requests.utils.cookiejar_from_dict({ 'webwxuvid': cookiesDict['webwxuvid'], 'webwx_auth_ticket': cookiesDict['webwx_auth_ticket'], 'login_frequency': '2', 'last_wxuin': cookiesDict['wxuin'], 'wxloadtime': cookiesDict['wxloadtime'] + '_expired', 'wxpluginkey': cookiesDict['wxloadtime'], 'wxuin': cookiesDict['wxuin'], 'mm_lang': 'zh_CN', 'MM_WX_NOTIFY_STATE': '1', 'MM_WX_SOUND_STATE': '1', }) except: logger.info('Load status for push login failed, we may have experienced a cookies change.') logger.info('If you are using the newest version of itchat, you may report a bug.')
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/async_components/login.py
Python
import asyncio import os, time, re, io import threading import json import random import traceback import logging try: from httplib import BadStatusLine except ImportError: from http.client import BadStatusLine import requests # type: ignore from pyqrcode import QRCode from .. import config, utils from ..returnvalues import ReturnValue from ..storage.templates import wrap_user_dict from .contact import update_local_chatrooms, update_local_friends from .messages import produce_msg logger = logging.getLogger('itchat') def load_login(core): core.login = login core.get_QRuuid = get_QRuuid core.get_QR = get_QR core.check_login = check_login core.web_init = web_init core.show_mobile_login = show_mobile_login core.start_receiving = start_receiving core.get_msg = get_msg core.logout = logout async def login(self, enableCmdQR=False, picDir=None, qrCallback=None, EventScanPayload=None,ScanStatus=None,event_stream=None, loginCallback=None, exitCallback=None): if self.alive or self.isLogging: logger.warning('itchat has already logged in.') return self.isLogging = True while self.isLogging: uuid = await push_login(self) if uuid: payload = EventScanPayload( status=ScanStatus.Waiting, qrcode=f"qrcode/https://login.weixin.qq.com/l/{uuid}" ) event_stream.emit('scan', payload) await asyncio.sleep(0.1) else: logger.info('Getting uuid of QR code.') self.get_QRuuid() payload = EventScanPayload( status=ScanStatus.Waiting, qrcode=f"https://login.weixin.qq.com/l/{self.uuid}" ) print(f"https://wechaty.js.org/qrcode/https://login.weixin.qq.com/l/{self.uuid}") event_stream.emit('scan', payload) await asyncio.sleep(0.1) # logger.info('Please scan the QR code to log in.') isLoggedIn = False while not isLoggedIn: status = await self.check_login() # if hasattr(qrCallback, '__call__'): # await qrCallback(uuid=self.uuid, status=status, qrcode=self.qrStorage.getvalue()) if status == '200': isLoggedIn = True payload = EventScanPayload( status=ScanStatus.Scanned, qrcode=f"https://login.weixin.qq.com/l/{self.uuid}" ) event_stream.emit('scan', payload) await asyncio.sleep(0.1) elif status == '201': if isLoggedIn is not None: logger.info('Please press confirm on your phone.') isLoggedIn = None payload = EventScanPayload( status=ScanStatus.Waiting, qrcode=f"https://login.weixin.qq.com/l/{self.uuid}" ) event_stream.emit('scan', payload) await asyncio.sleep(0.1) elif status != '408': payload = EventScanPayload( status=ScanStatus.Cancel, qrcode=f"https://login.weixin.qq.com/l/{self.uuid}" ) event_stream.emit('scan', payload) await asyncio.sleep(0.1) break if isLoggedIn: payload = EventScanPayload( status=ScanStatus.Confirmed, qrcode=f"https://login.weixin.qq.com/l/{self.uuid}" ) event_stream.emit('scan', payload) await asyncio.sleep(0.1) break elif self.isLogging: logger.info('Log in time out, reloading QR code.') payload = EventScanPayload( status=ScanStatus.Timeout, qrcode=f"https://login.weixin.qq.com/l/{self.uuid}" ) event_stream.emit('scan', payload) await asyncio.sleep(0.1) else: return logger.info('Loading the contact, this may take a little while.') await self.web_init() await self.show_mobile_login() self.get_contact(True) if hasattr(loginCallback, '__call__'): r = await loginCallback(self.storageClass.userName) else: utils.clear_screen() if os.path.exists(picDir or config.DEFAULT_QR): os.remove(picDir or config.DEFAULT_QR) logger.info('Login successfully as %s' % self.storageClass.nickName) await self.start_receiving(exitCallback) self.isLogging = False async def push_login(core): cookiesDict = core.s.cookies.get_dict() if 'wxuin' in cookiesDict: url = '%s/cgi-bin/mmwebwx-bin/webwxpushloginurl?uin=%s' % ( config.BASE_URL, cookiesDict['wxuin']) headers = { 'User-Agent' : config.USER_AGENT} r = core.s.get(url, headers=headers).json() if 'uuid' in r and r.get('ret') in (0, '0'): core.uuid = r['uuid'] return r['uuid'] return False def get_QRuuid(self): url = '%s/jslogin' % config.BASE_URL params = { 'appid' : 'wx782c26e4c19acffb', 'fun' : 'new', 'redirect_uri' : 'https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?mod=desktop', 'lang' : 'zh_CN' } headers = { 'User-Agent' : config.USER_AGENT} r = self.s.get(url, params=params, headers=headers) regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)";' data = re.search(regx, r.text) if data and data.group(1) == '200': self.uuid = data.group(2) return self.uuid async def get_QR(self, uuid=None, enableCmdQR=False, picDir=None, qrCallback=None): uuid = uuid or self.uuid picDir = picDir or config.DEFAULT_QR qrStorage = io.BytesIO() qrCode = QRCode('https://login.weixin.qq.com/l/' + uuid) qrCode.png(qrStorage, scale=10) if hasattr(qrCallback, '__call__'): await qrCallback(uuid=uuid, status='0', qrcode=qrStorage.getvalue()) else: with open(picDir, 'wb') as f: f.write(qrStorage.getvalue()) if enableCmdQR: utils.print_cmd_qr(qrCode.text(1), enableCmdQR=enableCmdQR) else: utils.print_qr(picDir) return qrStorage async def check_login(self, uuid=None): uuid = uuid or self.uuid url = '%s/cgi-bin/mmwebwx-bin/login' % config.BASE_URL localTime = int(time.time()) params = 'loginicon=true&uuid=%s&tip=1&r=%s&_=%s' % ( uuid, int(-localTime / 1579), localTime) headers = { 'User-Agent' : config.USER_AGENT} r = self.s.get(url, params=params, headers=headers) regx = r'window.code=(\d+)' data = re.search(regx, r.text) if data and data.group(1) == '200': if await process_login_info(self, r.text): return '200' else: return '400' elif data: return data.group(1) else: return '400' async def process_login_info(core, loginContent): ''' when finish login (scanning qrcode) * syncUrl and fileUploadingUrl will be fetched * deviceid and msgid will be generated * skey, wxsid, wxuin, pass_ticket will be fetched ''' regx = r'window.redirect_uri="(\S+)";' core.loginInfo['url'] = re.search(regx, loginContent).group(1) headers = { 'User-Agent' : config.USER_AGENT, 'client-version' : config.UOS_PATCH_CLIENT_VERSION, 'extspam' : config.UOS_PATCH_EXTSPAM, 'referer' : 'https://wx.qq.com/?&lang=zh_CN&target=t' } r = core.s.get(core.loginInfo['url'], headers=headers, allow_redirects=False) core.loginInfo['url'] = core.loginInfo['url'][:core.loginInfo['url'].rfind('/')] for indexUrl, detailedUrl in ( ("wx2.qq.com" , ("file.wx2.qq.com", "webpush.wx2.qq.com")), ("wx8.qq.com" , ("file.wx8.qq.com", "webpush.wx8.qq.com")), ("qq.com" , ("file.wx.qq.com", "webpush.wx.qq.com")), ("web2.wechat.com" , ("file.web2.wechat.com", "webpush.web2.wechat.com")), ("wechat.com" , ("file.web.wechat.com", "webpush.web.wechat.com"))): fileUrl, syncUrl = ['https://%s/cgi-bin/mmwebwx-bin' % url for url in detailedUrl] if indexUrl in core.loginInfo['url']: core.loginInfo['fileUrl'], core.loginInfo['syncUrl'] = \ fileUrl, syncUrl break else: core.loginInfo['fileUrl'] = core.loginInfo['syncUrl'] = core.loginInfo['url'] core.loginInfo['deviceid'] = 'e' + repr(random.random())[2:17] core.loginInfo['logintime'] = int(time.time() * 1e3) core.loginInfo['BaseRequest'] = {} cookies = core.s.cookies.get_dict() skey = re.findall('<skey>(.*?)</skey>', r.text, re.S)[0] pass_ticket = re.findall('<pass_ticket>(.*?)</pass_ticket>', r.text, re.S)[0] core.loginInfo['skey'] = core.loginInfo['BaseRequest']['Skey'] = skey core.loginInfo['wxsid'] = core.loginInfo['BaseRequest']['Sid'] = cookies["wxsid"] core.loginInfo['wxuin'] = core.loginInfo['BaseRequest']['Uin'] = cookies["wxuin"] core.loginInfo['pass_ticket'] = pass_ticket # A question : why pass_ticket == DeviceID ? # deviceID is only a randomly generated number # UOS PATCH By luvletter2333, Sun Feb 28 10:00 PM # for node in xml.dom.minidom.parseString(r.text).documentElement.childNodes: # if node.nodeName == 'skey': # core.loginInfo['skey'] = core.loginInfo['BaseRequest']['Skey'] = node.childNodes[0].data # elif node.nodeName == 'wxsid': # core.loginInfo['wxsid'] = core.loginInfo['BaseRequest']['Sid'] = node.childNodes[0].data # elif node.nodeName == 'wxuin': # core.loginInfo['wxuin'] = core.loginInfo['BaseRequest']['Uin'] = node.childNodes[0].data # elif node.nodeName == 'pass_ticket': # core.loginInfo['pass_ticket'] = core.loginInfo['BaseRequest']['DeviceID'] = node.childNodes[0].data if not all([key in core.loginInfo for key in ('skey', 'wxsid', 'wxuin', 'pass_ticket')]): logger.error('Your wechat account may be LIMITED to log in WEB wechat, error info:\n%s' % r.text) core.isLogging = False return False return True async def web_init(self): url = '%s/webwxinit' % self.loginInfo['url'] params = { 'r': int(-time.time() / 1579), 'pass_ticket': self.loginInfo['pass_ticket'], } data = { 'BaseRequest': self.loginInfo['BaseRequest'], } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT, } r = self.s.post(url, params=params, data=json.dumps(data), headers=headers) dic = json.loads(r.content.decode('utf-8', 'replace')) # deal with login info utils.emoji_formatter(dic['User'], 'NickName') self.loginInfo['InviteStartCount'] = int(dic['InviteStartCount']) self.loginInfo['User'] = wrap_user_dict(utils.struct_friend_info(dic['User'])) self.memberList.append(self.loginInfo['User']) self.loginInfo['SyncKey'] = dic['SyncKey'] self.loginInfo['synckey'] = '|'.join(['%s_%s' % (item['Key'], item['Val']) for item in dic['SyncKey']['List']]) self.storageClass.userName = dic['User']['UserName'] self.storageClass.nickName = dic['User']['NickName'] # deal with contact list returned when init contactList = dic.get('ContactList', []) chatroomList, otherList = [], [] for m in contactList: if m['Sex'] != 0: otherList.append(m) elif '@@' in m['UserName']: m['MemberList'] = [] # don't let dirty info pollute the list chatroomList.append(m) elif '@' in m['UserName']: # mp will be dealt in update_local_friends as well otherList.append(m) if chatroomList: update_local_chatrooms(self, chatroomList) if otherList: update_local_friends(self, otherList) return dic async def show_mobile_login(self): url = '%s/webwxstatusnotify?lang=zh_CN&pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket']) data = { 'BaseRequest' : self.loginInfo['BaseRequest'], 'Code' : 3, 'FromUserName' : self.storageClass.userName, 'ToUserName' : self.storageClass.userName, 'ClientMsgId' : int(time.time()), } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT, } r = self.s.post(url, data=json.dumps(data), headers=headers) return ReturnValue(rawResponse=r) async def start_receiving(self, exitCallback=None, getReceivingFnOnly=False): self.alive = True def maintain_loop(): retryCount = 0 while self.alive: try: i = sync_check(self) if i is None: self.alive = False elif i == '0': pass else: msgList, contactList = self.get_msg() if msgList: msgList = produce_msg(self, msgList) for msg in msgList: self.msgList.put(msg) if contactList: chatroomList, otherList = [], [] for contact in contactList: if '@@' in contact['UserName']: chatroomList.append(contact) else: otherList.append(contact) chatroomMsg = update_local_chatrooms(self, chatroomList) chatroomMsg['User'] = self.loginInfo['User'] self.msgList.put(chatroomMsg) update_local_friends(self, otherList) retryCount = 0 except requests.exceptions.ReadTimeout: pass except: retryCount += 1 logger.error(traceback.format_exc()) if self.receivingRetryCount < retryCount: self.alive = False else: time.sleep(1) self.logout() if hasattr(exitCallback, '__call__'): exitCallback(self.storageClass.userName) else: logger.info('LOG OUT!') if getReceivingFnOnly: return maintain_loop else: maintainThread = threading.Thread(target=maintain_loop) maintainThread.setDaemon(True) maintainThread.start() def sync_check(self): url = '%s/synccheck' % self.loginInfo.get('syncUrl', self.loginInfo['url']) params = { 'r' : int(time.time() * 1000), 'skey' : self.loginInfo['skey'], 'sid' : self.loginInfo['wxsid'], 'uin' : self.loginInfo['wxuin'], 'deviceid' : self.loginInfo['deviceid'], 'synckey' : self.loginInfo['synckey'], '_' : self.loginInfo['logintime'], } headers = { 'User-Agent' : config.USER_AGENT} self.loginInfo['logintime'] += 1 try: r = self.s.get(url, params=params, headers=headers, timeout=config.TIMEOUT) except requests.exceptions.ConnectionError as e: try: if not isinstance(e.args[0].args[1], BadStatusLine): raise # will return a package with status '0 -' # and value like: # 6f:00:8a:9c:09:74:e4:d8:e0:14:bf:96:3a:56:a0:64:1b:a4:25:5d:12:f4:31:a5:30:f1:c6:48:5f:c3:75:6a:99:93 # seems like status of typing, but before I make further achievement code will remain like this return '2' except: raise r.raise_for_status() regx = r'window.synccheck={retcode:"(\d+)",selector:"(\d+)"}' pm = re.search(regx, r.text) if pm is None or pm.group(1) != '0': logger.debug('Unexpected sync check result: %s' % r.text) return None return pm.group(2) def get_msg(self): self.loginInfo['deviceid'] = 'e' + repr(random.random())[2:17] url = '%s/webwxsync?sid=%s&skey=%s&pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['wxsid'], self.loginInfo['skey'],self.loginInfo['pass_ticket']) data = { 'BaseRequest' : self.loginInfo['BaseRequest'], 'SyncKey' : self.loginInfo['SyncKey'], 'rr' : ~int(time.time()), } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT } r = self.s.post(url, data=json.dumps(data), headers=headers, timeout=config.TIMEOUT) dic = json.loads(r.content.decode('utf-8', 'replace')) if dic['BaseResponse']['Ret'] != 0: return None, None self.loginInfo['SyncKey'] = dic['SyncKey'] self.loginInfo['synckey'] = '|'.join(['%s_%s' % (item['Key'], item['Val']) for item in dic['SyncCheckKey']['List']]) return dic['AddMsgList'], dic['ModContactList'] def logout(self): if self.alive: url = '%s/webwxlogout' % self.loginInfo['url'] params = { 'redirect' : 1, 'type' : 1, 'skey' : self.loginInfo['skey'], } headers = { 'User-Agent' : config.USER_AGENT} self.s.get(url, params=params, headers=headers) self.alive = False self.isLogging = False self.s.cookies.clear() del self.chatroomList[:] del self.memberList[:] del self.mpList[:] return ReturnValue({'BaseResponse': { 'ErrMsg': 'logout successfully.', 'Ret': 0, }})
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/async_components/messages.py
Python
import os, time, re, io import json import mimetypes, hashlib import logging from collections import OrderedDict from .. import config, utils from ..returnvalues import ReturnValue from ..storage import templates from .contact import update_local_uin logger = logging.getLogger('itchat') def load_messages(core): core.send_raw_msg = send_raw_msg core.send_msg = send_msg core.upload_file = upload_file core.send_file = send_file core.send_image = send_image core.send_video = send_video core.send = send core.revoke = revoke async def get_download_fn(core, url, msgId): async def download_fn(downloadDir=None): params = { 'msgid': msgId, 'skey': core.loginInfo['skey'],} headers = { 'User-Agent' : config.USER_AGENT} r = core.s.get(url, params=params, stream=True, headers = headers) tempStorage = io.BytesIO() for block in r.iter_content(1024): tempStorage.write(block) if downloadDir is None: return tempStorage.getvalue() with open(downloadDir, 'wb') as f: f.write(tempStorage.getvalue()) tempStorage.seek(0) return ReturnValue({'BaseResponse': { 'ErrMsg': 'Successfully downloaded', 'Ret': 0, }, 'PostFix': utils.get_image_postfix(tempStorage.read(20)), }) return download_fn def produce_msg(core, msgList): ''' for messages types * 40 msg, 43 videochat, 50 VOIPMSG, 52 voipnotifymsg * 53 webwxvoipnotifymsg, 9999 sysnotice ''' rl = [] srl = [40, 43, 50, 52, 53, 9999] for m in msgList: # get actual opposite if m['FromUserName'] == core.storageClass.userName: actualOpposite = m['ToUserName'] else: actualOpposite = m['FromUserName'] # produce basic message if '@@' in m['FromUserName'] or '@@' in m['ToUserName']: produce_group_chat(core, m) else: utils.msg_formatter(m, 'Content') # set user of msg if '@@' in actualOpposite: m['User'] = core.search_chatrooms(userName=actualOpposite) or \ templates.Chatroom({'UserName': actualOpposite}) # we don't need to update chatroom here because we have # updated once when producing basic message elif actualOpposite in ('filehelper', 'fmessage'): m['User'] = templates.User({'UserName': actualOpposite}) else: m['User'] = core.search_mps(userName=actualOpposite) or \ core.search_friends(userName=actualOpposite) or \ templates.User(userName=actualOpposite) # by default we think there may be a user missing not a mp m['User'].core = core if m['MsgType'] == 1: # words if m['Url']: regx = r'(.+?\(.+?\))' data = re.search(regx, m['Content']) data = 'Map' if data is None else data.group(1) msg = { 'Type': 'Map', 'Text': data,} else: msg = { 'Type': 'Text', 'Text': m['Content'],} elif m['MsgType'] == 3 or m['MsgType'] == 47: # picture download_fn = get_download_fn(core, '%s/webwxgetmsgimg' % core.loginInfo['url'], m['NewMsgId']) msg = { 'Type' : 'Picture', 'FileName' : '%s.%s' % (time.strftime('%y%m%d-%H%M%S', time.localtime()), 'png' if m['MsgType'] == 3 else 'gif'), 'Text' : download_fn, } elif m['MsgType'] == 34: # voice download_fn = get_download_fn(core, '%s/webwxgetvoice' % core.loginInfo['url'], m['NewMsgId']) msg = { 'Type': 'Recording', 'FileName' : '%s.mp3' % time.strftime('%y%m%d-%H%M%S', time.localtime()), 'Text': download_fn,} elif m['MsgType'] == 37: # friends m['User']['UserName'] = m['RecommendInfo']['UserName'] msg = { 'Type': 'Friends', 'Text': { 'status' : m['Status'], 'userName' : m['RecommendInfo']['UserName'], 'verifyContent' : m['Ticket'], 'autoUpdate' : m['RecommendInfo'], }, } m['User'].verifyDict = msg['Text'] elif m['MsgType'] == 42: # name card msg = { 'Type': 'Card', 'Text': m['RecommendInfo'], } elif m['MsgType'] in (43, 62): # tiny video msgId = m['MsgId'] async def download_video(videoDir=None): url = '%s/webwxgetvideo' % core.loginInfo['url'] params = { 'msgid': msgId, 'skey': core.loginInfo['skey'],} headers = {'Range': 'bytes=0-', 'User-Agent' : config.USER_AGENT} r = core.s.get(url, params=params, headers=headers, stream=True) tempStorage = io.BytesIO() for block in r.iter_content(1024): tempStorage.write(block) if videoDir is None: return tempStorage.getvalue() with open(videoDir, 'wb') as f: f.write(tempStorage.getvalue()) return ReturnValue({'BaseResponse': { 'ErrMsg': 'Successfully downloaded', 'Ret': 0, }}) msg = { 'Type': 'Video', 'FileName' : '%s.mp4' % time.strftime('%y%m%d-%H%M%S', time.localtime()), 'Text': download_video, } elif m['MsgType'] == 49: # sharing if m['AppMsgType'] == 0: # chat history msg = { 'Type': 'Note', 'Text': m['Content'], } elif m['AppMsgType'] == 6: rawMsg = m cookiesList = {name:data for name,data in core.s.cookies.items()} async def download_atta(attaDir=None): url = core.loginInfo['fileUrl'] + '/webwxgetmedia' params = { 'sender': rawMsg['FromUserName'], 'mediaid': rawMsg['MediaId'], 'filename': rawMsg['FileName'], 'fromuser': core.loginInfo['wxuin'], 'pass_ticket': 'undefined', 'webwx_data_ticket': cookiesList['webwx_data_ticket'],} headers = { 'User-Agent' : config.USER_AGENT} r = core.s.get(url, params=params, stream=True, headers=headers) tempStorage = io.BytesIO() for block in r.iter_content(1024): tempStorage.write(block) if attaDir is None: return tempStorage.getvalue() with open(attaDir, 'wb') as f: f.write(tempStorage.getvalue()) return ReturnValue({'BaseResponse': { 'ErrMsg': 'Successfully downloaded', 'Ret': 0, }}) msg = { 'Type': 'Attachment', 'Text': download_atta, } elif m['AppMsgType'] == 8: download_fn = get_download_fn(core, '%s/webwxgetmsgimg' % core.loginInfo['url'], m['NewMsgId']) msg = { 'Type' : 'Picture', 'FileName' : '%s.gif' % ( time.strftime('%y%m%d-%H%M%S', time.localtime())), 'Text' : download_fn, } elif m['AppMsgType'] == 17: msg = { 'Type': 'Note', 'Text': m['FileName'], } elif m['AppMsgType'] == 2000: regx = r'\[CDATA\[(.+?)\][\s\S]+?\[CDATA\[(.+?)\]' data = re.search(regx, m['Content']) if data: data = data.group(2).split(u'\u3002')[0] else: data = 'You may found detailed info in Content key.' msg = { 'Type': 'Note', 'Text': data, } else: msg = { 'Type': 'Sharing', 'Text': m['FileName'], } elif m['MsgType'] == 51: # phone init msg = update_local_uin(core, m) elif m['MsgType'] == 10000: msg = { 'Type': 'Note', 'Text': m['Content'],} elif m['MsgType'] == 10002: regx = r'\[CDATA\[(.+?)\]\]' data = re.search(regx, m['Content']) data = 'System message' if data is None else data.group(1).replace('\\', '') msg = { 'Type': 'Note', 'Text': data, } elif m['MsgType'] in srl: msg = { 'Type': 'Useless', 'Text': 'UselessMsg', } else: logger.debug('Useless message received: %s\n%s' % (m['MsgType'], str(m))) msg = { 'Type': 'Useless', 'Text': 'UselessMsg', } m = dict(m, **msg) rl.append(m) return rl def produce_group_chat(core, msg): r = re.match('(@[0-9a-z]*?):<br/>(.*)$', msg['Content']) if r: actualUserName, content = r.groups() chatroomUserName = msg['FromUserName'] elif msg['FromUserName'] == core.storageClass.userName: actualUserName = core.storageClass.userName content = msg['Content'] chatroomUserName = msg['ToUserName'] else: msg['ActualUserName'] = core.storageClass.userName msg['ActualNickName'] = core.storageClass.nickName msg['IsAt'] = False utils.msg_formatter(msg, 'Content') return chatroom = core.storageClass.search_chatrooms(userName=chatroomUserName) member = utils.search_dict_list((chatroom or {}).get( 'MemberList') or [], 'UserName', actualUserName) if member is None: chatroom = core.update_chatroom(chatroomUserName) member = utils.search_dict_list((chatroom or {}).get( 'MemberList') or [], 'UserName', actualUserName) if member is None: logger.debug('chatroom member fetch failed with %s' % actualUserName) msg['ActualNickName'] = '' msg['IsAt'] = False else: msg['ActualNickName'] = member.get('DisplayName', '') or member['NickName'] atFlag = '@' + (chatroom['Self'].get('DisplayName', '') or core.storageClass.nickName) msg['IsAt'] = ( (atFlag + (u'\u2005' if u'\u2005' in msg['Content'] else ' ')) in msg['Content'] or msg['Content'].endswith(atFlag)) msg['ActualUserName'] = actualUserName msg['Content'] = content utils.msg_formatter(msg, 'Content') async def send_raw_msg(self, msgType, content, toUserName): url = '%s/webwxsendmsg' % self.loginInfo['url'] data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Msg': { 'Type': msgType, 'Content': content, 'FromUserName': self.storageClass.userName, 'ToUserName': (toUserName if toUserName else self.storageClass.userName), 'LocalID': int(time.time() * 1e4), 'ClientMsgId': int(time.time() * 1e4), }, 'Scene': 0, } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT} r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8')) return ReturnValue(rawResponse=r) async def send_msg(self, msg='Test Message', toUserName=None): logger.debug('Request to send a text message to %s: %s' % (toUserName, msg)) r = await self.send_raw_msg(1, msg, toUserName) return r def _prepare_file(fileDir, file_=None): fileDict = {} if file_: if hasattr(file_, 'read'): file_ = file_.read() else: return ReturnValue({'BaseResponse': { 'ErrMsg': 'file_ param should be opened file', 'Ret': -1005, }}) else: if not utils.check_file(fileDir): return ReturnValue({'BaseResponse': { 'ErrMsg': 'No file found in specific dir', 'Ret': -1002, }}) with open(fileDir, 'rb') as f: file_ = f.read() fileDict['fileSize'] = len(file_) fileDict['fileMd5'] = hashlib.md5(file_).hexdigest() fileDict['file_'] = io.BytesIO(file_) return fileDict def upload_file(self, fileDir, isPicture=False, isVideo=False, toUserName='filehelper', file_=None, preparedFile=None): logger.debug('Request to upload a %s: %s' % ( 'picture' if isPicture else 'video' if isVideo else 'file', fileDir)) if not preparedFile: preparedFile = _prepare_file(fileDir, file_) if not preparedFile: return preparedFile fileSize, fileMd5, file_ = \ preparedFile['fileSize'], preparedFile['fileMd5'], preparedFile['file_'] fileSymbol = 'pic' if isPicture else 'video' if isVideo else'doc' chunks = int((fileSize - 1) / 524288) + 1 clientMediaId = int(time.time() * 1e4) uploadMediaRequest = json.dumps(OrderedDict([ ('UploadType', 2), ('BaseRequest', self.loginInfo['BaseRequest']), ('ClientMediaId', clientMediaId), ('TotalLen', fileSize), ('StartPos', 0), ('DataLen', fileSize), ('MediaType', 4), ('FromUserName', self.storageClass.userName), ('ToUserName', toUserName), ('FileMd5', fileMd5)] ), separators = (',', ':')) r = {'BaseResponse': {'Ret': -1005, 'ErrMsg': 'Empty file detected'}} for chunk in range(chunks): r = upload_chunk_file(self, fileDir, fileSymbol, fileSize, file_, chunk, chunks, uploadMediaRequest) file_.close() if isinstance(r, dict): return ReturnValue(r) return ReturnValue(rawResponse=r) def upload_chunk_file(core, fileDir, fileSymbol, fileSize, file_, chunk, chunks, uploadMediaRequest): url = core.loginInfo.get('fileUrl', core.loginInfo['url']) + \ '/webwxuploadmedia?f=json' # save it on server cookiesList = {name:data for name,data in core.s.cookies.items()} fileType = mimetypes.guess_type(fileDir)[0] or 'application/octet-stream' fileName = utils.quote(os.path.basename(fileDir)) files = OrderedDict([ ('id', (None, 'WU_FILE_0')), ('name', (None, fileName)), ('type', (None, fileType)), ('lastModifiedDate', (None, time.strftime('%a %b %d %Y %H:%M:%S GMT+0800 (CST)'))), ('size', (None, str(fileSize))), ('chunks', (None, None)), ('chunk', (None, None)), ('mediatype', (None, fileSymbol)), ('uploadmediarequest', (None, uploadMediaRequest)), ('webwx_data_ticket', (None, cookiesList['webwx_data_ticket'])), ('pass_ticket', (None, core.loginInfo['pass_ticket'])), ('filename' , (fileName, file_.read(524288), 'application/octet-stream'))]) if chunks == 1: del files['chunk']; del files['chunks'] else: files['chunk'], files['chunks'] = (None, str(chunk)), (None, str(chunks)) headers = { 'User-Agent' : config.USER_AGENT} return core.s.post(url, files=files, headers=headers, timeout=config.TIMEOUT) async def send_file(self, fileDir, toUserName=None, mediaId=None, file_=None): logger.debug('Request to send a file(mediaId: %s) to %s: %s' % ( mediaId, toUserName, fileDir)) if hasattr(fileDir, 'read'): return ReturnValue({'BaseResponse': { 'ErrMsg': 'fileDir param should not be an opened file in send_file', 'Ret': -1005, }}) if toUserName is None: toUserName = self.storageClass.userName preparedFile = _prepare_file(fileDir, file_) if not preparedFile: return preparedFile fileSize = preparedFile['fileSize'] if mediaId is None: r = self.upload_file(fileDir, preparedFile=preparedFile) if r: mediaId = r['MediaId'] else: return r url = '%s/webwxsendappmsg?fun=async&f=json' % self.loginInfo['url'] data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Msg': { 'Type': 6, 'Content': ("<appmsg appid='wxeb7ec651dd0aefa9' sdkver=''><title>%s</title>" % os.path.basename(fileDir) + "<des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl>" + "<appattach><totallen>%s</totallen><attachid>%s</attachid>" % (str(fileSize), mediaId) + "<fileext>%s</fileext></appattach><extinfo></extinfo></appmsg>" % os.path.splitext(fileDir)[1].replace('.','')), 'FromUserName': self.storageClass.userName, 'ToUserName': toUserName, 'LocalID': int(time.time() * 1e4), 'ClientMsgId': int(time.time() * 1e4), }, 'Scene': 0, } headers = { 'User-Agent': config.USER_AGENT, 'Content-Type': 'application/json;charset=UTF-8', } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8')) return ReturnValue(rawResponse=r) async def send_image(self, fileDir=None, toUserName=None, mediaId=None, file_=None): logger.debug('Request to send a image(mediaId: %s) to %s: %s' % ( mediaId, toUserName, fileDir)) if fileDir or file_: if hasattr(fileDir, 'read'): file_, fileDir = fileDir, None if fileDir is None: fileDir = 'tmp.jpg' # specific fileDir to send gifs else: return ReturnValue({'BaseResponse': { 'ErrMsg': 'Either fileDir or file_ should be specific', 'Ret': -1005, }}) if toUserName is None: toUserName = self.storageClass.userName if mediaId is None: r = self.upload_file(fileDir, isPicture=not fileDir[-4:] == '.gif', file_=file_) if r: mediaId = r['MediaId'] else: return r url = '%s/webwxsendmsgimg?fun=async&f=json' % self.loginInfo['url'] data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Msg': { 'Type': 3, 'MediaId': mediaId, 'FromUserName': self.storageClass.userName, 'ToUserName': toUserName, 'LocalID': int(time.time() * 1e4), 'ClientMsgId': int(time.time() * 1e4), }, 'Scene': 0, } if fileDir[-4:] == '.gif': url = '%s/webwxsendemoticon?fun=sys' % self.loginInfo['url'] data['Msg']['Type'] = 47 data['Msg']['EmojiFlag'] = 2 headers = { 'User-Agent': config.USER_AGENT, 'Content-Type': 'application/json;charset=UTF-8', } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8')) return ReturnValue(rawResponse=r) async def send_video(self, fileDir=None, toUserName=None, mediaId=None, file_=None): logger.debug('Request to send a video(mediaId: %s) to %s: %s' % ( mediaId, toUserName, fileDir)) if fileDir or file_: if hasattr(fileDir, 'read'): file_, fileDir = fileDir, None if fileDir is None: fileDir = 'tmp.mp4' # specific fileDir to send other formats else: return ReturnValue({'BaseResponse': { 'ErrMsg': 'Either fileDir or file_ should be specific', 'Ret': -1005, }}) if toUserName is None: toUserName = self.storageClass.userName if mediaId is None: r = self.upload_file(fileDir, isVideo=True, file_=file_) if r: mediaId = r['MediaId'] else: return r url = '%s/webwxsendvideomsg?fun=async&f=json&pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket']) data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Msg': { 'Type' : 43, 'MediaId' : mediaId, 'FromUserName' : self.storageClass.userName, 'ToUserName' : toUserName, 'LocalID' : int(time.time() * 1e4), 'ClientMsgId' : int(time.time() * 1e4), }, 'Scene': 0, } headers = { 'User-Agent' : config.USER_AGENT, 'Content-Type': 'application/json;charset=UTF-8', } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8')) return ReturnValue(rawResponse=r) async def send(self, msg, toUserName=None, mediaId=None): if not msg: r = ReturnValue({'BaseResponse': { 'ErrMsg': 'No message.', 'Ret': -1005, }}) elif msg[:5] == '@fil@': if mediaId is None: r = await self.send_file(msg[5:], toUserName) else: r = await self.send_file(msg[5:], toUserName, mediaId) elif msg[:5] == '@img@': if mediaId is None: r = await self.send_image(msg[5:], toUserName) else: r = await self.send_image(msg[5:], toUserName, mediaId) elif msg[:5] == '@msg@': r = await self.send_msg(msg[5:], toUserName) elif msg[:5] == '@vid@': if mediaId is None: r = await self.send_video(msg[5:], toUserName) else: r = await self.send_video(msg[5:], toUserName, mediaId) else: r = await self.send_msg(msg, toUserName) return r async def revoke(self, msgId, toUserName, localId=None): url = '%s/webwxrevokemsg' % self.loginInfo['url'] data = { 'BaseRequest': self.loginInfo['BaseRequest'], "ClientMsgId": localId or str(time.time() * 1e3), "SvrMsgId": msgId, "ToUserName": toUserName} headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8')) return ReturnValue(rawResponse=r)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/async_components/register.py
Python
import logging, traceback, sys, threading try: import Queue except ImportError: import queue as Queue # type: ignore from ..log import set_logging from ..utils import test_connect from ..storage import templates logger = logging.getLogger('itchat') def load_register(core): core.auto_login = auto_login core.configured_reply = configured_reply core.msg_register = msg_register core.run = run async def auto_login(self, EventScanPayload=None,ScanStatus=None,event_stream=None, hotReload=True, statusStorageDir='itchat.pkl', enableCmdQR=False, picDir=None, qrCallback=None, loginCallback=None, exitCallback=None): if not test_connect(): logger.info("You can't get access to internet or wechat domain, so exit.") sys.exit() self.useHotReload = hotReload self.hotReloadDir = statusStorageDir if hotReload: if await self.load_login_status(statusStorageDir, loginCallback=loginCallback, exitCallback=exitCallback): return await self.login(enableCmdQR=enableCmdQR, picDir=picDir, qrCallback=qrCallback, EventScanPayload=EventScanPayload, ScanStatus=ScanStatus, event_stream=event_stream, loginCallback=loginCallback, exitCallback=exitCallback) await self.dump_login_status(statusStorageDir) else: await self.login(enableCmdQR=enableCmdQR, picDir=picDir, qrCallback=qrCallback, EventScanPayload=EventScanPayload, ScanStatus=ScanStatus, event_stream=event_stream, loginCallback=loginCallback, exitCallback=exitCallback) async def configured_reply(self, event_stream, payload, message_container): ''' determine the type of message and reply if its method is defined however, I use a strange way to determine whether a msg is from massive platform I haven't found a better solution here The main problem I'm worrying about is the mismatching of new friends added on phone If you have any good idea, pleeeease report an issue. I will be more than grateful. ''' try: msg = self.msgList.get(timeout=1) if 'MsgId' in msg.keys(): message_container[msg['MsgId']] = msg except Queue.Empty: pass else: if isinstance(msg['User'], templates.User): replyFn = self.functionDict['FriendChat'].get(msg['Type']) elif isinstance(msg['User'], templates.MassivePlatform): replyFn = self.functionDict['MpChat'].get(msg['Type']) elif isinstance(msg['User'], templates.Chatroom): replyFn = self.functionDict['GroupChat'].get(msg['Type']) if replyFn is None: r = None else: try: r = await replyFn(msg) if r is not None: await self.send(r, msg.get('FromUserName')) except: logger.warning(traceback.format_exc()) def msg_register(self, msgType, isFriendChat=False, isGroupChat=False, isMpChat=False): ''' a decorator constructor return a specific decorator based on information given ''' if not (isinstance(msgType, list) or isinstance(msgType, tuple)): msgType = [msgType] def _msg_register(fn): for _msgType in msgType: if isFriendChat: self.functionDict['FriendChat'][_msgType] = fn if isGroupChat: self.functionDict['GroupChat'][_msgType] = fn if isMpChat: self.functionDict['MpChat'][_msgType] = fn if not any((isFriendChat, isGroupChat, isMpChat)): self.functionDict['FriendChat'][_msgType] = fn return fn return _msg_register async def run(self, debug=False, blockThread=True): logger.info('Start auto replying.') if debug: set_logging(loggingLevel=logging.DEBUG) async def reply_fn(): try: while self.alive: await self.configured_reply() except KeyboardInterrupt: if self.useHotReload: await self.dump_login_status() self.alive = False logger.debug('itchat received an ^C and exit.') logger.info('Bye~') if blockThread: await reply_fn() else: replyThread = threading.Thread(target=reply_fn) replyThread.setDaemon(True) replyThread.start()
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/components/__init__.py
Python
from .contact import load_contact from .hotreload import load_hotreload from .login import load_login from .messages import load_messages from .register import load_register def load_components(core): load_contact(core) load_hotreload(core) load_login(core) load_messages(core) load_register(core)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/components/contact.py
Python
import time import re import io import json import copy import logging from .. import config, utils from ..returnvalues import ReturnValue from ..storage import contact_change from ..utils import update_info_dict logger = logging.getLogger('itchat') def load_contact(core): core.update_chatroom = update_chatroom core.update_friend = update_friend core.get_contact = get_contact core.get_friends = get_friends core.get_chatrooms = get_chatrooms core.get_mps = get_mps core.set_alias = set_alias core.set_pinned = set_pinned core.accept_friend = accept_friend core.get_head_img = get_head_img core.create_chatroom = create_chatroom core.set_chatroom_name = set_chatroom_name core.delete_member_from_chatroom = delete_member_from_chatroom core.add_member_into_chatroom = add_member_into_chatroom def update_chatroom(self, userName, detailedMember=False): if not isinstance(userName, list): userName = [userName] url = '%s/webwxbatchgetcontact?type=ex&r=%s' % ( self.loginInfo['url'], int(time.time())) headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent': config.USER_AGENT} data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Count': len(userName), 'List': [{ 'UserName': u, 'ChatRoomId': '', } for u in userName], } chatroomList = json.loads(self.s.post(url, data=json.dumps(data), headers=headers ).content.decode('utf8', 'replace')).get('ContactList') if not chatroomList: return ReturnValue({'BaseResponse': { 'ErrMsg': 'No chatroom found', 'Ret': -1001, }}) if detailedMember: def get_detailed_member_info(encryChatroomId, memberList): url = '%s/webwxbatchgetcontact?type=ex&r=%s' % ( self.loginInfo['url'], int(time.time())) headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent': config.USER_AGENT, } data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Count': len(memberList), 'List': [{ 'UserName': member['UserName'], 'EncryChatRoomId': encryChatroomId} for member in memberList], } return json.loads(self.s.post(url, data=json.dumps(data), headers=headers ).content.decode('utf8', 'replace'))['ContactList'] MAX_GET_NUMBER = 50 for chatroom in chatroomList: totalMemberList = [] for i in range(int(len(chatroom['MemberList']) / MAX_GET_NUMBER + 1)): memberList = chatroom['MemberList'][i * MAX_GET_NUMBER: (i+1)*MAX_GET_NUMBER] totalMemberList += get_detailed_member_info( chatroom['EncryChatRoomId'], memberList) chatroom['MemberList'] = totalMemberList update_local_chatrooms(self, chatroomList) r = [self.storageClass.search_chatrooms(userName=c['UserName']) for c in chatroomList] return r if 1 < len(r) else r[0] def update_friend(self, userName): if not isinstance(userName, list): userName = [userName] url = '%s/webwxbatchgetcontact?type=ex&r=%s' % ( self.loginInfo['url'], int(time.time())) headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent': config.USER_AGENT} data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Count': len(userName), 'List': [{ 'UserName': u, 'EncryChatRoomId': '', } for u in userName], } friendList = json.loads(self.s.post(url, data=json.dumps(data), headers=headers ).content.decode('utf8', 'replace')).get('ContactList') update_local_friends(self, friendList) r = [self.storageClass.search_friends(userName=f['UserName']) for f in friendList] return r if len(r) != 1 else r[0] @contact_change def update_local_chatrooms(core, l): ''' get a list of chatrooms for updating local chatrooms return a list of given chatrooms with updated info ''' for chatroom in l: # format new chatrooms utils.emoji_formatter(chatroom, 'NickName') for member in chatroom['MemberList']: if 'NickName' in member: utils.emoji_formatter(member, 'NickName') if 'DisplayName' in member: utils.emoji_formatter(member, 'DisplayName') if 'RemarkName' in member: utils.emoji_formatter(member, 'RemarkName') # update it to old chatrooms oldChatroom = utils.search_dict_list( core.chatroomList, 'UserName', chatroom['UserName']) if oldChatroom: update_info_dict(oldChatroom, chatroom) # - update other values memberList = chatroom.get('MemberList', []) oldMemberList = oldChatroom['MemberList'] if memberList: for member in memberList: oldMember = utils.search_dict_list( oldMemberList, 'UserName', member['UserName']) if oldMember: update_info_dict(oldMember, member) else: oldMemberList.append(member) else: core.chatroomList.append(chatroom) oldChatroom = utils.search_dict_list( core.chatroomList, 'UserName', chatroom['UserName']) # delete useless members if len(chatroom['MemberList']) != len(oldChatroom['MemberList']) and \ chatroom['MemberList']: existsUserNames = [member['UserName'] for member in chatroom['MemberList']] delList = [] for i, member in enumerate(oldChatroom['MemberList']): if member['UserName'] not in existsUserNames: delList.append(i) delList.sort(reverse=True) for i in delList: del oldChatroom['MemberList'][i] # - update OwnerUin if oldChatroom.get('ChatRoomOwner') and oldChatroom.get('MemberList'): owner = utils.search_dict_list(oldChatroom['MemberList'], 'UserName', oldChatroom['ChatRoomOwner']) oldChatroom['OwnerUin'] = (owner or {}).get('Uin', 0) # - update IsAdmin if 'OwnerUin' in oldChatroom and oldChatroom['OwnerUin'] != 0: oldChatroom['IsAdmin'] = \ oldChatroom['OwnerUin'] == int(core.loginInfo['wxuin']) else: oldChatroom['IsAdmin'] = None # - update Self newSelf = utils.search_dict_list(oldChatroom['MemberList'], 'UserName', core.storageClass.userName) oldChatroom['Self'] = newSelf or copy.deepcopy(core.loginInfo['User']) return { 'Type': 'System', 'Text': [chatroom['UserName'] for chatroom in l], 'SystemInfo': 'chatrooms', 'FromUserName': core.storageClass.userName, 'ToUserName': core.storageClass.userName, } @contact_change def update_local_friends(core, l): ''' get a list of friends or mps for updating local contact ''' fullList = core.memberList + core.mpList for friend in l: if 'NickName' in friend: utils.emoji_formatter(friend, 'NickName') if 'DisplayName' in friend: utils.emoji_formatter(friend, 'DisplayName') if 'RemarkName' in friend: utils.emoji_formatter(friend, 'RemarkName') oldInfoDict = utils.search_dict_list( fullList, 'UserName', friend['UserName']) if oldInfoDict is None: oldInfoDict = copy.deepcopy(friend) if oldInfoDict['VerifyFlag'] & 8 == 0: core.memberList.append(oldInfoDict) else: core.mpList.append(oldInfoDict) else: update_info_dict(oldInfoDict, friend) @contact_change def update_local_uin(core, msg): ''' content contains uins and StatusNotifyUserName contains username they are in same order, so what I do is to pair them together I caught an exception in this method while not knowing why but don't worry, it won't cause any problem ''' uins = re.search('<username>([^<]*?)<', msg['Content']) usernameChangedList = [] r = { 'Type': 'System', 'Text': usernameChangedList, 'SystemInfo': 'uins', } if uins: uins = uins.group(1).split(',') usernames = msg['StatusNotifyUserName'].split(',') if 0 < len(uins) == len(usernames): for uin, username in zip(uins, usernames): if not '@' in username: continue fullContact = core.memberList + core.chatroomList + core.mpList userDicts = utils.search_dict_list(fullContact, 'UserName', username) if userDicts: if userDicts.get('Uin', 0) == 0: userDicts['Uin'] = uin usernameChangedList.append(username) logger.debug('Uin fetched: %s, %s' % (username, uin)) else: if userDicts['Uin'] != uin: logger.debug('Uin changed: %s, %s' % ( userDicts['Uin'], uin)) else: if '@@' in username: core.storageClass.updateLock.release() update_chatroom(core, username) core.storageClass.updateLock.acquire() newChatroomDict = utils.search_dict_list( core.chatroomList, 'UserName', username) if newChatroomDict is None: newChatroomDict = utils.struct_friend_info({ 'UserName': username, 'Uin': uin, 'Self': copy.deepcopy(core.loginInfo['User'])}) core.chatroomList.append(newChatroomDict) else: newChatroomDict['Uin'] = uin elif '@' in username: core.storageClass.updateLock.release() update_friend(core, username) core.storageClass.updateLock.acquire() newFriendDict = utils.search_dict_list( core.memberList, 'UserName', username) if newFriendDict is None: newFriendDict = utils.struct_friend_info({ 'UserName': username, 'Uin': uin, }) core.memberList.append(newFriendDict) else: newFriendDict['Uin'] = uin usernameChangedList.append(username) logger.debug('Uin fetched: %s, %s' % (username, uin)) else: logger.debug('Wrong length of uins & usernames: %s, %s' % ( len(uins), len(usernames))) else: logger.debug('No uins in 51 message') logger.debug(msg['Content']) return r def get_contact(self, update=False): if not update: return utils.contact_deep_copy(self, self.chatroomList) def _get_contact(seq=0): url = '%s/webwxgetcontact?r=%s&seq=%s&skey=%s' % (self.loginInfo['url'], int(time.time()), seq, self.loginInfo['skey']) headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent': config.USER_AGENT, } try: r = self.s.get(url, headers=headers) except: logger.info( 'Failed to fetch contact, that may because of the amount of your chatrooms') for chatroom in self.get_chatrooms(): self.update_chatroom(chatroom['UserName'], detailedMember=True) return 0, [] j = json.loads(r.content.decode('utf-8', 'replace')) return j.get('Seq', 0), j.get('MemberList') seq, memberList = 0, [] while 1: seq, batchMemberList = _get_contact(seq) memberList.extend(batchMemberList) if seq == 0: break chatroomList, otherList = [], [] for m in memberList: if m['Sex'] != 0: otherList.append(m) elif '@@' in m['UserName']: chatroomList.append(m) elif '@' in m['UserName']: # mp will be dealt in update_local_friends as well otherList.append(m) if chatroomList: update_local_chatrooms(self, chatroomList) if otherList: update_local_friends(self, otherList) return utils.contact_deep_copy(self, chatroomList) def get_friends(self, update=False): if update: self.get_contact(update=True) return utils.contact_deep_copy(self, self.memberList) def get_chatrooms(self, update=False, contactOnly=False): if contactOnly: return self.get_contact(update=True) else: if update: self.get_contact(True) return utils.contact_deep_copy(self, self.chatroomList) def get_mps(self, update=False): if update: self.get_contact(update=True) return utils.contact_deep_copy(self, self.mpList) def set_alias(self, userName, alias): oldFriendInfo = utils.search_dict_list( self.memberList, 'UserName', userName) if oldFriendInfo is None: return ReturnValue({'BaseResponse': { 'Ret': -1001, }}) url = '%s/webwxoplog?lang=%s&pass_ticket=%s' % ( self.loginInfo['url'], 'zh_CN', self.loginInfo['pass_ticket']) data = { 'UserName': userName, 'CmdId': 2, 'RemarkName': alias, 'BaseRequest': self.loginInfo['BaseRequest'], } headers = {'User-Agent': config.USER_AGENT} r = self.s.post(url, json.dumps(data, ensure_ascii=False).encode('utf8'), headers=headers) r = ReturnValue(rawResponse=r) if r: oldFriendInfo['RemarkName'] = alias return r def set_pinned(self, userName, isPinned=True): url = '%s/webwxoplog?pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket']) data = { 'UserName': userName, 'CmdId': 3, 'OP': int(isPinned), 'BaseRequest': self.loginInfo['BaseRequest'], } headers = {'User-Agent': config.USER_AGENT} r = self.s.post(url, json=data, headers=headers) return ReturnValue(rawResponse=r) def accept_friend(self, userName, v4='', autoUpdate=True): url = f"{self.loginInfo['url']}/webwxverifyuser?r={int(time.time())}&pass_ticket={self.loginInfo['pass_ticket']}" data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Opcode': 3, # 3 'VerifyUserListSize': 1, 'VerifyUserList': [{ 'Value': userName, 'VerifyUserTicket': v4, }], 'VerifyContent': '', 'SceneListCount': 1, 'SceneList': [33], 'skey': self.loginInfo['skey'], } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent': config.USER_AGENT} r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8', 'replace')) if autoUpdate: self.update_friend(userName) return ReturnValue(rawResponse=r) def get_head_img(self, userName=None, chatroomUserName=None, picDir=None): ''' get head image * if you want to get chatroom header: only set chatroomUserName * if you want to get friend header: only set userName * if you want to get chatroom member header: set both ''' params = { 'userName': userName or chatroomUserName or self.storageClass.userName, 'skey': self.loginInfo['skey'], 'type': 'big', } url = '%s/webwxgeticon' % self.loginInfo['url'] if chatroomUserName is None: infoDict = self.storageClass.search_friends(userName=userName) if infoDict is None: return ReturnValue({'BaseResponse': { 'ErrMsg': 'No friend found', 'Ret': -1001, }}) else: if userName is None: url = '%s/webwxgetheadimg' % self.loginInfo['url'] else: chatroom = self.storageClass.search_chatrooms( userName=chatroomUserName) if chatroomUserName is None: return ReturnValue({'BaseResponse': { 'ErrMsg': 'No chatroom found', 'Ret': -1001, }}) if 'EncryChatRoomId' in chatroom: params['chatroomid'] = chatroom['EncryChatRoomId'] params['chatroomid'] = params.get( 'chatroomid') or chatroom['UserName'] headers = {'User-Agent': config.USER_AGENT} r = self.s.get(url, params=params, stream=True, headers=headers) tempStorage = io.BytesIO() for block in r.iter_content(1024): tempStorage.write(block) if picDir is None: return tempStorage.getvalue() with open(picDir, 'wb') as f: f.write(tempStorage.getvalue()) tempStorage.seek(0) return ReturnValue({'BaseResponse': { 'ErrMsg': 'Successfully downloaded', 'Ret': 0, }, 'PostFix': utils.get_image_postfix(tempStorage.read(20)), }) def create_chatroom(self, memberList, topic=''): url = '%s/webwxcreatechatroom?pass_ticket=%s&r=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket'], int(time.time())) data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'MemberCount': len(memberList.split(',')), 'MemberList': [{'UserName': member} for member in memberList.split(',')], 'Topic': topic, } headers = { 'content-type': 'application/json; charset=UTF-8', 'User-Agent': config.USER_AGENT} r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8', 'ignore')) return ReturnValue(rawResponse=r) def set_chatroom_name(self, chatroomUserName, name): url = '%s/webwxupdatechatroom?fun=modtopic&pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket']) data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'ChatRoomName': chatroomUserName, 'NewTopic': name, } headers = { 'content-type': 'application/json; charset=UTF-8', 'User-Agent': config.USER_AGENT} r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8', 'ignore')) return ReturnValue(rawResponse=r) def delete_member_from_chatroom(self, chatroomUserName, memberList): url = '%s/webwxupdatechatroom?fun=delmember&pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket']) data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'ChatRoomName': chatroomUserName, 'DelMemberList': ','.join([member['UserName'] for member in memberList]), } headers = { 'content-type': 'application/json; charset=UTF-8', 'User-Agent': config.USER_AGENT} r = self.s.post(url, data=json.dumps(data), headers=headers) return ReturnValue(rawResponse=r) def add_member_into_chatroom(self, chatroomUserName, memberList, useInvitation=False): ''' add or invite member into chatroom * there are two ways to get members into chatroom: invite or directly add * but for chatrooms with more than 40 users, you can only use invite * but don't worry we will auto-force userInvitation for you when necessary ''' if not useInvitation: chatroom = self.storageClass.search_chatrooms( userName=chatroomUserName) if not chatroom: chatroom = self.update_chatroom(chatroomUserName) if len(chatroom['MemberList']) > self.loginInfo['InviteStartCount']: useInvitation = True if useInvitation: fun, memberKeyName = 'invitemember', 'InviteMemberList' else: fun, memberKeyName = 'addmember', 'AddMemberList' url = '%s/webwxupdatechatroom?fun=%s&pass_ticket=%s' % ( self.loginInfo['url'], fun, self.loginInfo['pass_ticket']) params = { 'BaseRequest': self.loginInfo['BaseRequest'], 'ChatRoomName': chatroomUserName, memberKeyName: memberList, } headers = { 'content-type': 'application/json; charset=UTF-8', 'User-Agent': config.USER_AGENT} r = self.s.post(url, data=json.dumps(params), headers=headers) return ReturnValue(rawResponse=r)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/components/hotreload.py
Python
import pickle, os import logging import requests from ..config import VERSION from ..returnvalues import ReturnValue from ..storage import templates from .contact import update_local_chatrooms, update_local_friends from .messages import produce_msg logger = logging.getLogger('itchat') def load_hotreload(core): core.dump_login_status = dump_login_status core.load_login_status = load_login_status def dump_login_status(self, fileDir=None): fileDir = fileDir or self.hotReloadDir try: with open(fileDir, 'w') as f: f.write('itchat - DELETE THIS') os.remove(fileDir) except: raise Exception('Incorrect fileDir') status = { 'version' : VERSION, 'loginInfo' : self.loginInfo, 'cookies' : self.s.cookies.get_dict(), 'storage' : self.storageClass.dumps()} with open(fileDir, 'wb') as f: pickle.dump(status, f) logger.debug('Dump login status for hot reload successfully.') def load_login_status(self, fileDir, loginCallback=None, exitCallback=None): try: with open(fileDir, 'rb') as f: j = pickle.load(f) except Exception as e: logger.debug('No such file, loading login status failed.') return ReturnValue({'BaseResponse': { 'ErrMsg': 'No such file, loading login status failed.', 'Ret': -1002, }}) if j.get('version', '') != VERSION: logger.debug(('you have updated itchat from %s to %s, ' + 'so cached status is ignored') % ( j.get('version', 'old version'), VERSION)) return ReturnValue({'BaseResponse': { 'ErrMsg': 'cached status ignored because of version', 'Ret': -1005, }}) self.loginInfo = j['loginInfo'] self.loginInfo['User'] = templates.User(self.loginInfo['User']) self.loginInfo['User'].core = self self.s.cookies = requests.utils.cookiejar_from_dict(j['cookies']) self.storageClass.loads(j['storage']) try: msgList, contactList = self.get_msg() except: msgList = contactList = None if (msgList or contactList) is None: self.logout() load_last_login_status(self.s, j['cookies']) logger.debug('server refused, loading login status failed.') return ReturnValue({'BaseResponse': { 'ErrMsg': 'server refused, loading login status failed.', 'Ret': -1003, }}) else: if contactList: for contact in contactList: if '@@' in contact['UserName']: update_local_chatrooms(self, [contact]) else: update_local_friends(self, [contact]) if msgList: msgList = produce_msg(self, msgList) for msg in msgList: self.msgList.put(msg) self.start_receiving(exitCallback) logger.debug('loading login status succeeded.') if hasattr(loginCallback, '__call__'): loginCallback() return ReturnValue({'BaseResponse': { 'ErrMsg': 'loading login status succeeded.', 'Ret': 0, }}) def load_last_login_status(session, cookiesDict): try: session.cookies = requests.utils.cookiejar_from_dict({ 'webwxuvid': cookiesDict['webwxuvid'], 'webwx_auth_ticket': cookiesDict['webwx_auth_ticket'], 'login_frequency': '2', 'last_wxuin': cookiesDict['wxuin'], 'wxloadtime': cookiesDict['wxloadtime'] + '_expired', 'wxpluginkey': cookiesDict['wxloadtime'], 'wxuin': cookiesDict['wxuin'], 'mm_lang': 'zh_CN', 'MM_WX_NOTIFY_STATE': '1', 'MM_WX_SOUND_STATE': '1', }) except: logger.info('Load status for push login failed, we may have experienced a cookies change.') logger.info('If you are using the newest version of itchat, you may report a bug.')
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/components/login.py
Python
import os import time import re import io import threading import json import xml.dom.minidom import random import traceback import logging try: from httplib import BadStatusLine except ImportError: from http.client import BadStatusLine import requests from pyqrcode import QRCode from .. import config, utils from ..returnvalues import ReturnValue from ..storage.templates import wrap_user_dict from .contact import update_local_chatrooms, update_local_friends from .messages import produce_msg logger = logging.getLogger('itchat') def load_login(core): core.login = login core.get_QRuuid = get_QRuuid core.get_QR = get_QR core.check_login = check_login core.web_init = web_init core.show_mobile_login = show_mobile_login core.start_receiving = start_receiving core.get_msg = get_msg core.logout = logout def login(self, enableCmdQR=False, picDir=None, qrCallback=None, loginCallback=None, exitCallback=None): if self.alive or self.isLogging: logger.warning('itchat has already logged in.') return self.isLogging = True logger.info('Ready to login.') while self.isLogging: uuid = push_login(self) if uuid: qrStorage = io.BytesIO() else: logger.info('Getting uuid of QR code.') while not self.get_QRuuid(): time.sleep(1) logger.info('Downloading QR code.') qrStorage = self.get_QR(enableCmdQR=enableCmdQR, picDir=picDir, qrCallback=qrCallback) # logger.info('Please scan the QR code to log in.') isLoggedIn = False while not isLoggedIn: status = self.check_login() if hasattr(qrCallback, '__call__'): qrCallback(uuid=self.uuid, status=status, qrcode=qrStorage.getvalue()) if status == '200': isLoggedIn = True elif status == '201': if isLoggedIn is not None: logger.info('Please press confirm on your phone.') isLoggedIn = None time.sleep(7) time.sleep(0.5) elif status != '408': break if isLoggedIn: break elif self.isLogging: logger.info('Log in time out, reloading QR code.') else: return # log in process is stopped by user logger.info('Loading the contact, this may take a little while.') self.web_init() self.show_mobile_login() self.get_contact(True) if hasattr(loginCallback, '__call__'): r = loginCallback() else: # utils.clear_screen() if os.path.exists(picDir or config.DEFAULT_QR): os.remove(picDir or config.DEFAULT_QR) logger.info('Login successfully as %s' % self.storageClass.nickName) self.start_receiving(exitCallback) self.isLogging = False def push_login(core): cookiesDict = core.s.cookies.get_dict() if 'wxuin' in cookiesDict: url = '%s/cgi-bin/mmwebwx-bin/webwxpushloginurl?uin=%s' % ( config.BASE_URL, cookiesDict['wxuin']) headers = {'User-Agent': config.USER_AGENT} r = core.s.get(url, headers=headers).json() if 'uuid' in r and r.get('ret') in (0, '0'): core.uuid = r['uuid'] return r['uuid'] return False def get_QRuuid(self): url = '%s/jslogin' % config.BASE_URL params = { 'appid': 'wx782c26e4c19acffb', 'fun': 'new', 'redirect_uri': 'https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?mod=desktop', 'lang': 'zh_CN'} headers = {'User-Agent': config.USER_AGENT} r = self.s.get(url, params=params, headers=headers) regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)";' data = re.search(regx, r.text) if data and data.group(1) == '200': self.uuid = data.group(2) return self.uuid def get_QR(self, uuid=None, enableCmdQR=False, picDir=None, qrCallback=None): uuid = uuid or self.uuid picDir = picDir or config.DEFAULT_QR qrStorage = io.BytesIO() qrCode = QRCode('https://login.weixin.qq.com/l/' + uuid) qrCode.png(qrStorage, scale=10) if hasattr(qrCallback, '__call__'): qrCallback(uuid=uuid, status='0', qrcode=qrStorage.getvalue()) else: with open(picDir, 'wb') as f: f.write(qrStorage.getvalue()) if enableCmdQR: utils.print_cmd_qr(qrCode.text(1), enableCmdQR=enableCmdQR) else: utils.print_qr(picDir) return qrStorage def check_login(self, uuid=None): uuid = uuid or self.uuid url = '%s/cgi-bin/mmwebwx-bin/login' % config.BASE_URL localTime = int(time.time()) params = 'loginicon=true&uuid=%s&tip=1&r=%s&_=%s' % ( uuid, int(-localTime / 1579), localTime) headers = {'User-Agent': config.USER_AGENT} r = self.s.get(url, params=params, headers=headers) regx = r'window.code=(\d+)' data = re.search(regx, r.text) if data and data.group(1) == '200': if process_login_info(self, r.text): return '200' else: return '400' elif data: return data.group(1) else: return '400' def process_login_info(core, loginContent): ''' when finish login (scanning qrcode) * syncUrl and fileUploadingUrl will be fetched * deviceid and msgid will be generated * skey, wxsid, wxuin, pass_ticket will be fetched ''' regx = r'window.redirect_uri="(\S+)";' core.loginInfo['url'] = re.search(regx, loginContent).group(1) headers = {'User-Agent': config.USER_AGENT, 'client-version': config.UOS_PATCH_CLIENT_VERSION, 'extspam': config.UOS_PATCH_EXTSPAM, 'referer': 'https://wx.qq.com/?&lang=zh_CN&target=t' } r = core.s.get(core.loginInfo['url'], headers=headers, allow_redirects=False) core.loginInfo['url'] = core.loginInfo['url'][:core.loginInfo['url'].rfind( '/')] for indexUrl, detailedUrl in ( ("wx2.qq.com", ("file.wx2.qq.com", "webpush.wx2.qq.com")), ("wx8.qq.com", ("file.wx8.qq.com", "webpush.wx8.qq.com")), ("qq.com", ("file.wx.qq.com", "webpush.wx.qq.com")), ("web2.wechat.com", ("file.web2.wechat.com", "webpush.web2.wechat.com")), ("wechat.com", ("file.web.wechat.com", "webpush.web.wechat.com"))): fileUrl, syncUrl = ['https://%s/cgi-bin/mmwebwx-bin' % url for url in detailedUrl] if indexUrl in core.loginInfo['url']: core.loginInfo['fileUrl'], core.loginInfo['syncUrl'] = \ fileUrl, syncUrl break else: core.loginInfo['fileUrl'] = core.loginInfo['syncUrl'] = core.loginInfo['url'] core.loginInfo['deviceid'] = 'e' + repr(random.random())[2:17] core.loginInfo['logintime'] = int(time.time() * 1e3) core.loginInfo['BaseRequest'] = {} cookies = core.s.cookies.get_dict() res = re.findall('<skey>(.*?)</skey>', r.text, re.S) skey = res[0] if res else None res = re.findall( '<pass_ticket>(.*?)</pass_ticket>', r.text, re.S) pass_ticket = res[0] if res else None if skey is not None: core.loginInfo['skey'] = core.loginInfo['BaseRequest']['Skey'] = skey core.loginInfo['wxsid'] = core.loginInfo['BaseRequest']['Sid'] = cookies["wxsid"] core.loginInfo['wxuin'] = core.loginInfo['BaseRequest']['Uin'] = cookies["wxuin"] if pass_ticket is not None: core.loginInfo['pass_ticket'] = pass_ticket # A question : why pass_ticket == DeviceID ? # deviceID is only a randomly generated number # UOS PATCH By luvletter2333, Sun Feb 28 10:00 PM # for node in xml.dom.minidom.parseString(r.text).documentElement.childNodes: # if node.nodeName == 'skey': # core.loginInfo['skey'] = core.loginInfo['BaseRequest']['Skey'] = node.childNodes[0].data # elif node.nodeName == 'wxsid': # core.loginInfo['wxsid'] = core.loginInfo['BaseRequest']['Sid'] = node.childNodes[0].data # elif node.nodeName == 'wxuin': # core.loginInfo['wxuin'] = core.loginInfo['BaseRequest']['Uin'] = node.childNodes[0].data # elif node.nodeName == 'pass_ticket': # core.loginInfo['pass_ticket'] = core.loginInfo['BaseRequest']['DeviceID'] = node.childNodes[0].data if not all([key in core.loginInfo for key in ('skey', 'wxsid', 'wxuin', 'pass_ticket')]): logger.error( 'Your wechat account may be LIMITED to log in WEB wechat, error info:\n%s' % r.text) core.isLogging = False return False return True def web_init(self): url = '%s/webwxinit' % self.loginInfo['url'] params = { 'r': int(-time.time() / 1579), 'pass_ticket': self.loginInfo['pass_ticket'], } data = {'BaseRequest': self.loginInfo['BaseRequest'], } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent': config.USER_AGENT, } r = self.s.post(url, params=params, data=json.dumps(data), headers=headers) dic = json.loads(r.content.decode('utf-8', 'replace')) # deal with login info utils.emoji_formatter(dic['User'], 'NickName') self.loginInfo['InviteStartCount'] = int(dic['InviteStartCount']) self.loginInfo['User'] = wrap_user_dict( utils.struct_friend_info(dic['User'])) self.memberList.append(self.loginInfo['User']) self.loginInfo['SyncKey'] = dic['SyncKey'] self.loginInfo['synckey'] = '|'.join(['%s_%s' % (item['Key'], item['Val']) for item in dic['SyncKey']['List']]) self.storageClass.userName = dic['User']['UserName'] self.storageClass.nickName = dic['User']['NickName'] # deal with contact list returned when init contactList = dic.get('ContactList', []) chatroomList, otherList = [], [] for m in contactList: if m['Sex'] != 0: otherList.append(m) elif '@@' in m['UserName']: m['MemberList'] = [] # don't let dirty info pollute the list chatroomList.append(m) elif '@' in m['UserName']: # mp will be dealt in update_local_friends as well otherList.append(m) if chatroomList: update_local_chatrooms(self, chatroomList) if otherList: update_local_friends(self, otherList) return dic def show_mobile_login(self): url = '%s/webwxstatusnotify?lang=zh_CN&pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket']) data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Code': 3, 'FromUserName': self.storageClass.userName, 'ToUserName': self.storageClass.userName, 'ClientMsgId': int(time.time()), } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent': config.USER_AGENT, } r = self.s.post(url, data=json.dumps(data), headers=headers) return ReturnValue(rawResponse=r) def start_receiving(self, exitCallback=None, getReceivingFnOnly=False): self.alive = True def maintain_loop(): retryCount = 0 while self.alive: try: i = sync_check(self) if i is None: self.alive = False elif i == '0': pass else: msgList, contactList = self.get_msg() if msgList: msgList = produce_msg(self, msgList) for msg in msgList: self.msgList.put(msg) if contactList: chatroomList, otherList = [], [] for contact in contactList: if '@@' in contact['UserName']: chatroomList.append(contact) else: otherList.append(contact) chatroomMsg = update_local_chatrooms( self, chatroomList) chatroomMsg['User'] = self.loginInfo['User'] self.msgList.put(chatroomMsg) update_local_friends(self, otherList) retryCount = 0 except requests.exceptions.ReadTimeout: pass except: retryCount += 1 logger.error(traceback.format_exc()) if self.receivingRetryCount < retryCount: logger.error("Having tried %s times, but still failed. " % ( retryCount) + "Stop trying...") self.alive = False else: time.sleep(1) self.logout() if hasattr(exitCallback, '__call__'): exitCallback() else: logger.info('LOG OUT!') if getReceivingFnOnly: return maintain_loop else: maintainThread = threading.Thread(target=maintain_loop) maintainThread.setDaemon(True) maintainThread.start() def sync_check(self): url = '%s/synccheck' % self.loginInfo.get('syncUrl', self.loginInfo['url']) params = { 'r': int(time.time() * 1000), 'skey': self.loginInfo['skey'], 'sid': self.loginInfo['wxsid'], 'uin': self.loginInfo['wxuin'], 'deviceid': self.loginInfo['deviceid'], 'synckey': self.loginInfo['synckey'], '_': self.loginInfo['logintime'], } headers = {'User-Agent': config.USER_AGENT} self.loginInfo['logintime'] += 1 try: r = self.s.get(url, params=params, headers=headers, timeout=config.TIMEOUT) except requests.exceptions.ConnectionError as e: try: if not isinstance(e.args[0].args[1], BadStatusLine): raise # will return a package with status '0 -' # and value like: # 6f:00:8a:9c:09:74:e4:d8:e0:14:bf:96:3a:56:a0:64:1b:a4:25:5d:12:f4:31:a5:30:f1:c6:48:5f:c3:75:6a:99:93 # seems like status of typing, but before I make further achievement code will remain like this return '2' except: raise r.raise_for_status() regx = r'window.synccheck={retcode:"(\d+)",selector:"(\d+)"}' pm = re.search(regx, r.text) if pm is None or pm.group(1) != '0': logger.error('Unexpected sync check result: %s' % r.text) return None return pm.group(2) def get_msg(self): self.loginInfo['deviceid'] = 'e' + repr(random.random())[2:17] url = '%s/webwxsync?sid=%s&skey=%s&pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['wxsid'], self.loginInfo['skey'], self.loginInfo['pass_ticket']) data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'SyncKey': self.loginInfo['SyncKey'], 'rr': ~int(time.time()), } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent': config.USER_AGENT} r = self.s.post(url, data=json.dumps(data), headers=headers, timeout=config.TIMEOUT) dic = json.loads(r.content.decode('utf-8', 'replace')) if dic['BaseResponse']['Ret'] != 0: return None, None self.loginInfo['SyncKey'] = dic['SyncKey'] self.loginInfo['synckey'] = '|'.join(['%s_%s' % (item['Key'], item['Val']) for item in dic['SyncCheckKey']['List']]) return dic['AddMsgList'], dic['ModContactList'] def logout(self): if self.alive: url = '%s/webwxlogout' % self.loginInfo['url'] params = { 'redirect': 1, 'type': 1, 'skey': self.loginInfo['skey'], } headers = {'User-Agent': config.USER_AGENT} self.s.get(url, params=params, headers=headers) self.alive = False self.isLogging = False self.s.cookies.clear() del self.chatroomList[:] del self.memberList[:] del self.mpList[:] return ReturnValue({'BaseResponse': { 'ErrMsg': 'logout successfully.', 'Ret': 0, }})
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/components/messages.py
Python
import os, time, re, io import json import mimetypes, hashlib import logging from collections import OrderedDict import requests from .. import config, utils from ..returnvalues import ReturnValue from ..storage import templates from .contact import update_local_uin logger = logging.getLogger('itchat') def load_messages(core): core.send_raw_msg = send_raw_msg core.send_msg = send_msg core.upload_file = upload_file core.send_file = send_file core.send_image = send_image core.send_video = send_video core.send = send core.revoke = revoke def get_download_fn(core, url, msgId): def download_fn(downloadDir=None): params = { 'msgid': msgId, 'skey': core.loginInfo['skey'],} headers = { 'User-Agent' : config.USER_AGENT } r = core.s.get(url, params=params, stream=True, headers = headers) tempStorage = io.BytesIO() for block in r.iter_content(1024): tempStorage.write(block) if downloadDir is None: return tempStorage.getvalue() with open(downloadDir, 'wb') as f: f.write(tempStorage.getvalue()) tempStorage.seek(0) return ReturnValue({'BaseResponse': { 'ErrMsg': 'Successfully downloaded', 'Ret': 0, }, 'PostFix': utils.get_image_postfix(tempStorage.read(20)), }) return download_fn def produce_msg(core, msgList): ''' for messages types * 40 msg, 43 videochat, 50 VOIPMSG, 52 voipnotifymsg * 53 webwxvoipnotifymsg, 9999 sysnotice ''' rl = [] srl = [40, 43, 50, 52, 53, 9999] for m in msgList: # get actual opposite if m['FromUserName'] == core.storageClass.userName: actualOpposite = m['ToUserName'] else: actualOpposite = m['FromUserName'] # produce basic message if '@@' in m['FromUserName'] or '@@' in m['ToUserName']: produce_group_chat(core, m) else: utils.msg_formatter(m, 'Content') # set user of msg if '@@' in actualOpposite: m['User'] = core.search_chatrooms(userName=actualOpposite) or \ templates.Chatroom({'UserName': actualOpposite}) # we don't need to update chatroom here because we have # updated once when producing basic message elif actualOpposite in ('filehelper', 'fmessage'): m['User'] = templates.User({'UserName': actualOpposite}) else: m['User'] = core.search_mps(userName=actualOpposite) or \ core.search_friends(userName=actualOpposite) or \ templates.User(userName=actualOpposite) # by default we think there may be a user missing not a mp m['User'].core = core if m['MsgType'] == 1: # words if m['Url']: regx = r'(.+?\(.+?\))' data = re.search(regx, m['Content']) data = 'Map' if data is None else data.group(1) msg = { 'Type': 'Map', 'Text': data,} else: msg = { 'Type': 'Text', 'Text': m['Content'],} elif m['MsgType'] == 3 or m['MsgType'] == 47: # picture download_fn = get_download_fn(core, '%s/webwxgetmsgimg' % core.loginInfo['url'], m['NewMsgId']) msg = { 'Type' : 'Picture', 'FileName' : '%s.%s' % (time.strftime('%y%m%d-%H%M%S', time.localtime()), 'png' if m['MsgType'] == 3 else 'gif'), 'Text' : download_fn, } elif m['MsgType'] == 34: # voice download_fn = get_download_fn(core, '%s/webwxgetvoice' % core.loginInfo['url'], m['NewMsgId']) msg = { 'Type': 'Recording', 'FileName' : '%s.mp3' % time.strftime('%y%m%d-%H%M%S', time.localtime()), 'Text': download_fn,} elif m['MsgType'] == 37: # friends m['User']['UserName'] = m['RecommendInfo']['UserName'] msg = { 'Type': 'Friends', 'Text': { 'status' : m['Status'], 'userName' : m['RecommendInfo']['UserName'], 'verifyContent' : m['Ticket'], 'autoUpdate' : m['RecommendInfo'], }, } m['User'].verifyDict = msg['Text'] elif m['MsgType'] == 42: # name card msg = { 'Type': 'Card', 'Text': m['RecommendInfo'], } elif m['MsgType'] in (43, 62): # tiny video msgId = m['MsgId'] def download_video(videoDir=None): url = '%s/webwxgetvideo' % core.loginInfo['url'] params = { 'msgid': msgId, 'skey': core.loginInfo['skey'],} headers = {'Range': 'bytes=0-', 'User-Agent' : config.USER_AGENT } r = core.s.get(url, params=params, headers=headers, stream=True) tempStorage = io.BytesIO() for block in r.iter_content(1024): tempStorage.write(block) if videoDir is None: return tempStorage.getvalue() with open(videoDir, 'wb') as f: f.write(tempStorage.getvalue()) return ReturnValue({'BaseResponse': { 'ErrMsg': 'Successfully downloaded', 'Ret': 0, }}) msg = { 'Type': 'Video', 'FileName' : '%s.mp4' % time.strftime('%y%m%d-%H%M%S', time.localtime()), 'Text': download_video, } elif m['MsgType'] == 49: # sharing if m['AppMsgType'] == 0: # chat history msg = { 'Type': 'Note', 'Text': m['Content'], } elif m['AppMsgType'] == 6: rawMsg = m cookiesList = {name:data for name,data in core.s.cookies.items()} def download_atta(attaDir=None): url = core.loginInfo['fileUrl'] + '/webwxgetmedia' params = { 'sender': rawMsg['FromUserName'], 'mediaid': rawMsg['MediaId'], 'filename': rawMsg['FileName'], 'fromuser': core.loginInfo['wxuin'], 'pass_ticket': 'undefined', 'webwx_data_ticket': cookiesList['webwx_data_ticket'],} headers = { 'User-Agent' : config.USER_AGENT } r = core.s.get(url, params=params, stream=True, headers=headers) tempStorage = io.BytesIO() for block in r.iter_content(1024): tempStorage.write(block) if attaDir is None: return tempStorage.getvalue() with open(attaDir, 'wb') as f: f.write(tempStorage.getvalue()) return ReturnValue({'BaseResponse': { 'ErrMsg': 'Successfully downloaded', 'Ret': 0, }}) msg = { 'Type': 'Attachment', 'Text': download_atta, } elif m['AppMsgType'] == 8: download_fn = get_download_fn(core, '%s/webwxgetmsgimg' % core.loginInfo['url'], m['NewMsgId']) msg = { 'Type' : 'Picture', 'FileName' : '%s.gif' % ( time.strftime('%y%m%d-%H%M%S', time.localtime())), 'Text' : download_fn, } elif m['AppMsgType'] == 17: msg = { 'Type': 'Note', 'Text': m['FileName'], } elif m['AppMsgType'] == 2000: regx = r'\[CDATA\[(.+?)\][\s\S]+?\[CDATA\[(.+?)\]' data = re.search(regx, m['Content']) if data: data = data.group(2).split(u'\u3002')[0] else: data = 'You may found detailed info in Content key.' msg = { 'Type': 'Note', 'Text': data, } else: msg = { 'Type': 'Sharing', 'Text': m['FileName'], } elif m['MsgType'] == 51: # phone init msg = update_local_uin(core, m) elif m['MsgType'] == 10000: msg = { 'Type': 'Note', 'Text': m['Content'],} elif m['MsgType'] == 10002: regx = r'\[CDATA\[(.+?)\]\]' data = re.search(regx, m['Content']) data = 'System message' if data is None else data.group(1).replace('\\', '') msg = { 'Type': 'Note', 'Text': data, } elif m['MsgType'] in srl: msg = { 'Type': 'Useless', 'Text': 'UselessMsg', } else: logger.debug('Useless message received: %s\n%s' % (m['MsgType'], str(m))) msg = { 'Type': 'Useless', 'Text': 'UselessMsg', } m = dict(m, **msg) rl.append(m) return rl def produce_group_chat(core, msg): r = re.match('(@[0-9a-z]*?):<br/>(.*)$', msg['Content']) if r: actualUserName, content = r.groups() chatroomUserName = msg['FromUserName'] elif msg['FromUserName'] == core.storageClass.userName: actualUserName = core.storageClass.userName content = msg['Content'] chatroomUserName = msg['ToUserName'] else: msg['ActualUserName'] = core.storageClass.userName msg['ActualNickName'] = core.storageClass.nickName msg['IsAt'] = False utils.msg_formatter(msg, 'Content') return chatroom = core.storageClass.search_chatrooms(userName=chatroomUserName) member = utils.search_dict_list((chatroom or {}).get( 'MemberList') or [], 'UserName', actualUserName) if member is None: chatroom = core.update_chatroom(chatroomUserName) member = utils.search_dict_list((chatroom or {}).get( 'MemberList') or [], 'UserName', actualUserName) if member is None: logger.debug('chatroom member fetch failed with %s' % actualUserName) msg['ActualNickName'] = '' msg['IsAt'] = False else: msg['ActualNickName'] = member.get('DisplayName', '') or member['NickName'] atFlag = '@' + (chatroom['Self'].get('DisplayName', '') or core.storageClass.nickName) msg['IsAt'] = ( (atFlag + (u'\u2005' if u'\u2005' in msg['Content'] else ' ')) in msg['Content'] or msg['Content'].endswith(atFlag)) msg['ActualUserName'] = actualUserName msg['Content'] = content utils.msg_formatter(msg, 'Content') def send_raw_msg(self, msgType, content, toUserName): url = '%s/webwxsendmsg' % self.loginInfo['url'] data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Msg': { 'Type': msgType, 'Content': content, 'FromUserName': self.storageClass.userName, 'ToUserName': (toUserName if toUserName else self.storageClass.userName), 'LocalID': int(time.time() * 1e4), 'ClientMsgId': int(time.time() * 1e4), }, 'Scene': 0, } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8')) return ReturnValue(rawResponse=r) def send_msg(self, msg='Test Message', toUserName=None): logger.debug('Request to send a text message to %s: %s' % (toUserName, msg)) r = self.send_raw_msg(1, msg, toUserName) return r def _prepare_file(fileDir, file_=None): fileDict = {} if file_: if hasattr(file_, 'read'): file_ = file_.read() else: return ReturnValue({'BaseResponse': { 'ErrMsg': 'file_ param should be opened file', 'Ret': -1005, }}) else: if not utils.check_file(fileDir): return ReturnValue({'BaseResponse': { 'ErrMsg': 'No file found in specific dir', 'Ret': -1002, }}) with open(fileDir, 'rb') as f: file_ = f.read() fileDict['fileSize'] = len(file_) fileDict['fileMd5'] = hashlib.md5(file_).hexdigest() fileDict['file_'] = io.BytesIO(file_) return fileDict def upload_file(self, fileDir, isPicture=False, isVideo=False, toUserName='filehelper', file_=None, preparedFile=None): logger.debug('Request to upload a %s: %s' % ( 'picture' if isPicture else 'video' if isVideo else 'file', fileDir)) if not preparedFile: preparedFile = _prepare_file(fileDir, file_) if not preparedFile: return preparedFile fileSize, fileMd5, file_ = \ preparedFile['fileSize'], preparedFile['fileMd5'], preparedFile['file_'] fileSymbol = 'pic' if isPicture else 'video' if isVideo else'doc' chunks = int((fileSize - 1) / 524288) + 1 clientMediaId = int(time.time() * 1e4) uploadMediaRequest = json.dumps(OrderedDict([ ('UploadType', 2), ('BaseRequest', self.loginInfo['BaseRequest']), ('ClientMediaId', clientMediaId), ('TotalLen', fileSize), ('StartPos', 0), ('DataLen', fileSize), ('MediaType', 4), ('FromUserName', self.storageClass.userName), ('ToUserName', toUserName), ('FileMd5', fileMd5)] ), separators = (',', ':')) r = {'BaseResponse': {'Ret': -1005, 'ErrMsg': 'Empty file detected'}} for chunk in range(chunks): r = upload_chunk_file(self, fileDir, fileSymbol, fileSize, file_, chunk, chunks, uploadMediaRequest) file_.close() if isinstance(r, dict): return ReturnValue(r) return ReturnValue(rawResponse=r) def upload_chunk_file(core, fileDir, fileSymbol, fileSize, file_, chunk, chunks, uploadMediaRequest): url = core.loginInfo.get('fileUrl', core.loginInfo['url']) + \ '/webwxuploadmedia?f=json' # save it on server cookiesList = {name:data for name,data in core.s.cookies.items()} fileType = mimetypes.guess_type(fileDir)[0] or 'application/octet-stream' fileName = utils.quote(os.path.basename(fileDir)) files = OrderedDict([ ('id', (None, 'WU_FILE_0')), ('name', (None, fileName)), ('type', (None, fileType)), ('lastModifiedDate', (None, time.strftime('%a %b %d %Y %H:%M:%S GMT+0800 (CST)'))), ('size', (None, str(fileSize))), ('chunks', (None, None)), ('chunk', (None, None)), ('mediatype', (None, fileSymbol)), ('uploadmediarequest', (None, uploadMediaRequest)), ('webwx_data_ticket', (None, cookiesList['webwx_data_ticket'])), ('pass_ticket', (None, core.loginInfo['pass_ticket'])), ('filename' , (fileName, file_.read(524288), 'application/octet-stream'))]) if chunks == 1: del files['chunk']; del files['chunks'] else: files['chunk'], files['chunks'] = (None, str(chunk)), (None, str(chunks)) headers = { 'User-Agent' : config.USER_AGENT } return core.s.post(url, files=files, headers=headers, timeout=config.TIMEOUT) def send_file(self, fileDir, toUserName=None, mediaId=None, file_=None): logger.debug('Request to send a file(mediaId: %s) to %s: %s' % ( mediaId, toUserName, fileDir)) if hasattr(fileDir, 'read'): return ReturnValue({'BaseResponse': { 'ErrMsg': 'fileDir param should not be an opened file in send_file', 'Ret': -1005, }}) if toUserName is None: toUserName = self.storageClass.userName preparedFile = _prepare_file(fileDir, file_) if not preparedFile: return preparedFile fileSize = preparedFile['fileSize'] if mediaId is None: r = self.upload_file(fileDir, preparedFile=preparedFile) if r: mediaId = r['MediaId'] else: return r url = '%s/webwxsendappmsg?fun=async&f=json' % self.loginInfo['url'] data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Msg': { 'Type': 6, 'Content': ("<appmsg appid='wxeb7ec651dd0aefa9' sdkver=''><title>%s</title>" % os.path.basename(fileDir) + "<des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl>" + "<appattach><totallen>%s</totallen><attachid>%s</attachid>" % (str(fileSize), mediaId) + "<fileext>%s</fileext></appattach><extinfo></extinfo></appmsg>" % os.path.splitext(fileDir)[1].replace('.','')), 'FromUserName': self.storageClass.userName, 'ToUserName': toUserName, 'LocalID': int(time.time() * 1e4), 'ClientMsgId': int(time.time() * 1e4), }, 'Scene': 0, } headers = { 'User-Agent': config.USER_AGENT, 'Content-Type': 'application/json;charset=UTF-8', } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8')) return ReturnValue(rawResponse=r) def send_image(self, fileDir=None, toUserName=None, mediaId=None, file_=None): logger.debug('Request to send a image(mediaId: %s) to %s: %s' % ( mediaId, toUserName, fileDir)) if fileDir or file_: if hasattr(fileDir, 'read'): file_, fileDir = fileDir, None if fileDir is None: fileDir = 'tmp.jpg' # specific fileDir to send gifs else: return ReturnValue({'BaseResponse': { 'ErrMsg': 'Either fileDir or file_ should be specific', 'Ret': -1005, }}) if toUserName is None: toUserName = self.storageClass.userName if mediaId is None: r = self.upload_file(fileDir, isPicture=not fileDir[-4:] == '.gif', file_=file_) if r: mediaId = r['MediaId'] else: return r url = '%s/webwxsendmsgimg?fun=async&f=json' % self.loginInfo['url'] data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Msg': { 'Type': 3, 'MediaId': mediaId, 'FromUserName': self.storageClass.userName, 'ToUserName': toUserName, 'LocalID': int(time.time() * 1e4), 'ClientMsgId': int(time.time() * 1e4), }, 'Scene': 0, } if fileDir[-4:] == '.gif': url = '%s/webwxsendemoticon?fun=sys' % self.loginInfo['url'] data['Msg']['Type'] = 47 data['Msg']['EmojiFlag'] = 2 headers = { 'User-Agent': config.USER_AGENT, 'Content-Type': 'application/json;charset=UTF-8', } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8')) return ReturnValue(rawResponse=r) def send_video(self, fileDir=None, toUserName=None, mediaId=None, file_=None): logger.debug('Request to send a video(mediaId: %s) to %s: %s' % ( mediaId, toUserName, fileDir)) if fileDir or file_: if hasattr(fileDir, 'read'): file_, fileDir = fileDir, None if fileDir is None: fileDir = 'tmp.mp4' # specific fileDir to send other formats else: return ReturnValue({'BaseResponse': { 'ErrMsg': 'Either fileDir or file_ should be specific', 'Ret': -1005, }}) if toUserName is None: toUserName = self.storageClass.userName if mediaId is None: r = self.upload_file(fileDir, isVideo=True, file_=file_) if r: mediaId = r['MediaId'] else: return r url = '%s/webwxsendvideomsg?fun=async&f=json&pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket']) data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Msg': { 'Type' : 43, 'MediaId' : mediaId, 'FromUserName' : self.storageClass.userName, 'ToUserName' : toUserName, 'LocalID' : int(time.time() * 1e4), 'ClientMsgId' : int(time.time() * 1e4), }, 'Scene': 0, } headers = { 'User-Agent' : config.USER_AGENT, 'Content-Type': 'application/json;charset=UTF-8', } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8')) return ReturnValue(rawResponse=r) def send(self, msg, toUserName=None, mediaId=None): if not msg: r = ReturnValue({'BaseResponse': { 'ErrMsg': 'No message.', 'Ret': -1005, }}) elif msg[:5] == '@fil@': if mediaId is None: r = self.send_file(msg[5:], toUserName) else: r = self.send_file(msg[5:], toUserName, mediaId) elif msg[:5] == '@img@': if mediaId is None: r = self.send_image(msg[5:], toUserName) else: r = self.send_image(msg[5:], toUserName, mediaId) elif msg[:5] == '@msg@': r = self.send_msg(msg[5:], toUserName) elif msg[:5] == '@vid@': if mediaId is None: r = self.send_video(msg[5:], toUserName) else: r = self.send_video(msg[5:], toUserName, mediaId) else: r = self.send_msg(msg, toUserName) return r def revoke(self, msgId, toUserName, localId=None): url = '%s/webwxrevokemsg' % self.loginInfo['url'] data = { 'BaseRequest': self.loginInfo['BaseRequest'], "ClientMsgId": localId or str(time.time() * 1e3), "SvrMsgId": msgId, "ToUserName": toUserName} headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8')) return ReturnValue(rawResponse=r)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/components/register.py
Python
import logging, traceback, sys, threading try: import Queue except ImportError: import queue as Queue from ..log import set_logging from ..utils import test_connect from ..storage import templates logger = logging.getLogger('itchat') def load_register(core): core.auto_login = auto_login core.configured_reply = configured_reply core.msg_register = msg_register core.run = run def auto_login(self, hotReload=False, statusStorageDir='itchat.pkl', enableCmdQR=False, picDir=None, qrCallback=None, loginCallback=None, exitCallback=None): if not test_connect(): logger.info("You can't get access to internet or wechat domain, so exit.") sys.exit() self.useHotReload = hotReload self.hotReloadDir = statusStorageDir if hotReload: rval=self.load_login_status(statusStorageDir, loginCallback=loginCallback, exitCallback=exitCallback) if rval: return logger.error('Hot reload failed, logging in normally, error={}'.format(rval)) self.logout() self.login(enableCmdQR=enableCmdQR, picDir=picDir, qrCallback=qrCallback, loginCallback=loginCallback, exitCallback=exitCallback) self.dump_login_status(statusStorageDir) else: self.login(enableCmdQR=enableCmdQR, picDir=picDir, qrCallback=qrCallback, loginCallback=loginCallback, exitCallback=exitCallback) def configured_reply(self): ''' determine the type of message and reply if its method is defined however, I use a strange way to determine whether a msg is from massive platform I haven't found a better solution here The main problem I'm worrying about is the mismatching of new friends added on phone If you have any good idea, pleeeease report an issue. I will be more than grateful. ''' try: msg = self.msgList.get(timeout=1) except Queue.Empty: pass else: if isinstance(msg['User'], templates.User): replyFn = self.functionDict['FriendChat'].get(msg['Type']) elif isinstance(msg['User'], templates.MassivePlatform): replyFn = self.functionDict['MpChat'].get(msg['Type']) elif isinstance(msg['User'], templates.Chatroom): replyFn = self.functionDict['GroupChat'].get(msg['Type']) if replyFn is None: r = None else: try: r = replyFn(msg) if r is not None: self.send(r, msg.get('FromUserName')) except: logger.warning(traceback.format_exc()) def msg_register(self, msgType, isFriendChat=False, isGroupChat=False, isMpChat=False): ''' a decorator constructor return a specific decorator based on information given ''' if not (isinstance(msgType, list) or isinstance(msgType, tuple)): msgType = [msgType] def _msg_register(fn): for _msgType in msgType: if isFriendChat: self.functionDict['FriendChat'][_msgType] = fn if isGroupChat: self.functionDict['GroupChat'][_msgType] = fn if isMpChat: self.functionDict['MpChat'][_msgType] = fn if not any((isFriendChat, isGroupChat, isMpChat)): self.functionDict['FriendChat'][_msgType] = fn return fn return _msg_register def run(self, debug=False, blockThread=True): logger.info('Start auto replying.') if debug: set_logging(loggingLevel=logging.DEBUG) def reply_fn(): try: while self.alive: self.configured_reply() except KeyboardInterrupt: if self.useHotReload: self.dump_login_status() self.alive = False logger.debug('itchat received an ^C and exit.') logger.info('Bye~') if blockThread: reply_fn() else: replyThread = threading.Thread(target=reply_fn) replyThread.setDaemon(True) replyThread.start()
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/config.py
Python
import os, platform VERSION = '1.5.0.dev' # use this envrionment to initialize the async & sync componment ASYNC_COMPONENTS = os.environ.get('ITCHAT_UOS_ASYNC', False) BASE_URL = 'https://login.weixin.qq.com' OS = platform.system() # Windows, Linux, Darwin DIR = os.getcwd() DEFAULT_QR = 'QR.png' TIMEOUT = (10, 60) USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36' UOS_PATCH_CLIENT_VERSION = '2.0.0' UOS_PATCH_EXTSPAM = 'Go8FCIkFEokFCggwMDAwMDAwMRAGGvAESySibk50w5Wb3uTl2c2h64jVVrV7gNs06GFlWplHQbY/5FfiO++1yH4ykCyNPWKXmco+wfQzK5R98D3so7rJ5LmGFvBLjGceleySrc3SOf2Pc1gVehzJgODeS0lDL3/I/0S2SSE98YgKleq6Uqx6ndTy9yaL9qFxJL7eiA/R3SEfTaW1SBoSITIu+EEkXff+Pv8NHOk7N57rcGk1w0ZzRrQDkXTOXFN2iHYIzAAZPIOY45Lsh+A4slpgnDiaOvRtlQYCt97nmPLuTipOJ8Qc5pM7ZsOsAPPrCQL7nK0I7aPrFDF0q4ziUUKettzW8MrAaiVfmbD1/VkmLNVqqZVvBCtRblXb5FHmtS8FxnqCzYP4WFvz3T0TcrOqwLX1M/DQvcHaGGw0B0y4bZMs7lVScGBFxMj3vbFi2SRKbKhaitxHfYHAOAa0X7/MSS0RNAjdwoyGHeOepXOKY+h3iHeqCvgOH6LOifdHf/1aaZNwSkGotYnYScW8Yx63LnSwba7+hESrtPa/huRmB9KWvMCKbDThL/nne14hnL277EDCSocPu3rOSYjuB9gKSOdVmWsj9Dxb/iZIe+S6AiG29Esm+/eUacSba0k8wn5HhHg9d4tIcixrxveflc8vi2/wNQGVFNsGO6tB5WF0xf/plngOvQ1/ivGV/C1Qpdhzznh0ExAVJ6dwzNg7qIEBaw+BzTJTUuRcPk92Sn6QDn2Pu3mpONaEumacjW4w6ipPnPw+g2TfywJjeEcpSZaP4Q3YV5HG8D6UjWA4GSkBKculWpdCMadx0usMomsSS/74QgpYqcPkmamB4nVv1JxczYITIqItIKjD35IGKAUwAA=='
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/content.py
Python
TEXT = 'Text' MAP = 'Map' CARD = 'Card' NOTE = 'Note' SHARING = 'Sharing' PICTURE = 'Picture' RECORDING = VOICE = 'Recording' ATTACHMENT = 'Attachment' VIDEO = 'Video' FRIENDS = 'Friends' SYSTEM = 'System' INCOME_MSG = [TEXT, MAP, CARD, NOTE, SHARING, PICTURE, RECORDING, VOICE, ATTACHMENT, VIDEO, FRIENDS, SYSTEM]
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/core.py
Python
import requests from . import storage class Core(object): def __init__(self): ''' init is the only method defined in core.py alive is value showing whether core is running - you should call logout method to change it - after logout, a core object can login again storageClass only uses basic python types - so for advanced uses, inherit it yourself receivingRetryCount is for receiving loop retry - it's 5 now, but actually even 1 is enough - failing is failing ''' self.alive, self.isLogging = False, False self.storageClass = storage.Storage(self) self.memberList = self.storageClass.memberList self.mpList = self.storageClass.mpList self.chatroomList = self.storageClass.chatroomList self.msgList = self.storageClass.msgList self.loginInfo = {} self.s = requests.Session() self.uuid = None self.functionDict = {'FriendChat': {}, 'GroupChat': {}, 'MpChat': {}} self.useHotReload, self.hotReloadDir = False, 'itchat.pkl' self.receivingRetryCount = 5 def login(self, enableCmdQR=False, picDir=None, qrCallback=None, loginCallback=None, exitCallback=None): ''' log in like web wechat does for log in - a QR code will be downloaded and opened - then scanning status is logged, it paused for you confirm - finally it logged in and show your nickName for options - enableCmdQR: show qrcode in command line - integers can be used to fit strange char length - picDir: place for storing qrcode - qrCallback: method that should accept uuid, status, qrcode - loginCallback: callback after successfully logged in - if not set, screen is cleared and qrcode is deleted - exitCallback: callback after logged out - it contains calling of logout for usage ..code::python import itchat itchat.login() it is defined in components/login.py and of course every single move in login can be called outside - you may scan source code to see how - and modified according to your own demand ''' raise NotImplementedError() def get_QRuuid(self): ''' get uuid for qrcode uuid is the symbol of qrcode - for logging in, you need to get a uuid first - for downloading qrcode, you need to pass uuid to it - for checking login status, uuid is also required if uuid has timed out, just get another it is defined in components/login.py ''' raise NotImplementedError() def get_QR(self, uuid=None, enableCmdQR=False, picDir=None, qrCallback=None): ''' download and show qrcode for options - uuid: if uuid is not set, latest uuid you fetched will be used - enableCmdQR: show qrcode in cmd - picDir: where to store qrcode - qrCallback: method that should accept uuid, status, qrcode it is defined in components/login.py ''' raise NotImplementedError() def check_login(self, uuid=None): ''' check login status for options: - uuid: if uuid is not set, latest uuid you fetched will be used for return values: - a string will be returned - for meaning of return values - 200: log in successfully - 201: waiting for press confirm - 408: uuid timed out - 0 : unknown error for processing: - syncUrl and fileUrl is set - BaseRequest is set blocks until reaches any of above status it is defined in components/login.py ''' raise NotImplementedError() def web_init(self): ''' get info necessary for initializing for processing: - own account info is set - inviteStartCount is set - syncKey is set - part of contact is fetched it is defined in components/login.py ''' raise NotImplementedError() def show_mobile_login(self): ''' show web wechat login sign the sign is on the top of mobile phone wechat sign will be added after sometime even without calling this function it is defined in components/login.py ''' raise NotImplementedError() def start_receiving(self, exitCallback=None, getReceivingFnOnly=False): ''' open a thread for heart loop and receiving messages for options: - exitCallback: callback after logged out - it contains calling of logout - getReceivingFnOnly: if True thread will not be created and started. Instead, receive fn will be returned. for processing: - messages: msgs are formatted and passed on to registered fns - contact : chatrooms are updated when related info is received it is defined in components/login.py ''' raise NotImplementedError() def get_msg(self): ''' fetch messages for fetching - method blocks for sometime until - new messages are to be received - or anytime they like - synckey is updated with returned synccheckkey it is defined in components/login.py ''' raise NotImplementedError() def logout(self): ''' logout if core is now alive logout will tell wechat backstage to logout and core gets ready for another login it is defined in components/login.py ''' raise NotImplementedError() def update_chatroom(self, userName, detailedMember=False): ''' update chatroom for chatroom contact - a chatroom contact need updating to be detailed - detailed means members, encryid, etc - auto updating of heart loop is a more detailed updating - member uin will also be filled - once called, updated info will be stored for options - userName: 'UserName' key of chatroom or a list of it - detailedMember: whether to get members of contact it is defined in components/contact.py ''' raise NotImplementedError() def update_friend(self, userName): ''' update chatroom for friend contact - once called, updated info will be stored for options - userName: 'UserName' key of a friend or a list of it it is defined in components/contact.py ''' raise NotImplementedError() def get_contact(self, update=False): ''' fetch part of contact for part - all the massive platforms and friends are fetched - if update, only starred chatrooms are fetched for options - update: if not set, local value will be returned for results - chatroomList will be returned it is defined in components/contact.py ''' raise NotImplementedError() def get_friends(self, update=False): ''' fetch friends list for options - update: if not set, local value will be returned for results - a list of friends' info dicts will be returned it is defined in components/contact.py ''' raise NotImplementedError() def get_chatrooms(self, update=False, contactOnly=False): ''' fetch chatrooms list for options - update: if not set, local value will be returned - contactOnly: if set, only starred chatrooms will be returned for results - a list of chatrooms' info dicts will be returned it is defined in components/contact.py ''' raise NotImplementedError() def get_mps(self, update=False): ''' fetch massive platforms list for options - update: if not set, local value will be returned for results - a list of platforms' info dicts will be returned it is defined in components/contact.py ''' raise NotImplementedError() def set_alias(self, userName, alias): ''' set alias for a friend for options - userName: 'UserName' key of info dict - alias: new alias it is defined in components/contact.py ''' raise NotImplementedError() def set_pinned(self, userName, isPinned=True): ''' set pinned for a friend or a chatroom for options - userName: 'UserName' key of info dict - isPinned: whether to pin it is defined in components/contact.py ''' raise NotImplementedError() def accept_friend(self, userName, v4,autoUpdate=True): ''' accept a friend or accept a friend for options - userName: 'UserName' for friend's info dict - status: - for adding status should be 2 - for accepting status should be 3 - ticket: greeting message - userInfo: friend's other info for adding into local storage it is defined in components/contact.py ''' raise NotImplementedError() def get_head_img(self, userName=None, chatroomUserName=None, picDir=None): ''' place for docs for options - if you want to get chatroom header: only set chatroomUserName - if you want to get friend header: only set userName - if you want to get chatroom member header: set both it is defined in components/contact.py ''' raise NotImplementedError() def create_chatroom(self, memberList, topic=''): ''' create a chatroom for creating - its calling frequency is strictly limited for options - memberList: list of member info dict - topic: topic of new chatroom it is defined in components/contact.py ''' raise NotImplementedError() def set_chatroom_name(self, chatroomUserName, name): ''' set chatroom name for setting - it makes an updating of chatroom - which means detailed info will be returned in heart loop for options - chatroomUserName: 'UserName' key of chatroom info dict - name: new chatroom name it is defined in components/contact.py ''' raise NotImplementedError() def delete_member_from_chatroom(self, chatroomUserName, memberList): ''' deletes members from chatroom for deleting - you can't delete yourself - if so, no one will be deleted - strict-limited frequency for options - chatroomUserName: 'UserName' key of chatroom info dict - memberList: list of members' info dict it is defined in components/contact.py ''' raise NotImplementedError() def add_member_into_chatroom(self, chatroomUserName, memberList, useInvitation=False): ''' add members into chatroom for adding - you can't add yourself or member already in chatroom - if so, no one will be added - if member will over 40 after adding, invitation must be used - strict-limited frequency for options - chatroomUserName: 'UserName' key of chatroom info dict - memberList: list of members' info dict - useInvitation: if invitation is not required, set this to use it is defined in components/contact.py ''' raise NotImplementedError() def send_raw_msg(self, msgType, content, toUserName): ''' many messages are sent in a common way for demo .. code:: python @itchat.msg_register(itchat.content.CARD) def reply(msg): itchat.send_raw_msg(msg['MsgType'], msg['Content'], msg['FromUserName']) there are some little tricks here, you may discover them yourself but remember they are tricks it is defined in components/messages.py ''' raise NotImplementedError() def send_msg(self, msg='Test Message', toUserName=None): ''' send plain text message for options - msg: should be unicode if there's non-ascii words in msg - toUserName: 'UserName' key of friend dict it is defined in components/messages.py ''' raise NotImplementedError() def upload_file(self, fileDir, isPicture=False, isVideo=False, toUserName='filehelper', file_=None, preparedFile=None): ''' upload file to server and get mediaId for options - fileDir: dir for file ready for upload - isPicture: whether file is a picture - isVideo: whether file is a video for return values will return a ReturnValue if succeeded, mediaId is in r['MediaId'] it is defined in components/messages.py ''' raise NotImplementedError() def send_file(self, fileDir, toUserName=None, mediaId=None, file_=None): ''' send attachment for options - fileDir: dir for file ready for upload - mediaId: mediaId for file. - if set, file will not be uploaded twice - toUserName: 'UserName' key of friend dict it is defined in components/messages.py ''' raise NotImplementedError() def send_image(self, fileDir=None, toUserName=None, mediaId=None, file_=None): ''' send image for options - fileDir: dir for file ready for upload - if it's a gif, name it like 'xx.gif' - mediaId: mediaId for file. - if set, file will not be uploaded twice - toUserName: 'UserName' key of friend dict it is defined in components/messages.py ''' raise NotImplementedError() def send_video(self, fileDir=None, toUserName=None, mediaId=None, file_=None): ''' send video for options - fileDir: dir for file ready for upload - if mediaId is set, it's unnecessary to set fileDir - mediaId: mediaId for file. - if set, file will not be uploaded twice - toUserName: 'UserName' key of friend dict it is defined in components/messages.py ''' raise NotImplementedError() def send(self, msg, toUserName=None, mediaId=None): ''' wrapped function for all the sending functions for options - msg: message starts with different string indicates different type - list of type string: ['@fil@', '@img@', '@msg@', '@vid@'] - they are for file, image, plain text, video - if none of them matches, it will be sent like plain text - toUserName: 'UserName' key of friend dict - mediaId: if set, uploading will not be repeated it is defined in components/messages.py ''' raise NotImplementedError() def revoke(self, msgId, toUserName, localId=None): ''' revoke message with its and msgId for options - msgId: message Id on server - toUserName: 'UserName' key of friend dict - localId: message Id at local (optional) it is defined in components/messages.py ''' raise NotImplementedError() def dump_login_status(self, fileDir=None): ''' dump login status to a specific file for option - fileDir: dir for dumping login status it is defined in components/hotreload.py ''' raise NotImplementedError() def load_login_status(self, fileDir, loginCallback=None, exitCallback=None): ''' load login status from a specific file for option - fileDir: file for loading login status - loginCallback: callback after successfully logged in - if not set, screen is cleared and qrcode is deleted - exitCallback: callback after logged out - it contains calling of logout it is defined in components/hotreload.py ''' raise NotImplementedError() def auto_login(self, hotReload=False, statusStorageDir='itchat.pkl', enableCmdQR=False, picDir=None, qrCallback=None, loginCallback=None, exitCallback=None): ''' log in like web wechat does for log in - a QR code will be downloaded and opened - then scanning status is logged, it paused for you confirm - finally it logged in and show your nickName for options - hotReload: enable hot reload - statusStorageDir: dir for storing log in status - enableCmdQR: show qrcode in command line - integers can be used to fit strange char length - picDir: place for storing qrcode - loginCallback: callback after successfully logged in - if not set, screen is cleared and qrcode is deleted - exitCallback: callback after logged out - it contains calling of logout - qrCallback: method that should accept uuid, status, qrcode for usage ..code::python import itchat itchat.auto_login() it is defined in components/register.py and of course every single move in login can be called outside - you may scan source code to see how - and modified according to your own demond ''' raise NotImplementedError() def configured_reply(self): ''' determine the type of message and reply if its method is defined however, I use a strange way to determine whether a msg is from massive platform I haven't found a better solution here The main problem I'm worrying about is the mismatching of new friends added on phone If you have any good idea, pleeeease report an issue. I will be more than grateful. ''' raise NotImplementedError() def msg_register(self, msgType, isFriendChat=False, isGroupChat=False, isMpChat=False): ''' a decorator constructor return a specific decorator based on information given ''' raise NotImplementedError() def run(self, debug=True, blockThread=True): ''' start auto respond for option - debug: if set, debug info will be shown on screen it is defined in components/register.py ''' raise NotImplementedError() def search_friends(self, name=None, userName=None, remarkName=None, nickName=None, wechatAccount=None): return self.storageClass.search_friends(name, userName, remarkName, nickName, wechatAccount) def search_chatrooms(self, name=None, userName=None): return self.storageClass.search_chatrooms(name, userName) def search_mps(self, name=None, userName=None): return self.storageClass.search_mps(name, userName)
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/log.py
Python
import logging class LogSystem(object): handlerList = [] showOnCmd = True loggingLevel = logging.INFO loggingFile = None def __init__(self): self.logger = logging.getLogger('itchat') self.logger.addHandler(logging.NullHandler()) self.logger.setLevel(self.loggingLevel) self.cmdHandler = logging.StreamHandler() self.fileHandler = None self.logger.addHandler(self.cmdHandler) def set_logging(self, showOnCmd=True, loggingFile=None, loggingLevel=logging.INFO): if showOnCmd != self.showOnCmd: if showOnCmd: self.logger.addHandler(self.cmdHandler) else: self.logger.removeHandler(self.cmdHandler) self.showOnCmd = showOnCmd if loggingFile != self.loggingFile: if self.loggingFile is not None: # clear old fileHandler self.logger.removeHandler(self.fileHandler) self.fileHandler.close() if loggingFile is not None: # add new fileHandler self.fileHandler = logging.FileHandler(loggingFile) self.logger.addHandler(self.fileHandler) self.loggingFile = loggingFile if loggingLevel != self.loggingLevel: self.logger.setLevel(loggingLevel) self.loggingLevel = loggingLevel ls = LogSystem() set_logging = ls.set_logging
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/returnvalues.py
Python
#coding=utf8 TRANSLATE = 'Chinese' class ReturnValue(dict): ''' turn return value of itchat into a boolean value for requests: ..code::python import requests r = requests.get('http://httpbin.org/get') print(ReturnValue(rawResponse=r) for normal dict: ..code::python returnDict = { 'BaseResponse': { 'Ret': 0, 'ErrMsg': 'My error msg', }, } print(ReturnValue(returnDict)) ''' def __init__(self, returnValueDict={}, rawResponse=None): if rawResponse: try: returnValueDict = rawResponse.json() except ValueError: returnValueDict = { 'BaseResponse': { 'Ret': -1004, 'ErrMsg': 'Unexpected return value', }, 'Data': rawResponse.content, } for k, v in returnValueDict.items(): self[k] = v if not 'BaseResponse' in self: self['BaseResponse'] = { 'ErrMsg': 'no BaseResponse in raw response', 'Ret': -1000, } if TRANSLATE: self['BaseResponse']['RawMsg'] = self['BaseResponse'].get('ErrMsg', '') self['BaseResponse']['ErrMsg'] = \ TRANSLATION[TRANSLATE].get( self['BaseResponse'].get('Ret', '')) \ or self['BaseResponse'].get('ErrMsg', u'No ErrMsg') self['BaseResponse']['RawMsg'] = \ self['BaseResponse']['RawMsg'] or self['BaseResponse']['ErrMsg'] def __nonzero__(self): return self['BaseResponse'].get('Ret') == 0 def __bool__(self): return self.__nonzero__() def __str__(self): return '{%s}' % ', '.join( ['%s: %s' % (repr(k),repr(v)) for k,v in self.items()]) def __repr__(self): return '<ItchatReturnValue: %s>' % self.__str__() TRANSLATION = { 'Chinese': { -1000: u'返回值不带BaseResponse', -1001: u'无法找到对应的成员', -1002: u'文件位置错误', -1003: u'服务器拒绝连接', -1004: u'服务器返回异常值', -1005: u'参数错误', -1006: u'无效操作', 0: u'请求成功', }, }
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/storage/__init__.py
Python
import os, time, copy from threading import Lock from .messagequeue import Queue from .templates import ( ContactList, AbstractUserDict, User, MassivePlatform, Chatroom, ChatroomMember) def contact_change(fn): def _contact_change(core, *args, **kwargs): with core.storageClass.updateLock: return fn(core, *args, **kwargs) return _contact_change class Storage(object): def __init__(self, core): self.userName = None self.nickName = None self.updateLock = Lock() self.memberList = ContactList() self.mpList = ContactList() self.chatroomList = ContactList() self.msgList = Queue(-1) self.lastInputUserName = None self.memberList.set_default_value(contactClass=User) self.memberList.core = core self.mpList.set_default_value(contactClass=MassivePlatform) self.mpList.core = core self.chatroomList.set_default_value(contactClass=Chatroom) self.chatroomList.core = core def dumps(self): return { 'userName' : self.userName, 'nickName' : self.nickName, 'memberList' : self.memberList, 'mpList' : self.mpList, 'chatroomList' : self.chatroomList, 'lastInputUserName' : self.lastInputUserName, } def loads(self, j): self.userName = j.get('userName', None) self.nickName = j.get('nickName', None) del self.memberList[:] for i in j.get('memberList', []): self.memberList.append(i) del self.mpList[:] for i in j.get('mpList', []): self.mpList.append(i) del self.chatroomList[:] for i in j.get('chatroomList', []): self.chatroomList.append(i) # I tried to solve everything in pickle # but this way is easier and more storage-saving for chatroom in self.chatroomList: if 'MemberList' in chatroom: for member in chatroom['MemberList']: member.core = chatroom.core member.chatroom = chatroom if 'Self' in chatroom: chatroom['Self'].core = chatroom.core chatroom['Self'].chatroom = chatroom self.lastInputUserName = j.get('lastInputUserName', None) def search_friends(self, name=None, userName=None, remarkName=None, nickName=None, wechatAccount=None): with self.updateLock: if (name or userName or remarkName or nickName or wechatAccount) is None: return copy.deepcopy(self.memberList[0]) # my own account elif userName: # return the only userName match for m in self.memberList: if m['UserName'] == userName: return copy.deepcopy(m) else: matchDict = { 'RemarkName' : remarkName, 'NickName' : nickName, 'Alias' : wechatAccount, } for k in ('RemarkName', 'NickName', 'Alias'): if matchDict[k] is None: del matchDict[k] if name: # select based on name contact = [] for m in self.memberList: if any([m.get(k) == name for k in ('RemarkName', 'NickName', 'Alias')]): contact.append(m) else: contact = self.memberList[:] if matchDict: # select again based on matchDict friendList = [] for m in contact: if all([m.get(k) == v for k, v in matchDict.items()]): friendList.append(m) return copy.deepcopy(friendList) else: return copy.deepcopy(contact) def search_chatrooms(self, name=None, userName=None): with self.updateLock: if userName is not None: for m in self.chatroomList: if m['UserName'] == userName: return copy.deepcopy(m) elif name is not None: matchList = [] for m in self.chatroomList: if name in m['NickName']: matchList.append(copy.deepcopy(m)) return matchList def search_mps(self, name=None, userName=None): with self.updateLock: if userName is not None: for m in self.mpList: if m['UserName'] == userName: return copy.deepcopy(m) elif name is not None: matchList = [] for m in self.mpList: if name in m['NickName']: matchList.append(copy.deepcopy(m)) return matchList
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/storage/messagequeue.py
Python
import logging try: import Queue as queue except ImportError: import queue from .templates import AttributeDict logger = logging.getLogger('itchat') class Queue(queue.Queue): def put(self, message): queue.Queue.put(self, Message(message)) class Message(AttributeDict): def download(self, fileName): if hasattr(self.text, '__call__'): return self.text(fileName) else: return b'' def __getitem__(self, value): if value in ('isAdmin', 'isAt'): v = value[0].upper() + value[1:] # ''[1:] == '' logger.debug('%s is expired in 1.3.0, use %s instead.' % (value, v)) value = v return super(Message, self).__getitem__(value) def __str__(self): return '{%s}' % ', '.join( ['%s: %s' % (repr(k),repr(v)) for k,v in self.items()]) def __repr__(self): return '<%s: %s>' % (self.__class__.__name__.split('.')[-1], self.__str__())
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/storage/templates.py
Python
import logging, copy, pickle from weakref import ref from ..returnvalues import ReturnValue from ..utils import update_info_dict logger = logging.getLogger('itchat') class AttributeDict(dict): def __getattr__(self, value): keyName = value[0].upper() + value[1:] try: return self[keyName] except KeyError: raise AttributeError("'%s' object has no attribute '%s'" % ( self.__class__.__name__.split('.')[-1], keyName)) def get(self, v, d=None): try: return self[v] except KeyError: return d class UnInitializedItchat(object): def _raise_error(self, *args, **kwargs): logger.warning('An itchat instance is called before initialized') def __getattr__(self, value): return self._raise_error class ContactList(list): ''' when a dict is append, init function will be called to format that dict ''' def __init__(self, *args, **kwargs): super(ContactList, self).__init__(*args, **kwargs) self.__setstate__(None) @property def core(self): return getattr(self, '_core', lambda: fakeItchat)() or fakeItchat @core.setter def core(self, value): self._core = ref(value) def set_default_value(self, initFunction=None, contactClass=None): if hasattr(initFunction, '__call__'): self.contactInitFn = initFunction if hasattr(contactClass, '__call__'): self.contactClass = contactClass def append(self, value): contact = self.contactClass(value) contact.core = self.core if self.contactInitFn is not None: contact = self.contactInitFn(self, contact) or contact super(ContactList, self).append(contact) def __deepcopy__(self, memo): r = self.__class__([copy.deepcopy(v) for v in self]) r.contactInitFn = self.contactInitFn r.contactClass = self.contactClass r.core = self.core return r def __getstate__(self): return 1 def __setstate__(self, state): self.contactInitFn = None self.contactClass = User def __str__(self): return '[%s]' % ', '.join([repr(v) for v in self]) def __repr__(self): return '<%s: %s>' % (self.__class__.__name__.split('.')[-1], self.__str__()) class AbstractUserDict(AttributeDict): def __init__(self, *args, **kwargs): super(AbstractUserDict, self).__init__(*args, **kwargs) @property def core(self): return getattr(self, '_core', lambda: fakeItchat)() or fakeItchat @core.setter def core(self, value): self._core = ref(value) def update(self): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s can not be updated' % \ self.__class__.__name__, }, }) def set_alias(self, alias): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s can not set alias' % \ self.__class__.__name__, }, }) def set_pinned(self, isPinned=True): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s can not be pinned' % \ self.__class__.__name__, }, }) def verify(self): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s do not need verify' % \ self.__class__.__name__, }, }) def get_head_image(self, imageDir=None): return self.core.get_head_img(self.userName, picDir=imageDir) def delete_member(self, userName): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s can not delete member' % \ self.__class__.__name__, }, }) def add_member(self, userName): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s can not add member' % \ self.__class__.__name__, }, }) def send_raw_msg(self, msgType, content): return self.core.send_raw_msg(msgType, content, self.userName) def send_msg(self, msg='Test Message'): return self.core.send_msg(msg, self.userName) def send_file(self, fileDir, mediaId=None): return self.core.send_file(fileDir, self.userName, mediaId) def send_image(self, fileDir, mediaId=None): return self.core.send_image(fileDir, self.userName, mediaId) def send_video(self, fileDir=None, mediaId=None): return self.core.send_video(fileDir, self.userName, mediaId) def send(self, msg, mediaId=None): return self.core.send(msg, self.userName, mediaId) def search_member(self, name=None, userName=None, remarkName=None, nickName=None, wechatAccount=None): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s do not have members' % \ self.__class__.__name__, }, }) def __deepcopy__(self, memo): r = self.__class__() for k, v in self.items(): r[copy.deepcopy(k)] = copy.deepcopy(v) r.core = self.core return r def __str__(self): return '{%s}' % ', '.join( ['%s: %s' % (repr(k),repr(v)) for k,v in self.items()]) def __repr__(self): return '<%s: %s>' % (self.__class__.__name__.split('.')[-1], self.__str__()) def __getstate__(self): return 1 def __setstate__(self, state): pass class User(AbstractUserDict): def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.__setstate__(None) def update(self): r = self.core.update_friend(self.userName) if r: update_info_dict(self, r) return r def set_alias(self, alias): return self.core.set_alias(self.userName, alias) def set_pinned(self, isPinned=True): return self.core.set_pinned(self.userName, isPinned) def verify(self): return self.core.add_friend(**self.verifyDict) def __deepcopy__(self, memo): r = super(User, self).__deepcopy__(memo) r.verifyDict = copy.deepcopy(self.verifyDict) return r def __setstate__(self, state): super(User, self).__setstate__(state) self.verifyDict = {} self['MemberList'] = fakeContactList class MassivePlatform(AbstractUserDict): def __init__(self, *args, **kwargs): super(MassivePlatform, self).__init__(*args, **kwargs) self.__setstate__(None) def __setstate__(self, state): super(MassivePlatform, self).__setstate__(state) self['MemberList'] = fakeContactList class Chatroom(AbstractUserDict): def __init__(self, *args, **kwargs): super(Chatroom, self).__init__(*args, **kwargs) memberList = ContactList() userName = self.get('UserName', '') refSelf = ref(self) def init_fn(parentList, d): d.chatroom = refSelf() or \ parentList.core.search_chatrooms(userName=userName) memberList.set_default_value(init_fn, ChatroomMember) if 'MemberList' in self: for member in self.memberList: memberList.append(member) self['MemberList'] = memberList @property def core(self): return getattr(self, '_core', lambda: fakeItchat)() or fakeItchat @core.setter def core(self, value): self._core = ref(value) self.memberList.core = value for member in self.memberList: member.core = value def update(self, detailedMember=False): r = self.core.update_chatroom(self.userName, detailedMember) if r: update_info_dict(self, r) self['MemberList'] = r['MemberList'] return r def set_alias(self, alias): return self.core.set_chatroom_name(self.userName, alias) def set_pinned(self, isPinned=True): return self.core.set_pinned(self.userName, isPinned) def delete_member(self, userName): return self.core.delete_member_from_chatroom(self.userName, userName) def add_member(self, userName): return self.core.add_member_into_chatroom(self.userName, userName) def search_member(self, name=None, userName=None, remarkName=None, nickName=None, wechatAccount=None): with self.core.storageClass.updateLock: if (name or userName or remarkName or nickName or wechatAccount) is None: return None elif userName: # return the only userName match for m in self.memberList: if m.userName == userName: return copy.deepcopy(m) else: matchDict = { 'RemarkName' : remarkName, 'NickName' : nickName, 'Alias' : wechatAccount, } for k in ('RemarkName', 'NickName', 'Alias'): if matchDict[k] is None: del matchDict[k] if name: # select based on name contact = [] for m in self.memberList: if any([m.get(k) == name for k in ('RemarkName', 'NickName', 'Alias')]): contact.append(m) else: contact = self.memberList[:] if matchDict: # select again based on matchDict friendList = [] for m in contact: if all([m.get(k) == v for k, v in matchDict.items()]): friendList.append(m) return copy.deepcopy(friendList) else: return copy.deepcopy(contact) def __setstate__(self, state): super(Chatroom, self).__setstate__(state) if not 'MemberList' in self: self['MemberList'] = fakeContactList class ChatroomMember(AbstractUserDict): def __init__(self, *args, **kwargs): super(AbstractUserDict, self).__init__(*args, **kwargs) self.__setstate__(None) @property def chatroom(self): r = getattr(self, '_chatroom', lambda: fakeChatroom)() if r is None: userName = getattr(self, '_chatroomUserName', '') r = self.core.search_chatrooms(userName=userName) if isinstance(r, dict): self.chatroom = r return r or fakeChatroom @chatroom.setter def chatroom(self, value): if isinstance(value, dict) and 'UserName' in value: self._chatroom = ref(value) self._chatroomUserName = value['UserName'] def get_head_image(self, imageDir=None): return self.core.get_head_img(self.userName, self.chatroom.userName, picDir=imageDir) def delete_member(self, userName): return self.core.delete_member_from_chatroom(self.chatroom.userName, self.userName) def send_raw_msg(self, msgType, content): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s can not send message directly' % \ self.__class__.__name__, }, }) def send_msg(self, msg='Test Message'): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s can not send message directly' % \ self.__class__.__name__, }, }) def send_file(self, fileDir, mediaId=None): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s can not send message directly' % \ self.__class__.__name__, }, }) def send_image(self, fileDir, mediaId=None): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s can not send message directly' % \ self.__class__.__name__, }, }) def send_video(self, fileDir=None, mediaId=None): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s can not send message directly' % \ self.__class__.__name__, }, }) def send(self, msg, mediaId=None): return ReturnValue({'BaseResponse': { 'Ret': -1006, 'ErrMsg': '%s can not send message directly' % \ self.__class__.__name__, }, }) def __setstate__(self, state): super(ChatroomMember, self).__setstate__(state) self['MemberList'] = fakeContactList def wrap_user_dict(d): userName = d.get('UserName') if '@@' in userName: r = Chatroom(d) elif d.get('VerifyFlag', 8) & 8 == 0: r = User(d) else: r = MassivePlatform(d) return r fakeItchat = UnInitializedItchat() fakeContactList = ContactList() fakeChatroom = Chatroom()
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
lib/itchat/utils.py
Python
import re, os, sys, subprocess, copy, traceback, logging try: from HTMLParser import HTMLParser except ImportError: from html.parser import HTMLParser try: from urllib import quote as _quote quote = lambda n: _quote(n.encode('utf8', 'replace')) except ImportError: from urllib.parse import quote import requests from . import config logger = logging.getLogger('itchat') emojiRegex = re.compile(r'<span class="emoji emoji(.{1,10})"></span>') htmlParser = HTMLParser() if not hasattr(htmlParser, 'unescape'): import html htmlParser.unescape = html.unescape # FIX Python 3.9 HTMLParser.unescape is removed. See https://docs.python.org/3.9/whatsnew/3.9.html try: b = u'\u2588' sys.stdout.write(b + '\r') sys.stdout.flush() except UnicodeEncodeError: BLOCK = 'MM' else: BLOCK = b friendInfoTemplate = {} for k in ('UserName', 'City', 'DisplayName', 'PYQuanPin', 'RemarkPYInitial', 'Province', 'KeyWord', 'RemarkName', 'PYInitial', 'EncryChatRoomId', 'Alias', 'Signature', 'NickName', 'RemarkPYQuanPin', 'HeadImgUrl'): friendInfoTemplate[k] = '' for k in ('UniFriend', 'Sex', 'AppAccountFlag', 'VerifyFlag', 'ChatRoomId', 'HideInputBarFlag', 'AttrStatus', 'SnsFlag', 'MemberCount', 'OwnerUin', 'ContactFlag', 'Uin', 'StarFriend', 'Statues'): friendInfoTemplate[k] = 0 friendInfoTemplate['MemberList'] = [] def clear_screen(): os.system('cls' if config.OS == 'Windows' else 'clear') def emoji_formatter(d, k): ''' _emoji_deebugger is for bugs about emoji match caused by wechat backstage like :face with tears of joy: will be replaced with :cat face with tears of joy: ''' def _emoji_debugger(d, k): s = d[k].replace('<span class="emoji emoji1f450"></span', '<span class="emoji emoji1f450"></span>') # fix missing bug def __fix_miss_match(m): return '<span class="emoji emoji%s"></span>' % ({ '1f63c': '1f601', '1f639': '1f602', '1f63a': '1f603', '1f4ab': '1f616', '1f64d': '1f614', '1f63b': '1f60d', '1f63d': '1f618', '1f64e': '1f621', '1f63f': '1f622', }.get(m.group(1), m.group(1))) return emojiRegex.sub(__fix_miss_match, s) def _emoji_formatter(m): s = m.group(1) if len(s) == 6: return ('\\U%s\\U%s'%(s[:2].rjust(8, '0'), s[2:].rjust(8, '0')) ).encode('utf8').decode('unicode-escape', 'replace') elif len(s) == 10: return ('\\U%s\\U%s'%(s[:5].rjust(8, '0'), s[5:].rjust(8, '0')) ).encode('utf8').decode('unicode-escape', 'replace') else: return ('\\U%s'%m.group(1).rjust(8, '0') ).encode('utf8').decode('unicode-escape', 'replace') d[k] = _emoji_debugger(d, k) d[k] = emojiRegex.sub(_emoji_formatter, d[k]) def msg_formatter(d, k): emoji_formatter(d, k) d[k] = d[k].replace('<br/>', '\n') d[k] = htmlParser.unescape(d[k]) def check_file(fileDir): try: with open(fileDir): pass return True except: return False def print_qr(fileDir): if config.OS == 'Darwin': subprocess.call(['open', fileDir]) elif config.OS == 'Linux': subprocess.call(['xdg-open', fileDir]) else: os.startfile(fileDir) def print_cmd_qr(qrText, white=BLOCK, black=' ', enableCmdQR=True): blockCount = int(enableCmdQR) if abs(blockCount) == 0: blockCount = 1 white *= abs(blockCount) if blockCount < 0: white, black = black, white sys.stdout.write(' '*50 + '\r') sys.stdout.flush() qr = qrText.replace('0', white).replace('1', black) sys.stdout.write(qr) sys.stdout.flush() def struct_friend_info(knownInfo): member = copy.deepcopy(friendInfoTemplate) for k, v in copy.deepcopy(knownInfo).items(): member[k] = v return member def search_dict_list(l, key, value): ''' Search a list of dict * return dict with specific value & key ''' for i in l: if i.get(key) == value: return i def print_line(msg, oneLine = False): if oneLine: sys.stdout.write(' '*40 + '\r') sys.stdout.flush() else: sys.stdout.write('\n') sys.stdout.write(msg.encode(sys.stdin.encoding or 'utf8', 'replace' ).decode(sys.stdin.encoding or 'utf8', 'replace')) sys.stdout.flush() def test_connect(retryTime=5): for i in range(retryTime): try: r = requests.get(config.BASE_URL) return True except: if i == retryTime - 1: logger.error(traceback.format_exc()) return False def contact_deep_copy(core, contact): with core.storageClass.updateLock: return copy.deepcopy(contact) def get_image_postfix(data): data = data[:20] if b'GIF' in data: return 'gif' elif b'PNG' in data: return 'png' elif b'JFIF' in data: return 'jpg' return '' def update_info_dict(oldInfoDict, newInfoDict): ''' only normal values will be updated here because newInfoDict is normal dict, so it's not necessary to consider templates ''' for k, v in newInfoDict.items(): if any((isinstance(v, t) for t in (tuple, list, dict))): pass # these values will be updated somewhere else elif oldInfoDict.get(k) is None or v not in (None, '', '0', 0): oldInfoDict[k] = v
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
models/ali/ali_qwen_bot.py
Python
# encoding:utf-8 import json import time from typing import List, Tuple import openai import openai.error import broadscope_bailian from broadscope_bailian import ChatQaMessage from models.bot import Bot from models.ali.ali_qwen_session import AliQwenSession from models.session_manager import SessionManager from bridge.context import ContextType from bridge.reply import Reply, ReplyType from common.log import logger from common import const from config import conf, load_config class AliQwenBot(Bot): def __init__(self): super().__init__() self.api_key_expired_time = self.set_api_key() self.sessions = SessionManager(AliQwenSession, model=conf().get("model", const.QWEN)) def api_key_client(self): return broadscope_bailian.AccessTokenClient(access_key_id=self.access_key_id(), access_key_secret=self.access_key_secret()) def access_key_id(self): return conf().get("qwen_access_key_id") def access_key_secret(self): return conf().get("qwen_access_key_secret") def agent_key(self): return conf().get("qwen_agent_key") def app_id(self): return conf().get("qwen_app_id") def node_id(self): return conf().get("qwen_node_id", "") def temperature(self): return conf().get("temperature", 0.2 ) def top_p(self): return conf().get("top_p", 1) def reply(self, query, context=None): # acquire reply content if context.type == ContextType.TEXT: logger.info("[QWEN] query={}".format(query)) session_id = context["session_id"] reply = None clear_memory_commands = conf().get("clear_memory_commands", ["#清除记忆"]) if query in clear_memory_commands: self.sessions.clear_session(session_id) reply = Reply(ReplyType.INFO, "记忆已清除") elif query == "#清除所有": self.sessions.clear_all_session() reply = Reply(ReplyType.INFO, "所有人记忆已清除") elif query == "#更新配置": load_config() reply = Reply(ReplyType.INFO, "配置已更新") if reply: return reply session = self.sessions.session_query(query, session_id) logger.debug("[QWEN] session query={}".format(session.messages)) reply_content = self.reply_text(session) logger.debug( "[QWEN] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format( session.messages, session_id, reply_content["content"], reply_content["completion_tokens"], ) ) if reply_content["completion_tokens"] == 0 and len(reply_content["content"]) > 0: reply = Reply(ReplyType.ERROR, reply_content["content"]) elif reply_content["completion_tokens"] > 0: self.sessions.session_reply(reply_content["content"], session_id, reply_content["total_tokens"]) reply = Reply(ReplyType.TEXT, reply_content["content"]) else: reply = Reply(ReplyType.ERROR, reply_content["content"]) logger.debug("[QWEN] reply {} used 0 tokens.".format(reply_content)) return reply else: reply = Reply(ReplyType.ERROR, "Bot不支持处理{}类型的消息".format(context.type)) return reply def reply_text(self, session: AliQwenSession, retry_count=0) -> dict: """ call bailian's ChatCompletion to get the answer :param session: a conversation session :param retry_count: retry count :return: {} """ try: prompt, history = self.convert_messages_format(session.messages) self.update_api_key_if_expired() # NOTE 阿里百炼的call()函数未提供temperature参数,考虑到temperature和top_p参数作用相同,取两者较小的值作为top_p参数传入,详情见文档 https://help.aliyun.com/document_detail/2587502.htm response = broadscope_bailian.Completions().call(app_id=self.app_id(), prompt=prompt, history=history, top_p=min(self.temperature(), self.top_p())) completion_content = self.get_completion_content(response, self.node_id()) completion_tokens, total_tokens = self.calc_tokens(session.messages, completion_content) return { "total_tokens": total_tokens, "completion_tokens": completion_tokens, "content": completion_content, } except Exception as e: need_retry = retry_count < 2 result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"} if isinstance(e, openai.error.RateLimitError): logger.warn("[QWEN] RateLimitError: {}".format(e)) result["content"] = "提问太快啦,请休息一下再问我吧" if need_retry: time.sleep(20) elif isinstance(e, openai.error.Timeout): logger.warn("[QWEN] Timeout: {}".format(e)) result["content"] = "我没有收到你的消息" if need_retry: time.sleep(5) elif isinstance(e, openai.error.APIError): logger.warn("[QWEN] Bad Gateway: {}".format(e)) result["content"] = "请再问我一次" if need_retry: time.sleep(10) elif isinstance(e, openai.error.APIConnectionError): logger.warn("[QWEN] APIConnectionError: {}".format(e)) need_retry = False result["content"] = "我连接不到你的网络" else: logger.exception("[QWEN] Exception: {}".format(e)) need_retry = False self.sessions.clear_session(session.session_id) if need_retry: logger.warn("[QWEN] 第{}次重试".format(retry_count + 1)) return self.reply_text(session, retry_count + 1) else: return result def set_api_key(self): api_key, expired_time = self.api_key_client().create_token(agent_key=self.agent_key()) broadscope_bailian.api_key = api_key return expired_time def update_api_key_if_expired(self): if time.time() > self.api_key_expired_time: self.api_key_expired_time = self.set_api_key() def convert_messages_format(self, messages) -> Tuple[str, List[ChatQaMessage]]: history = [] user_content = '' assistant_content = '' system_content = '' for message in messages: role = message.get('role') if role == 'user': user_content += message.get('content') elif role == 'assistant': assistant_content = message.get('content') history.append(ChatQaMessage(user_content, assistant_content)) user_content = '' assistant_content = '' elif role =='system': system_content += message.get('content') if user_content == '': raise Exception('no user message') if system_content != '': # NOTE 模拟系统消息,测试发现人格描述以"你需要扮演ChatGPT"开头能够起作用,而以"你是ChatGPT"开头模型会直接否认 system_qa = ChatQaMessage(system_content, '好的,我会严格按照你的设定回答问题') history.insert(0, system_qa) logger.debug("[QWEN] converted qa messages: {}".format([item.to_dict() for item in history])) logger.debug("[QWEN] user content as prompt: {}".format(user_content)) return user_content, history def get_completion_content(self, response, node_id): if not response['Success']: return f"[ERROR]\n{response['Code']}:{response['Message']}" text = response['Data']['Text'] if node_id == '': return text # TODO: 当使用流程编排创建大模型应用时,响应结构如下,最终结果在['finalResult'][node_id]['response']['text']中,暂时先这么写 # { # 'Success': True, # 'Code': None, # 'Message': None, # 'Data': { # 'ResponseId': '9822f38dbacf4c9b8daf5ca03a2daf15', # 'SessionId': 'session_id', # 'Text': '{"finalResult":{"LLM_T7islK":{"params":{"modelId":"qwen-plus-v1","prompt":"${systemVars.query}${bizVars.Text}"},"response":{"text":"作为一个AI语言模型,我没有年龄,因为我没有生日。\n我只是一个程序,没有生命和身体。"}}}}', # 'Thoughts': [], # 'Debug': {}, # 'DocReferences': [] # }, # 'RequestId': '8e11d31551ce4c3f83f49e6e0dd998b0', # 'Failed': None # } text_dict = json.loads(text) completion_content = text_dict['finalResult'][node_id]['response']['text'] return completion_content def calc_tokens(self, messages, completion_content): completion_tokens = len(completion_content) prompt_tokens = 0 for message in messages: prompt_tokens += len(message["content"]) return completion_tokens, prompt_tokens + completion_tokens
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
models/ali/ali_qwen_session.py
Python
from models.session_manager import Session from common.log import logger """ e.g. [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"}, {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, {"role": "user", "content": "Where was it played?"} ] """ class AliQwenSession(Session): def __init__(self, session_id, system_prompt=None, model="qianwen"): super().__init__(session_id, system_prompt) self.model = model self.reset() def discard_exceeding(self, max_tokens, cur_tokens=None): precise = True try: cur_tokens = self.calc_tokens() except Exception as e: precise = False if cur_tokens is None: raise e logger.debug("Exception when counting tokens precisely for query: {}".format(e)) while cur_tokens > max_tokens: if len(self.messages) > 2: self.messages.pop(1) elif len(self.messages) == 2 and self.messages[1]["role"] == "assistant": self.messages.pop(1) if precise: cur_tokens = self.calc_tokens() else: cur_tokens = cur_tokens - max_tokens break elif len(self.messages) == 2 and self.messages[1]["role"] == "user": logger.warn("user message exceed max_tokens. total_tokens={}".format(cur_tokens)) break else: logger.debug("max_tokens={}, total_tokens={}, len(messages)={}".format(max_tokens, cur_tokens, len(self.messages))) break if precise: cur_tokens = self.calc_tokens() else: cur_tokens = cur_tokens - max_tokens return cur_tokens def calc_tokens(self): return num_tokens_from_messages(self.messages, self.model) def num_tokens_from_messages(messages, model): """Returns the number of tokens used by a list of messages.""" # 官方token计算规则:"对于中文文本来说,1个token通常对应一个汉字;对于英文文本来说,1个token通常对应3至4个字母或1个单词" # 详情请产看文档:https://help.aliyun.com/document_detail/2586397.html # 目前根据字符串长度粗略估计token数,不影响正常使用 tokens = 0 for msg in messages: tokens += len(msg["content"]) return tokens
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
models/baidu/baidu_unit_bot.py
Python
# encoding:utf-8 import requests from models.bot import Bot from bridge.reply import Reply, ReplyType # Baidu Unit对话接口 (可用, 但能力较弱) class BaiduUnitBot(Bot): def reply(self, query, context=None): token = self.get_token() url = "https://aip.baidubce.com/rpc/2.0/unit/service/v3/chat?access_token=" + token post_data = ( '{"version":"3.0","service_id":"S73177","session_id":"","log_id":"7758521","skill_ids":["1221886"],"request":{"terminal_id":"88888","query":"' + query + '", "hyper_params": {"chat_custom_bot_profile": 1}}}' ) print(post_data) headers = {"content-type": "application/x-www-form-urlencoded"} response = requests.post(url, data=post_data.encode(), headers=headers) if response: reply = Reply( ReplyType.TEXT, response.json()["result"]["context"]["SYS_PRESUMED_HIST"][1], ) return reply def get_token(self): access_key = "YOUR_ACCESS_KEY" secret_key = "YOUR_SECRET_KEY" host = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + access_key + "&client_secret=" + secret_key response = requests.get(host) if response: print(response.json()) return response.json()["access_token"]
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
models/baidu/baidu_wenxin.py
Python
# encoding:utf-8 import requests import json from common import const from models.bot import Bot from models.session_manager import SessionManager from bridge.context import ContextType from bridge.reply import Reply, ReplyType from common.log import logger from config import conf from models.baidu.baidu_wenxin_session import BaiduWenxinSession BAIDU_API_KEY = conf().get("baidu_wenxin_api_key") BAIDU_SECRET_KEY = conf().get("baidu_wenxin_secret_key") class BaiduWenxinBot(Bot): def __init__(self): super().__init__() wenxin_model = conf().get("baidu_wenxin_model") self.prompt_enabled = conf().get("baidu_wenxin_prompt_enabled") if self.prompt_enabled: self.prompt = conf().get("character_desc", "") if self.prompt == "": logger.warn("[BAIDU] Although you enabled model prompt, character_desc is not specified.") if wenxin_model is not None: wenxin_model = conf().get("baidu_wenxin_model") or "eb-instant" else: if conf().get("model") and conf().get("model") == const.WEN_XIN: wenxin_model = "completions" elif conf().get("model") and conf().get("model") == const.WEN_XIN_4: wenxin_model = "completions_pro" self.sessions = SessionManager(BaiduWenxinSession, model=wenxin_model) def reply(self, query, context=None): # acquire reply content if context and context.type: if context.type == ContextType.TEXT: logger.info("[BAIDU] query={}".format(query)) session_id = context["session_id"] reply = None if query == "#清除记忆": self.sessions.clear_session(session_id) reply = Reply(ReplyType.INFO, "记忆已清除") elif query == "#清除所有": self.sessions.clear_all_session() reply = Reply(ReplyType.INFO, "所有人记忆已清除") else: session = self.sessions.session_query(query, session_id) result = self.reply_text(session) total_tokens, completion_tokens, reply_content = ( result["total_tokens"], result["completion_tokens"], result["content"], ) logger.debug( "[BAIDU] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(session.messages, session_id, reply_content, completion_tokens) ) if total_tokens == 0: reply = Reply(ReplyType.ERROR, reply_content) else: self.sessions.session_reply(reply_content, session_id, total_tokens) reply = Reply(ReplyType.TEXT, reply_content) return reply elif context.type == ContextType.IMAGE_CREATE: ok, retstring = self.create_img(query, 0) reply = None if ok: reply = Reply(ReplyType.IMAGE_URL, retstring) else: reply = Reply(ReplyType.ERROR, retstring) return reply def reply_text(self, session: BaiduWenxinSession, retry_count=0): try: logger.info("[BAIDU] model={}".format(session.model)) access_token = self.get_access_token() if access_token == 'None': logger.warn("[BAIDU] access token 获取失败") return { "total_tokens": 0, "completion_tokens": 0, "content": 0, } url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/" + session.model + "?access_token=" + access_token headers = { 'Content-Type': 'application/json' } payload = {'messages': session.messages, 'system': self.prompt} if self.prompt_enabled else {'messages': session.messages} response = requests.request("POST", url, headers=headers, data=json.dumps(payload)) response_text = json.loads(response.text) logger.info(f"[BAIDU] response text={response_text}") res_content = response_text["result"] total_tokens = response_text["usage"]["total_tokens"] completion_tokens = response_text["usage"]["completion_tokens"] logger.info("[BAIDU] reply={}".format(res_content)) return { "total_tokens": total_tokens, "completion_tokens": completion_tokens, "content": res_content, } except Exception as e: need_retry = retry_count < 2 logger.warn("[BAIDU] Exception: {}".format(e)) need_retry = False self.sessions.clear_session(session.session_id) result = {"total_tokens": 0, "completion_tokens": 0, "content": "出错了: {}".format(e)} return result def get_access_token(self): """ 使用 AK,SK 生成鉴权签名(Access Token) :return: access_token,或是None(如果错误) """ url = "https://aip.baidubce.com/oauth/2.0/token" params = {"grant_type": "client_credentials", "client_id": BAIDU_API_KEY, "client_secret": BAIDU_SECRET_KEY} return str(requests.post(url, params=params).json().get("access_token"))
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
models/baidu/baidu_wenxin_session.py
Python
from models.session_manager import Session from common.log import logger """ e.g. [ {"role": "user", "content": "Who won the world series in 2020?"}, {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, {"role": "user", "content": "Where was it played?"} ] """ class BaiduWenxinSession(Session): def __init__(self, session_id, system_prompt=None, model="gpt-3.5-turbo"): super().__init__(session_id, system_prompt) self.model = model # 百度文心不支持system prompt # self.reset() def discard_exceeding(self, max_tokens, cur_tokens=None): precise = True try: cur_tokens = self.calc_tokens() except Exception as e: precise = False if cur_tokens is None: raise e logger.debug("Exception when counting tokens precisely for query: {}".format(e)) while cur_tokens > max_tokens: if len(self.messages) >= 2: self.messages.pop(0) self.messages.pop(0) else: logger.debug("max_tokens={}, total_tokens={}, len(messages)={}".format(max_tokens, cur_tokens, len(self.messages))) break if precise: cur_tokens = self.calc_tokens() else: cur_tokens = cur_tokens - max_tokens return cur_tokens def calc_tokens(self): return num_tokens_from_messages(self.messages, self.model) def num_tokens_from_messages(messages, model): """Returns the number of tokens used by a list of messages.""" tokens = 0 for msg in messages: # 官方token计算规则暂不明确: "大约为 token数为 "中文字 + 其他语种单词数 x 1.3" # 这里先直接根据字数粗略估算吧,暂不影响正常使用,仅在判断是否丢弃历史会话的时候会有偏差 tokens += len(msg["content"]) return tokens
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
models/bot.py
Python
""" Auto-replay chat robot abstract class """ from bridge.context import Context from bridge.reply import Reply class Bot(object): def reply(self, query, context: Context = None) -> Reply: """ bot auto-reply content :param req: received message :return: reply content """ raise NotImplementedError
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
models/bot_factory.py
Python
""" channel factory """ from common import const def create_bot(bot_type): """ create a bot_type instance :param bot_type: bot type code :return: bot instance """ if bot_type == const.BAIDU: # 替换Baidu Unit为Baidu文心千帆对话接口 # from models.baidu.baidu_unit_bot import BaiduUnitBot # return BaiduUnitBot() from models.baidu.baidu_wenxin import BaiduWenxinBot return BaiduWenxinBot() elif bot_type == const.CHATGPT: # ChatGPT 网页端web接口 from models.chatgpt.chat_gpt_bot import ChatGPTBot return ChatGPTBot() elif bot_type == const.OPEN_AI: # OpenAI 官方对话模型API from models.openai.open_ai_bot import OpenAIBot return OpenAIBot() elif bot_type == const.CHATGPTONAZURE: # Azure chatgpt service https://azure.microsoft.com/en-in/products/cognitive-services/openai-service/ from models.chatgpt.chat_gpt_bot import AzureChatGPTBot return AzureChatGPTBot() elif bot_type == const.XUNFEI: from models.xunfei.xunfei_spark_bot import XunFeiBot return XunFeiBot() elif bot_type == const.LINKAI: from models.linkai.link_ai_bot import LinkAIBot return LinkAIBot() elif bot_type == const.CLAUDEAPI: from models.claudeapi.claude_api_bot import ClaudeAPIBot return ClaudeAPIBot() elif bot_type == const.QWEN: from models.ali.ali_qwen_bot import AliQwenBot return AliQwenBot() elif bot_type == const.QWEN_DASHSCOPE: from models.dashscope.dashscope_bot import DashscopeBot return DashscopeBot() elif bot_type == const.GEMINI: from models.gemini.google_gemini_bot import GoogleGeminiBot return GoogleGeminiBot() elif bot_type == const.ZHIPU_AI: from models.zhipuai.zhipuai_bot import ZHIPUAIBot return ZHIPUAIBot() elif bot_type == const.MOONSHOT: from models.moonshot.moonshot_bot import MoonshotBot return MoonshotBot() elif bot_type == const.MiniMax: from models.minimax.minimax_bot import MinimaxBot return MinimaxBot() elif bot_type == const.MODELSCOPE: from models.modelscope.modelscope_bot import ModelScopeBot return ModelScopeBot() elif bot_type == const.DOUBAO: from models.doubao.doubao_bot import DoubaoBot return DoubaoBot() raise RuntimeError
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
models/chatgpt/chat_gpt_bot.py
Python
# encoding:utf-8 import time import json import openai import openai.error import requests from common import const from models.bot import Bot from models.openai_compatible_bot import OpenAICompatibleBot from models.chatgpt.chat_gpt_session import ChatGPTSession from models.openai.open_ai_image import OpenAIImage from models.session_manager import SessionManager from bridge.context import ContextType from bridge.reply import Reply, ReplyType from common.log import logger from common.token_bucket import TokenBucket from config import conf, load_config from models.baidu.baidu_wenxin_session import BaiduWenxinSession # OpenAI对话模型API (可用) class ChatGPTBot(Bot, OpenAIImage, OpenAICompatibleBot): def __init__(self): super().__init__() # set the default api_key openai.api_key = conf().get("open_ai_api_key") if conf().get("open_ai_api_base"): openai.api_base = conf().get("open_ai_api_base") proxy = conf().get("proxy") if proxy: openai.proxy = proxy if conf().get("rate_limit_chatgpt"): self.tb4chatgpt = TokenBucket(conf().get("rate_limit_chatgpt", 20)) conf_model = conf().get("model") or "gpt-3.5-turbo" self.sessions = SessionManager(ChatGPTSession, model=conf().get("model") or "gpt-3.5-turbo") # o1相关模型不支持system prompt,暂时用文心模型的session self.args = { "model": conf_model, # 对话模型的名称 "temperature": conf().get("temperature", 0.9), # 值在[0,1]之间,越大表示回复越具有不确定性 # "max_tokens":4096, # 回复最大的字符数 "top_p": conf().get("top_p", 1), "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容 "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容 "request_timeout": conf().get("request_timeout", None), # 请求超时时间,openai接口默认设置为600,对于难问题一般需要较长时间 "timeout": conf().get("request_timeout", None), # 重试超时时间,在这个时间内,将会自动重试 } # 部分模型暂不支持一些参数,特殊处理 if conf_model in [const.O1, const.O1_MINI, const.GPT_5, const.GPT_5_MINI, const.GPT_5_NANO]: remove_keys = ["temperature", "top_p", "frequency_penalty", "presence_penalty"] for key in remove_keys: self.args.pop(key, None) # 如果键不存在,使用 None 来避免抛出错、 if conf_model in [const.O1, const.O1_MINI]: # o1系列模型不支持系统提示词,使用文心模型的session self.sessions = SessionManager(BaiduWenxinSession, model=conf().get("model") or const.O1_MINI) def get_api_config(self): """Get API configuration for OpenAI-compatible base class""" return { 'api_key': conf().get("open_ai_api_key"), 'api_base': conf().get("open_ai_api_base"), 'model': conf().get("model", "gpt-3.5-turbo"), 'default_temperature': conf().get("temperature", 0.9), 'default_top_p': conf().get("top_p", 1.0), 'default_frequency_penalty': conf().get("frequency_penalty", 0.0), 'default_presence_penalty': conf().get("presence_penalty", 0.0), } def reply(self, query, context=None): # acquire reply content if context.type == ContextType.TEXT: logger.info("[CHATGPT] query={}".format(query)) session_id = context["session_id"] reply = None clear_memory_commands = conf().get("clear_memory_commands", ["#清除记忆"]) if query in clear_memory_commands: self.sessions.clear_session(session_id) reply = Reply(ReplyType.INFO, "记忆已清除") elif query == "#清除所有": self.sessions.clear_all_session() reply = Reply(ReplyType.INFO, "所有人记忆已清除") elif query == "#更新配置": load_config() reply = Reply(ReplyType.INFO, "配置已更新") if reply: return reply session = self.sessions.session_query(query, session_id) logger.debug("[CHATGPT] session query={}".format(session.messages)) api_key = context.get("openai_api_key") model = context.get("gpt_model") new_args = None if model: new_args = self.args.copy() new_args["model"] = model # if context.get('stream'): # # reply in stream # return self.reply_text_stream(query, new_query, session_id) reply_content = self.reply_text(session, api_key, args=new_args) logger.debug( "[CHATGPT] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format( session.messages, session_id, reply_content["content"], reply_content["completion_tokens"], ) ) if reply_content["completion_tokens"] == 0 and len(reply_content["content"]) > 0: reply = Reply(ReplyType.ERROR, reply_content["content"]) elif reply_content["completion_tokens"] > 0: self.sessions.session_reply(reply_content["content"], session_id, reply_content["total_tokens"]) reply = Reply(ReplyType.TEXT, reply_content["content"]) else: reply = Reply(ReplyType.ERROR, reply_content["content"]) logger.debug("[CHATGPT] reply {} used 0 tokens.".format(reply_content)) return reply elif context.type == ContextType.IMAGE_CREATE: ok, retstring = self.create_img(query, 0) reply = None if ok: reply = Reply(ReplyType.IMAGE_URL, retstring) else: reply = Reply(ReplyType.ERROR, retstring) return reply elif context.type == ContextType.IMAGE: logger.info("[CHATGPT] Image message received") reply = self.reply_image(context) return reply else: reply = Reply(ReplyType.ERROR, "Bot不支持处理{}类型的消息".format(context.type)) return reply def reply_image(self, context): """ Process image message using OpenAI Vision API """ import base64 import os try: image_path = context.content logger.info(f"[CHATGPT] Processing image: {image_path}") # Check if file exists if not os.path.exists(image_path): logger.error(f"[CHATGPT] Image file not found: {image_path}") return Reply(ReplyType.ERROR, "图片文件不存在") # Read and encode image with open(image_path, "rb") as f: image_data = f.read() image_base64 = base64.b64encode(image_data).decode("utf-8") # Detect image format extension = os.path.splitext(image_path)[1].lower() mime_type_map = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".gif": "image/gif", ".webp": "image/webp" } mime_type = mime_type_map.get(extension, "image/jpeg") # Get model and API config model = context.get("gpt_model") or conf().get("model", "gpt-4o") api_key = context.get("openai_api_key") or conf().get("open_ai_api_key") api_base = conf().get("open_ai_api_base") # Build vision request messages = [ { "role": "user", "content": [ {"type": "text", "text": "请描述这张图片的内容"}, { "type": "image_url", "image_url": { "url": f"data:{mime_type};base64,{image_base64}" } } ] } ] logger.info(f"[CHATGPT] Calling vision API with model: {model}") # Call OpenAI API kwargs = { "model": model, "messages": messages, "max_tokens": 1000 } if api_key: kwargs["api_key"] = api_key if api_base: kwargs["api_base"] = api_base response = openai.ChatCompletion.create(**kwargs) content = response.choices[0]["message"]["content"] logger.info(f"[CHATGPT] Vision API response: {content[:100]}...") # Clean up temp file try: os.remove(image_path) logger.debug(f"[CHATGPT] Removed temp image file: {image_path}") except: pass return Reply(ReplyType.TEXT, content) except Exception as e: logger.error(f"[CHATGPT] Image processing error: {e}") import traceback logger.error(traceback.format_exc()) return Reply(ReplyType.ERROR, f"图片识别失败: {str(e)}") def reply_text(self, session: ChatGPTSession, api_key=None, args=None, retry_count=0) -> dict: """ call openai's ChatCompletion to get the answer :param session: a conversation session :param session_id: session id :param retry_count: retry count :return: {} """ try: if conf().get("rate_limit_chatgpt") and not self.tb4chatgpt.get_token(): raise openai.error.RateLimitError("RateLimitError: rate limit exceeded") # if api_key == None, the default openai.api_key will be used if args is None: args = self.args response = openai.ChatCompletion.create(api_key=api_key, messages=session.messages, **args) # logger.debug("[CHATGPT] response={}".format(response)) logger.info("[ChatGPT] reply={}, total_tokens={}".format(response.choices[0]['message']['content'], response["usage"]["total_tokens"])) return { "total_tokens": response["usage"]["total_tokens"], "completion_tokens": response["usage"]["completion_tokens"], "content": response.choices[0]["message"]["content"], } except Exception as e: need_retry = retry_count < 2 result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"} if isinstance(e, openai.error.RateLimitError): logger.warn("[CHATGPT] RateLimitError: {}".format(e)) result["content"] = "提问太快啦,请休息一下再问我吧" if need_retry: time.sleep(20) elif isinstance(e, openai.error.Timeout): logger.warn("[CHATGPT] Timeout: {}".format(e)) result["content"] = "我没有收到你的消息" if need_retry: time.sleep(5) elif isinstance(e, openai.error.APIError): logger.warn("[CHATGPT] Bad Gateway: {}".format(e)) result["content"] = "请再问我一次" if need_retry: time.sleep(10) elif isinstance(e, openai.error.APIConnectionError): logger.warn("[CHATGPT] APIConnectionError: {}".format(e)) result["content"] = "我连接不到你的网络" if need_retry: time.sleep(5) else: logger.exception("[CHATGPT] Exception: {}".format(e)) need_retry = False self.sessions.clear_session(session.session_id) if need_retry: logger.warn("[CHATGPT] 第{}次重试".format(retry_count + 1)) return self.reply_text(session, api_key, args, retry_count + 1) else: return result class AzureChatGPTBot(ChatGPTBot): def __init__(self): super().__init__() openai.api_type = "azure" openai.api_version = conf().get("azure_api_version", "2023-06-01-preview") self.args["deployment_id"] = conf().get("azure_deployment_id") def create_img(self, query, retry_count=0, api_key=None): text_to_image_model = conf().get("text_to_image") if text_to_image_model == "dall-e-2": api_version = "2023-06-01-preview" endpoint = conf().get("azure_openai_dalle_api_base","open_ai_api_base") # 检查endpoint是否以/结尾 if not endpoint.endswith("/"): endpoint = endpoint + "/" url = "{}openai/images/generations:submit?api-version={}".format(endpoint, api_version) api_key = conf().get("azure_openai_dalle_api_key","open_ai_api_key") headers = {"api-key": api_key, "Content-Type": "application/json"} try: body = {"prompt": query, "size": conf().get("image_create_size", "256x256"),"n": 1} submission = requests.post(url, headers=headers, json=body) operation_location = submission.headers['operation-location'] status = "" while (status != "succeeded"): if retry_count > 3: return False, "图片生成失败" response = requests.get(operation_location, headers=headers) status = response.json()['status'] retry_count += 1 image_url = response.json()['result']['data'][0]['url'] return True, image_url except Exception as e: logger.error("create image error: {}".format(e)) return False, "图片生成失败" elif text_to_image_model == "dall-e-3": api_version = conf().get("azure_api_version", "2024-02-15-preview") endpoint = conf().get("azure_openai_dalle_api_base","open_ai_api_base") # 检查endpoint是否以/结尾 if not endpoint.endswith("/"): endpoint = endpoint + "/" url = "{}openai/deployments/{}/images/generations?api-version={}".format(endpoint, conf().get("azure_openai_dalle_deployment_id","text_to_image"),api_version) api_key = conf().get("azure_openai_dalle_api_key","open_ai_api_key") headers = {"api-key": api_key, "Content-Type": "application/json"} try: body = {"prompt": query, "size": conf().get("image_create_size", "1024x1024"), "quality": conf().get("dalle3_image_quality", "standard")} response = requests.post(url, headers=headers, json=body) response.raise_for_status() # 检查请求是否成功 data = response.json() # 检查响应中是否包含图像 URL if 'data' in data and len(data['data']) > 0 and 'url' in data['data'][0]: image_url = data['data'][0]['url'] return True, image_url else: error_message = "响应中没有图像 URL" logger.error(error_message) return False, "图片生成失败" except requests.exceptions.RequestException as e: # 捕获所有请求相关的异常 try: error_detail = response.json().get('error', {}).get('message', str(e)) except ValueError: error_detail = str(e) error_message = f"{error_detail}" logger.error(error_message) return False, error_message except Exception as e: # 捕获所有其他异常 error_message = f"生成图像时发生错误: {e}" logger.error(error_message) return False, "图片生成失败" else: return False, "图片生成失败,未配置text_to_image参数"
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
models/chatgpt/chat_gpt_session.py
Python
from models.session_manager import Session from common.log import logger from common import const """ e.g. [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"}, {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, {"role": "user", "content": "Where was it played?"} ] """ class ChatGPTSession(Session): def __init__(self, session_id, system_prompt=None, model="gpt-3.5-turbo"): super().__init__(session_id, system_prompt) self.model = model self.reset() def discard_exceeding(self, max_tokens, cur_tokens=None): precise = True try: cur_tokens = self.calc_tokens() except Exception as e: precise = False if cur_tokens is None: raise e logger.debug("Exception when counting tokens precisely for query: {}".format(e)) while cur_tokens > max_tokens: if len(self.messages) > 2: self.messages.pop(1) elif len(self.messages) == 2 and self.messages[1]["role"] == "assistant": self.messages.pop(1) if precise: cur_tokens = self.calc_tokens() else: cur_tokens = cur_tokens - max_tokens break elif len(self.messages) == 2 and self.messages[1]["role"] == "user": logger.warn("user message exceed max_tokens. total_tokens={}".format(cur_tokens)) break else: logger.debug("max_tokens={}, total_tokens={}, len(messages)={}".format(max_tokens, cur_tokens, len(self.messages))) break if precise: cur_tokens = self.calc_tokens() else: cur_tokens = cur_tokens - max_tokens return cur_tokens def calc_tokens(self): return num_tokens_from_messages(self.messages, self.model) # refer to https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb def num_tokens_from_messages(messages, model): """Returns the number of tokens used by a list of messages.""" if model in ["wenxin", "xunfei"] or model.startswith(const.GEMINI): return num_tokens_by_character(messages) import tiktoken if model in ["gpt-3.5-turbo-0301", "gpt-35-turbo", "gpt-3.5-turbo-1106", "moonshot", const.LINKAI_35]: return num_tokens_from_messages(messages, model="gpt-3.5-turbo") elif model in ["gpt-4-0314", "gpt-4-0613", "gpt-4-32k", "gpt-4-32k-0613", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-16k-0613", "gpt-35-turbo-16k", "gpt-4-turbo-preview", "gpt-4-1106-preview", const.GPT4_TURBO_PREVIEW, const.GPT4_VISION_PREVIEW, const.GPT4_TURBO_01_25, const.GPT_4o, const.GPT_4O_0806, const.GPT_4o_MINI, const.LINKAI_4o, const.LINKAI_4_TURBO, const.GPT_5, const.GPT_5_MINI, const.GPT_5_NANO]: return num_tokens_from_messages(messages, model="gpt-4") elif model.startswith("claude-3"): return num_tokens_from_messages(messages, model="gpt-3.5-turbo") try: encoding = tiktoken.encoding_for_model(model) except KeyError: logger.debug("Warning: model not found. Using cl100k_base encoding.") encoding = tiktoken.get_encoding("cl100k_base") if model == "gpt-3.5-turbo": tokens_per_message = 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n tokens_per_name = -1 # if there's a name, the role is omitted elif model == "gpt-4": tokens_per_message = 3 tokens_per_name = 1 else: logger.debug(f"num_tokens_from_messages() is not implemented for model {model}. Returning num tokens assuming gpt-3.5-turbo.") return num_tokens_from_messages(messages, model="gpt-3.5-turbo") num_tokens = 0 for message in messages: num_tokens += tokens_per_message for key, value in message.items(): num_tokens += len(encoding.encode(value)) if key == "name": num_tokens += tokens_per_name num_tokens += 3 # every reply is primed with <|start|>assistant<|message|> return num_tokens def num_tokens_by_character(messages): """Returns the number of tokens used by a list of messages.""" tokens = 0 for msg in messages: tokens += len(msg["content"]) return tokens
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech
models/claudeapi/claude_api_bot.py
Python
# encoding:utf-8 import json import time import requests from models.baidu.baidu_wenxin_session import BaiduWenxinSession from models.bot import Bot from models.session_manager import SessionManager from bridge.context import ContextType from bridge.reply import Reply, ReplyType from common import const from common.log import logger from config import conf # Optional OpenAI image support try: from models.openai.open_ai_image import OpenAIImage _openai_image_available = True except Exception as e: logger.warning(f"OpenAI image support not available: {e}") _openai_image_available = False OpenAIImage = object # Fallback to object user_session = dict() # OpenAI对话模型API (可用) class ClaudeAPIBot(Bot, OpenAIImage): def __init__(self): super().__init__() self.api_key = conf().get("claude_api_key") self.api_base = conf().get("claude_api_base") or "https://api.anthropic.com/v1" self.proxy = conf().get("proxy", None) self.sessions = SessionManager(BaiduWenxinSession, model=conf().get("model") or "text-davinci-003") def reply(self, query, context=None): # acquire reply content if context and context.type: if context.type == ContextType.TEXT: logger.info("[CLAUDE_API] query={}".format(query)) session_id = context["session_id"] reply = None if query == "#清除记忆": self.sessions.clear_session(session_id) reply = Reply(ReplyType.INFO, "记忆已清除") elif query == "#清除所有": self.sessions.clear_all_session() reply = Reply(ReplyType.INFO, "所有人记忆已清除") else: session = self.sessions.session_query(query, session_id) result = self.reply_text(session) logger.info(result) total_tokens, completion_tokens, reply_content = ( result["total_tokens"], result["completion_tokens"], result["content"], ) logger.debug( "[CLAUDE_API] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(str(session), session_id, reply_content, completion_tokens) ) if total_tokens == 0: reply = Reply(ReplyType.ERROR, reply_content) else: self.sessions.session_reply(reply_content, session_id, total_tokens) reply = Reply(ReplyType.TEXT, reply_content) return reply elif context.type == ContextType.IMAGE_CREATE: ok, retstring = self.create_img(query, 0) reply = None if ok: reply = Reply(ReplyType.IMAGE_URL, retstring) else: reply = Reply(ReplyType.ERROR, retstring) return reply def reply_text(self, session: BaiduWenxinSession, retry_count=0, tools=None): try: actual_model = self._model_mapping(conf().get("model")) # Prepare headers headers = { "x-api-key": self.api_key, "anthropic-version": "2023-06-01", "content-type": "application/json" } # Extract system prompt if present and prepare Claude-compatible messages system_prompt = conf().get("character_desc", "") claude_messages = [] for msg in session.messages: if msg.get("role") == "system": system_prompt = msg["content"] else: claude_messages.append(msg) # Prepare request data data = { "model": actual_model, "messages": claude_messages, "max_tokens": self._get_max_tokens(actual_model) } if system_prompt: data["system"] = system_prompt if tools: data["tools"] = tools # Make HTTP request proxies = {"http": self.proxy, "https": self.proxy} if self.proxy else None response = requests.post( f"{self.api_base}/messages", headers=headers, json=data, proxies=proxies ) if response.status_code != 200: raise Exception(f"API request failed: {response.status_code} - {response.text}") claude_response = response.json() # Handle response content and tool calls res_content = "" tool_calls = [] content_blocks = claude_response.get("content", []) for block in content_blocks: if block.get("type") == "text": res_content += block.get("text", "") elif block.get("type") == "tool_use": tool_calls.append({ "id": block.get("id", ""), "name": block.get("name", ""), "arguments": block.get("input", {}) }) res_content = res_content.strip().replace("<|endoftext|>", "") usage = claude_response.get("usage", {}) total_tokens = usage.get("input_tokens", 0) + usage.get("output_tokens", 0) completion_tokens = usage.get("output_tokens", 0) logger.info("[CLAUDE_API] reply={}".format(res_content)) if tool_calls: logger.info("[CLAUDE_API] tool_calls={}".format(tool_calls)) result = { "total_tokens": total_tokens, "completion_tokens": completion_tokens, "content": res_content, } if tool_calls: result["tool_calls"] = tool_calls return result except Exception as e: need_retry = retry_count < 2 result = {"total_tokens": 0, "completion_tokens": 0, "content": "我现在有点累了,等会再来吧"} # Handle different types of errors error_str = str(e).lower() if "rate" in error_str or "limit" in error_str: logger.warn("[CLAUDE_API] RateLimitError: {}".format(e)) result["content"] = "提问太快啦,请休息一下再问我吧" if need_retry: time.sleep(20) elif "timeout" in error_str: logger.warn("[CLAUDE_API] Timeout: {}".format(e)) result["content"] = "我没有收到你的消息" if need_retry: time.sleep(5) elif "connection" in error_str or "network" in error_str: logger.warn("[CLAUDE_API] APIConnectionError: {}".format(e)) need_retry = False result["content"] = "我连接不到你的网络" else: logger.warn("[CLAUDE_API] Exception: {}".format(e)) need_retry = False self.sessions.clear_session(session.session_id) if need_retry: logger.warn("[CLAUDE_API] 第{}次重试".format(retry_count + 1)) return self.reply_text(session, retry_count + 1, tools) else: return result def _model_mapping(self, model) -> str: if model == "claude-3-opus": return const.CLAUDE_3_OPUS elif model == "claude-3-sonnet": return const.CLAUDE_3_SONNET elif model == "claude-3-haiku": return const.CLAUDE_3_HAIKU elif model == "claude-3.5-sonnet": return const.CLAUDE_35_SONNET return model def _get_max_tokens(self, model: str) -> int: """ Get max_tokens for the model. Reference from pi-mono: - Claude 3.5/3.7: 8192 - Claude 3 Opus: 4096 - Default: 8192 """ if model and (model.startswith("claude-3-5") or model.startswith("claude-3-7")): return 8192 elif model and model.startswith("claude-3") and "opus" in model: return 4096 elif model and (model.startswith("claude-sonnet-4") or model.startswith("claude-opus-4")): return 64000 return 8192 def call_with_tools(self, messages, tools=None, stream=False, **kwargs): """ Call Claude API with tool support for agent integration Args: messages: List of messages tools: List of tool definitions stream: Whether to use streaming **kwargs: Additional parameters Returns: Formatted response compatible with OpenAI format or generator for streaming """ actual_model = self._model_mapping(conf().get("model")) # Extract system prompt from messages if present system_prompt = kwargs.get("system", conf().get("character_desc", "")) claude_messages = [] for msg in messages: if msg.get("role") == "system": system_prompt = msg["content"] else: claude_messages.append(msg) request_params = { "model": actual_model, "max_tokens": kwargs.get("max_tokens", self._get_max_tokens(actual_model)), "messages": claude_messages, "stream": stream } if system_prompt: request_params["system"] = system_prompt if tools: request_params["tools"] = tools try: if stream: return self._handle_stream_response(request_params) else: return self._handle_sync_response(request_params) except Exception as e: logger.error(f"Claude API call error: {e}") if stream: # Return error generator for stream def error_generator(): yield { "error": True, "message": str(e), "status_code": 500 } return error_generator() else: # Return error response for sync return { "error": True, "message": str(e), "status_code": 500 } def _handle_sync_response(self, request_params): """Handle synchronous Claude API response""" # Prepare headers headers = { "x-api-key": self.api_key, "anthropic-version": "2023-06-01", "content-type": "application/json" } # Make HTTP request proxies = {"http": self.proxy, "https": self.proxy} if self.proxy else None response = requests.post( f"{self.api_base}/messages", headers=headers, json=request_params, proxies=proxies ) if response.status_code != 200: raise Exception(f"API request failed: {response.status_code} - {response.text}") claude_response = response.json() # Extract content blocks text_content = "" tool_calls = [] content_blocks = claude_response.get("content", []) for block in content_blocks: if block.get("type") == "text": text_content += block.get("text", "") elif block.get("type") == "tool_use": tool_calls.append({ "id": block.get("id", ""), "type": "function", "function": { "name": block.get("name", ""), "arguments": json.dumps(block.get("input", {})) } }) # Build message in OpenAI format message = { "role": "assistant", "content": text_content } if tool_calls: message["tool_calls"] = tool_calls # Format response to match OpenAI structure usage = claude_response.get("usage", {}) formatted_response = { "id": claude_response.get("id", ""), "object": "chat.completion", "created": int(time.time()), "model": claude_response.get("model", request_params["model"]), "choices": [ { "index": 0, "message": message, "finish_reason": claude_response.get("stop_reason", "stop") } ], "usage": { "prompt_tokens": usage.get("input_tokens", 0), "completion_tokens": usage.get("output_tokens", 0), "total_tokens": usage.get("input_tokens", 0) + usage.get("output_tokens", 0) } } return formatted_response def _handle_stream_response(self, request_params): """Handle streaming Claude API response using HTTP requests""" # Prepare headers headers = { "x-api-key": self.api_key, "anthropic-version": "2023-06-01", "content-type": "application/json" } # Add stream parameter request_params["stream"] = True # Track tool use state tool_uses_map = {} # {index: {id, name, input}} current_tool_use_index = -1 stop_reason = None # Track stop reason from Claude try: # Make streaming HTTP request proxies = {"http": self.proxy, "https": self.proxy} if self.proxy else None response = requests.post( f"{self.api_base}/messages", headers=headers, json=request_params, proxies=proxies, stream=True ) if response.status_code != 200: error_text = response.text try: error_data = json.loads(error_text) error_msg = error_data.get("error", {}).get("message", error_text) except: error_msg = error_text or "Unknown error" yield { "error": True, "status_code": response.status_code, "message": error_msg } return # Process streaming response for line in response.iter_lines(): if line: line = line.decode('utf-8') if line.startswith('data: '): line = line[6:] # Remove 'data: ' prefix if line == '[DONE]': break try: event = json.loads(line) event_type = event.get("type") if event_type == "content_block_start": # New content block block = event.get("content_block", {}) if block.get("type") == "tool_use": current_tool_use_index = event.get("index", 0) tool_uses_map[current_tool_use_index] = { "id": block.get("id", ""), "name": block.get("name", ""), "input": "" } elif event_type == "content_block_delta": delta = event.get("delta", {}) delta_type = delta.get("type") if delta_type == "text_delta": # Text content content = delta.get("text", "") yield { "id": event.get("id", ""), "object": "chat.completion.chunk", "created": int(time.time()), "model": request_params["model"], "choices": [{ "index": 0, "delta": {"content": content}, "finish_reason": None }] } elif delta_type == "input_json_delta": # Tool input accumulation if current_tool_use_index >= 0: tool_uses_map[current_tool_use_index]["input"] += delta.get("partial_json", "") elif event_type == "message_delta": # Extract stop_reason from delta delta = event.get("delta", {}) if "stop_reason" in delta: stop_reason = delta.get("stop_reason") logger.info(f"[Claude] Stream stop_reason: {stop_reason}") # Message complete - yield tool calls if any if tool_uses_map: for idx in sorted(tool_uses_map.keys()): tool_data = tool_uses_map[idx] yield { "id": event.get("id", ""), "object": "chat.completion.chunk", "created": int(time.time()), "model": request_params["model"], "choices": [{ "index": 0, "delta": { "tool_calls": [{ "index": idx, "id": tool_data["id"], "type": "function", "function": { "name": tool_data["name"], "arguments": tool_data["input"] } }] }, "finish_reason": stop_reason }] } elif event_type == "message_stop": # Final event - log completion logger.debug(f"[Claude] Stream completed with stop_reason: {stop_reason}") except json.JSONDecodeError: continue except requests.RequestException as e: logger.error(f"Claude streaming request error: {e}") yield { "error": True, "message": f"Connection error: {str(e)}", "status_code": 0 } except Exception as e: logger.error(f"Claude streaming error: {e}") yield { "error": True, "message": str(e), "status_code": 500 }
zhayujie/chatgpt-on-wechat
41,284
CowAgent是基于大模型的超级AI助理,能主动思考和任务规划、访问操作系统和外部资源、创造和执行Skills、拥有长期记忆并不断成长。同时支持飞书、钉钉、企业微信应用、微信公众号、网页等接入,可选择OpenAI/Claude/Gemini/DeepSeek/ Qwen/GLM/Kimi/LinkAI,能处理文本、语音、图片和文件,可快速搭建个人AI助手和企业数字员工。
Python
zhayujie
Minimal Future Tech