重大版本调整:gewechat兼容。
This commit is contained in:
122
gewechat/api/callback.py
Normal file
122
gewechat/api/callback.py
Normal file
@@ -0,0 +1,122 @@
|
||||
from fastapi import APIRouter, Request
|
||||
from gewechat.call_back_message.message import WxMessage, MessageType, AppMessageType
|
||||
import logging
|
||||
|
||||
from robot import Robot
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 存储Robot实例的字典,以appid为键
|
||||
robot_instances = {}
|
||||
|
||||
|
||||
def register_robot(appid, robot_instance):
|
||||
"""注册Robot实例"""
|
||||
robot_instances[appid] = robot_instance
|
||||
logger.info(f"已注册appid为{appid}的Robot实例")
|
||||
|
||||
|
||||
@router.post("/gewechat/callback")
|
||||
async def callback(request: Request):
|
||||
"""接收微信消息回调"""
|
||||
try:
|
||||
# 获取原始JSON数据
|
||||
json_data = await request.json()
|
||||
|
||||
# 创建消息对象
|
||||
msg = WxMessage.from_json(json_data)
|
||||
|
||||
# 根据消息类型处理
|
||||
if msg.type_name == "AddMsg":
|
||||
await handle_add_message(msg)
|
||||
elif msg.type_name == "ModContacts":
|
||||
await handle_mod_contacts(msg)
|
||||
elif msg.type_name == "DelContacts":
|
||||
await handle_del_contacts(msg)
|
||||
elif msg.type_name == "Offline":
|
||||
await handle_offline(msg)
|
||||
|
||||
return {"code": 0, "message": "success"}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"处理回调消息失败: {str(e)}", exc_info=True)
|
||||
return {"code": -1, "message": f"处理失败: {str(e)}"}
|
||||
|
||||
|
||||
async def handle_add_message(msg: WxMessage):
|
||||
"""处理新消息"""
|
||||
try:
|
||||
# 获取对应的Robot实例
|
||||
robot: Robot = robot_instances.get(msg.appid)
|
||||
if robot:
|
||||
# 调用Robot的onMsg方法处理消息
|
||||
robot.onMsg(msg)
|
||||
else:
|
||||
logger.warning(f"未找到appid为{msg.appid}的Robot实例")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"处理新消息失败: {str(e)}", exc_info=True)
|
||||
raise
|
||||
|
||||
|
||||
async def handle_mod_contacts(msg: WxMessage):
|
||||
"""处理联系人变更"""
|
||||
logger.info(f"联系人信息变更: {msg.raw_data}")
|
||||
# 获取对应的Robot实例并刷新联系人
|
||||
robot = robot_instances.get(msg.appid)
|
||||
if robot:
|
||||
robot.refresh_contacts()
|
||||
|
||||
|
||||
async def handle_del_contacts(msg: WxMessage):
|
||||
"""处理联系人删除"""
|
||||
logger.info(f"联系人被删除: {msg.raw_data}")
|
||||
# 获取对应的Robot实例并刷新联系人
|
||||
robot = robot_instances.get(msg.appid)
|
||||
if robot:
|
||||
robot.refresh_contacts()
|
||||
|
||||
|
||||
async def handle_offline(msg: WxMessage):
|
||||
"""处理离线通知"""
|
||||
logger.info(f"账号离线: {msg.wxid}")
|
||||
# 可以在这里处理账号离线逻辑
|
||||
|
||||
|
||||
async def handle_text_message(msg: WxMessage):
|
||||
"""处理文本消息"""
|
||||
logger.info(f"收到文本消息: {msg.content.raw_content}")
|
||||
# TODO: 实现文本消息处理逻辑
|
||||
|
||||
|
||||
async def handle_image_message(msg: WxMessage):
|
||||
"""处理图片消息"""
|
||||
image_content = msg.get_image_content()
|
||||
if image_content:
|
||||
logger.info(f"收到图片消息: {image_content.url}")
|
||||
# TODO: 实现图片消息处理逻辑
|
||||
|
||||
|
||||
async def handle_app_message(msg: WxMessage):
|
||||
"""处理应用消息"""
|
||||
app_type = msg.get_app_message_type()
|
||||
if app_type == AppMessageType.LINK:
|
||||
logger.info("收到链接消息")
|
||||
elif app_type == AppMessageType.FILE:
|
||||
logger.info("收到文件消息")
|
||||
elif app_type == AppMessageType.MINIPROGRAM:
|
||||
logger.info("收到小程序消息")
|
||||
# TODO: 实现应用消息处理逻辑
|
||||
|
||||
|
||||
async def handle_system_message(msg: WxMessage):
|
||||
"""处理系统消息"""
|
||||
logger.info(f"收到系统消息: {msg.content.raw_content}")
|
||||
# TODO: 实现系统消息处理逻辑
|
||||
|
||||
|
||||
async def handle_system_notify(msg: WxMessage):
|
||||
"""处理系统通知"""
|
||||
logger.info(f"收到系统通知: {msg.content.raw_content}")
|
||||
# TODO: 实现系统通知处理逻辑
|
||||
85
gewechat/api/start_server.py
Normal file
85
gewechat/api/start_server.py
Normal file
@@ -0,0 +1,85 @@
|
||||
import threading
|
||||
import logging
|
||||
import socket
|
||||
import uvicorn
|
||||
from fastapi import FastAPI
|
||||
|
||||
from gewechat.api.callback import router as callback_router
|
||||
|
||||
# 配置日志
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def is_port_in_use(port, host='0.0.0.0'):
|
||||
"""检查端口是否被占用"""
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
try:
|
||||
s.bind((host, port))
|
||||
return False
|
||||
except socket.error:
|
||||
return True
|
||||
|
||||
def start_fastapi_server(host="0.0.0.0", port=8999):
|
||||
"""启动FastAPI服务器"""
|
||||
# 检查端口是否被占用
|
||||
if is_port_in_use(port, host):
|
||||
logger.warning(f"端口 {port} 已被占用,尝试使用其他端口")
|
||||
# 尝试其他端口
|
||||
for test_port in range(9000, 9100):
|
||||
if not is_port_in_use(test_port, host):
|
||||
port = test_port
|
||||
break
|
||||
else:
|
||||
logger.error("无法找到可用端口,服务器启动失败")
|
||||
return False
|
||||
|
||||
try:
|
||||
app = FastAPI()
|
||||
app.include_router(callback_router)
|
||||
|
||||
# 添加健康检查路由
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {"status": "ok"}
|
||||
|
||||
logger.info(f"正在启动FastAPI服务器,地址: http://{host}:{port}")
|
||||
|
||||
# 使用线程启动uvicorn服务器
|
||||
server_thread = threading.Thread(
|
||||
target=uvicorn.run,
|
||||
args=(app,),
|
||||
kwargs={"host": host, "port": port, "log_level": "info"},
|
||||
daemon=True
|
||||
)
|
||||
server_thread.start()
|
||||
logger.info(f"FastAPI 服务已在 http://{host}:{port} 启动")
|
||||
logger.info(f"回调URL: http://{host}:{port}/gewechat/callback")
|
||||
|
||||
# 返回启动的端口,以便调用者知道实际使用的端口
|
||||
return port
|
||||
except Exception as e:
|
||||
logger.error(f"启动FastAPI服务器失败: {e}", exc_info=True)
|
||||
return False
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 配置日志
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
# 启动服务器
|
||||
port = start_fastapi_server()
|
||||
if port:
|
||||
print(f"服务器启动成功,端口: {port}")
|
||||
print(f"回调URL: http://localhost:{port}/gewechat/callback")
|
||||
print(f"健康检查URL: http://localhost:{port}/health")
|
||||
|
||||
# 保持主线程运行
|
||||
try:
|
||||
import time
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
print("服务器已停止")
|
||||
else:
|
||||
print("服务器启动失败")
|
||||
Reference in New Issue
Block a user