Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
ai
/
ai-workflow
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 97a47fde
authored
Jul 09, 2026
by
sunqi02
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
feat: 添加按手机号发送消息功能,重构相关服务和请求模型
1 parent
14b54102
Hide whitespace changes
Inline
Side-by-side
Showing
4 changed files
with
114 additions
and
2 deletions
workspace/agent-admin/backend/app/customer_info/api.py
workspace/agent-admin/backend/app/customer_info/schema.py
workspace/agent-admin/backend/app/customer_info/send_service.py
workspace/agent-admin/backend/app/main.py
workspace/agent-admin/backend/app/customer_info/api.py
View file @
97a47fd
from
__future__
import
annotations
from
__future__
import
annotations
from
fastapi
import
APIRouter
,
Depends
,
HTTPException
from
fastapi
import
APIRouter
,
Depends
,
HTTPException
,
Request
from
sqlalchemy.orm
import
Session
from
sqlalchemy.orm
import
Session
from
app.agent_core.im_service
import
IMService
from
app.infrastructure.database
import
get_db
from
app.infrastructure.database
import
get_db
from
app.schema.common
import
ApiResponse
,
success_response_payload
,
SuccessFlagData
from
app.schema.common
import
ApiResponse
,
success_response_payload
,
SuccessFlagData
from
app.customer_info.schema
import
CustomerGroupPhoneResponse
,
PhoneBindingSubmitRequest
from
app.customer_info.schema
import
(
CustomerGroupPhoneResponse
,
PhoneBindingSubmitRequest
,
SendByPhoneRequest
,
)
from
app.customer_info.send_service
import
PhoneMessageSender
,
SendByPhoneError
from
app.customer_info.service
import
CustomerInfoService
from
app.customer_info.service
import
CustomerInfoService
router
=
APIRouter
(
prefix
=
"/api/v1/customer-info"
,
tags
=
[
"customer-info"
])
router
=
APIRouter
(
prefix
=
"/api/v1/customer-info"
,
tags
=
[
"customer-info"
])
...
@@ -39,3 +45,30 @@ def get_phone(
...
@@ -39,3 +45,30 @@ def get_phone(
if
record
is
None
:
if
record
is
None
:
raise
HTTPException
(
status_code
=
404
,
detail
=
"未找到匹配的客户群组记录"
)
raise
HTTPException
(
status_code
=
404
,
detail
=
"未找到匹配的客户群组记录"
)
return
success_response_payload
(
200
,
record
)
return
success_response_payload
(
200
,
record
)
def
_get_im_service
(
request
:
Request
)
->
IMService
:
im
=
getattr
(
request
.
app
.
state
,
"im_service"
,
None
)
if
im
is
None
:
raise
HTTPException
(
status_code
=
503
,
detail
=
"IM 服务未就绪"
)
return
im
@router.post
(
"/send-by-phone"
)
async
def
send_by_phone
(
req
:
SendByPhoneRequest
,
request
:
Request
,
db
:
Session
=
Depends
(
get_db
),
):
"""外部服务按手机号查找群组并发送消息。"""
im_service
=
_get_im_service
(
request
)
sender
=
PhoneMessageSender
(
db
=
db
,
im_service
=
im_service
)
try
:
result
=
await
sender
.
send_by_phone
(
phone
=
req
.
phone
,
content
=
req
.
content
)
except
SendByPhoneError
as
e
:
raise
HTTPException
(
status_code
=
400
,
detail
=
str
(
e
))
if
result
[
"success"
]:
return
success_response_payload
(
200
,
result
)
raise
HTTPException
(
status_code
=
502
,
detail
=
result
[
"message"
])
workspace/agent-admin/backend/app/customer_info/schema.py
View file @
97a47fd
...
@@ -12,6 +12,16 @@ class PhoneBindingSubmitRequest(BaseModel):
...
@@ -12,6 +12,16 @@ class PhoneBindingSubmitRequest(BaseModel):
phone
:
str
=
Field
(
...
,
max_length
=
20
,
description
=
"手机号码"
)
phone
:
str
=
Field
(
...
,
max_length
=
20
,
description
=
"手机号码"
)
class
SendByPhoneRequest
(
BaseModel
):
phone
:
str
=
Field
(
...
,
max_length
=
20
,
description
=
"客户手机号"
)
content
:
str
=
Field
(
...
,
description
=
"消息内容"
)
class
SendByPhoneResponse
(
BaseModel
):
success
:
bool
message
:
str
class
CustomerGroupPhoneResponse
(
BaseModel
):
class
CustomerGroupPhoneResponse
(
BaseModel
):
model_config
=
ConfigDict
(
from_attributes
=
True
)
model_config
=
ConfigDict
(
from_attributes
=
True
)
...
...
workspace/agent-admin/backend/app/customer_info/send_service.py
0 → 100644
View file @
97a47fd
from
__future__
import
annotations
import
logging
from
typing
import
Dict
,
List
,
Tuple
from
sqlalchemy.orm
import
Session
from
sqlalchemy
import
text
from
app.agent_core.im_service
import
IMService
,
IMServiceError
logger
=
logging
.
getLogger
(
__name__
)
class
SendByPhoneError
(
Exception
):
"""Raised when send-by-phone operation fails."""
pass
class
PhoneMessageSender
:
"""通过手机号查找群组并发送消息。"""
# language=MySQL
_QUERY
=
"""
SELECT cgp.group_id, wcg.bot_id
FROM customer_group_phones cgp
JOIN wecom_customer_groups wcg ON cgp.group_id = wcg.group_id
WHERE cgp.phone = :phone AND wcg.is_deleted = 0
"""
def
__init__
(
self
,
db
:
Session
,
im_service
:
IMService
):
self
.
db
=
db
self
.
im_service
=
im_service
def
_lookup_targets
(
self
,
phone
:
str
)
->
List
[
Tuple
[
str
,
str
]]:
"""联表查询获取 phone 对应的 (group_id, bot_id) 对。"""
rows
=
self
.
db
.
execute
(
text
(
self
.
_QUERY
),
{
"phone"
:
phone
})
.
fetchall
()
if
not
rows
:
raise
SendByPhoneError
(
"号码未绑定微信群"
)
return
[(
row
.
group_id
,
row
.
bot_id
)
for
row
in
rows
]
# type: ignore[union-attr]
async
def
send_by_phone
(
self
,
phone
:
str
,
content
:
str
)
->
Dict
[
str
,
object
]:
"""按手机号查找群组并发送消息。"""
targets
=
self
.
_lookup_targets
(
phone
)
results
:
List
[
Tuple
[
str
,
bool
,
str
]]
=
[]
for
group_id
,
bot_id
in
targets
:
try
:
resp
=
await
self
.
im_service
.
send_message
(
bot_id
=
bot_id
,
content
=
content
,
contact_id
=
group_id
,
)
logger
.
info
(
"发送成功: group_id=
%
s, bot_id=
%
s, resp=
%
s"
,
group_id
,
bot_id
,
resp
)
results
.
append
((
group_id
,
True
,
"ok"
))
except
IMServiceError
as
e
:
logger
.
error
(
"发送失败: group_id=
%
s, bot_id=
%
s, err=
%
s"
,
group_id
,
bot_id
,
e
)
results
.
append
((
group_id
,
False
,
str
(
e
)))
success_count
=
sum
(
1
for
_
,
ok
,
_
in
results
if
ok
)
return
{
"success"
:
success_count
>
0
,
"message"
:
f
"处理完成:共 {len(targets)} 个群,成功 {success_count} 个"
,
"details"
:
[
{
"group_id"
:
gid
,
"success"
:
ok
,
"error"
:
msg
if
not
ok
else
None
}
for
gid
,
ok
,
msg
in
results
],
}
workspace/agent-admin/backend/app/main.py
View file @
97a47fd
...
@@ -93,6 +93,8 @@ async def lifespan(app: FastAPI):
...
@@ -93,6 +93,8 @@ async def lifespan(app: FastAPI):
api_key
=
os
.
getenv
(
"IM_API_KEY"
,
settings
.
im
.
api_key
),
api_key
=
os
.
getenv
(
"IM_API_KEY"
,
settings
.
im
.
api_key
),
)
)
app
.
state
.
im_service
=
im_service
agent_hub_instance
=
AgentHub
(
agent_hub_instance
=
AgentHub
(
config_loader
=
config_loader
,
config_loader
=
config_loader
,
session_service
=
session_service
,
session_service
=
session_service
,
...
...
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment