bot.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. #!/usr/bin/env python3
  2. # encoding:utf-8
  3. import os
  4. import time
  5. import json
  6. import wave
  7. import queue
  8. import threading
  9. import traceback
  10. import sys
  11. import pjsua2 as pj
  12. from enum import Enum
  13. from src.core.callcenter import registry
  14. from src.core.callcenter.cache import Cache
  15. from src.core.datasource import SIP_SERVER, SERVE_HOST
  16. from src.core.voip.constant import *
  17. import requests
  18. from src.core.callcenter.api import BotChatRequest,ChatMessage
  19. from src.core import singleton_keys
  20. from src.core.callcenter.snowflake import Snowflake
  21. from src.core.callcenter.data_handler import *
  22. calls = {}
  23. # recording_file = '/code/src/core/voip/incoming_call.wav'
  24. # player_file1 = '/code/src/core/voip/test111.wav'
  25. # player_file2 = '/code/src/core/voip/test222.wav'
  26. class BotStatus(Enum):
  27. # 等待用户讲话,未超时
  28. wait_speaking_not_timeout = 1
  29. # 等待用户讲话,已超时但用户仍在持续讲话
  30. wait_speaking_timeout_user_speaking = 2
  31. # 机器人讲话过程中
  32. speaking = 3
  33. # 等待用户讲话结束
  34. wait_user_speaking_end = 4
  35. # 等待大模型输出
  36. wait_gpt_return = 5
  37. class UserStatus(Enum):
  38. # ASR返回值为sentenceBegin后将状态置为Speaking
  39. speaking = 1
  40. # ASR返回值为sentenceEnd后,将状态置为Silence
  41. silence = 2
  42. class MyAudioMediaPort(pj.AudioMediaPort):
  43. def __init__(self, call, aud_media=None, asr=None):
  44. pj.AudioMediaPort.__init__(self)
  45. # # 打开一个 .pcm 文件来保存音频流(可选:保存为 .wav)
  46. # self.wav = wave.open(f"{recording_file}", "wb")
  47. # self.wav.setnchannels(1)
  48. # self.wav.setsampwidth(2) # 假设每个样本是 16 位(2 字节)
  49. # self.wav.setframerate(16000)
  50. print("MyAudioMediaPort::come in, debugger")
  51. self.call = call
  52. self.aud_media = aud_media
  53. self.asr = asr
  54. self.user_asr_texts = []
  55. def onFrameRequested(self, frame):
  56. print("Request audio frame:", frame)
  57. def onFrameReceived(self, frame):
  58. # self.wav.writeframes(bytes(frame.buf))
  59. # print("Received audio frame:", frame.buf, frame.size)
  60. if self.asr: # 如果ASR实例存在,则发送音频数据
  61. self.asr.send_audio(frame.buf)
  62. try:
  63. asr_text = self.get_asr_text()
  64. play_complete = self.call.is_play_complete()
  65. current_time = time.time() # 实时当前时间
  66. if self.call.inputType == '1.0':
  67. time_difference = int(current_time - self.call.inputLongStart)
  68. # print('current_time - self.call.inputLongStart:',time_difference > 35, self.call.txtLock , play_complete)
  69. if time_difference > 35 and play_complete:
  70. self.user_asr_texts.append(f"DTMF({self.call.digit})DTMF")
  71. user_asr_text = self.user_asr_texts[0] if len(self.user_asr_texts) == 1 else '###'.join(self.user_asr_texts)
  72. self.user_asr_texts.clear()
  73. self.call.chat(user_asr_text)
  74. # print("测试超长", user_asr_text)
  75. elif asr_text:
  76. self.user_asr_texts.append(asr_text)
  77. if time_difference > int(self.call.wait_time):
  78. self.call.reset_wait_time()
  79. else:
  80. if asr_text and not play_complete:
  81. self.user_asr_texts.append(asr_text)
  82. if (asr_text and play_complete) or (play_complete and self.user_asr_texts):
  83. if asr_text:
  84. self.user_asr_texts.append(asr_text)
  85. user_asr_text = self.user_asr_texts[0] if len(self.user_asr_texts) == 1 else '###'.join(self.user_asr_texts)
  86. self.user_asr_texts.clear()
  87. self.call.chat(user_asr_text)
  88. if self.call.wait_time and self.call.wait_time != "0" and play_complete and not asr_text:
  89. self.call.wait_time_check(current_time, self.call.wait_time)
  90. message_queue_size = self.call.message_queue.qsize()
  91. if (message_queue_size > 0 and not self.call.cur_player_file) or (message_queue_size > 0 and play_complete):
  92. # self.call.logger.info('onFrameReceived:message_queue_size=', message_queue_size, 'play_complete=', play_complete, asr_text)
  93. self.call.cur_player_file, self.call.wait_time, self.call.inputType,self.call.action, self.call.node_id = self.get_player_file()
  94. # 重置播放完成标志和超时计时器,确保新的播放从头开始计时
  95. self.call.reset_wait_time()
  96. self.call.send_bot_speaker(self.call.cur_player_file)
  97. except:
  98. pass
  99. def get_asr_text(self):
  100. try:
  101. asr_text = self.call.user_asr_text_queue.get(block=False)
  102. self.call.logger.info('get_asr_text: %s', asr_text)
  103. return asr_text
  104. except:
  105. pass
  106. def get_player_file(self):
  107. try:
  108. message = self.call.message_queue.get(block=False)
  109. player_file = [item.voice_url for item in message.contents if item.content_type == 'voice']
  110. return player_file, message.wait_time, message.inputType, message.action, message.node_id
  111. except Exception as e:
  112. traceback.print_exc()
  113. class MyAudioMediaPlayer(pj.AudioMediaPlayer):
  114. def __init__(self, player_id, sink, on_complete=None):
  115. pj.AudioMediaPlayer.__init__(self)
  116. self.player_id = player_id
  117. self.sink = sink
  118. self.on_complete = on_complete
  119. def onEof2(self):
  120. # self.stopTransmit(self.sink)
  121. if self.on_complete:
  122. self.on_complete(self.player_id)
  123. # Subclass to extend the Account and get notifications etc.
  124. class Account(pj.Account):
  125. def __init__(self, agent, user_part, **kwargs):
  126. pj.Account.__init__(self)
  127. self.agent = agent
  128. self.user_part = user_part
  129. self.calls = {}
  130. self.kwargs = kwargs
  131. def onRegState(self, prm):
  132. ai = self.getInfo()
  133. print("***OnRegState: " + prm.reason, ai.id,ai.isDefault,ai.uri,ai.regIsConfigured,ai.regIsActive,ai.regExpiresSec,ai.regStatus,ai.regStatusText,ai.regLastErr,ai.onlineStatus,ai.onlineStatusText)
  134. def onIncomingCall(self, prm):
  135. ai = self.getInfo()
  136. print("***onIncomingCall: ", prm.callId, ai.id,ai.isDefault,ai.uri,ai.regIsConfigured,ai.regIsActive,ai.regExpiresSec,ai.regStatus,ai.regStatusText,ai.regLastErr,ai.onlineStatus,ai.onlineStatusText)
  137. call = MyCall(self.agent, self, self.user_part, prm.callId, **self.kwargs)
  138. call_op_param = pj.CallOpParam(True)
  139. call_op_param.statusCode = pj.PJSIP_SC_OK
  140. call.answer(call_op_param)
  141. self.calls[prm.callId] = call
  142. class MyCall(pj.Call):
  143. def __init__(self, agent, acc, user_part, call_id, **kwargs):
  144. pj.Call.__init__(self, acc, call_id)
  145. self.agent = agent
  146. self.logger = agent.logger
  147. self.user_part = user_part
  148. self.call_id = call_id
  149. self.kwargs = kwargs
  150. self.aud_media = None
  151. self.audio_port = None
  152. self.audio_player = None
  153. self.asr = None
  154. self.session_id = kwargs.get('variable_sip_h_P-LIBRA-CallId')
  155. self.device_id = kwargs.get('variable_sip_h_P-LIBRA-DeviceId')
  156. self.call_phone = kwargs.get("Caller-Caller-ID-Number")
  157. self.logger.info("self.session_id:%s, self.call_phone:%s", self.session_id,self.call_phone)
  158. self.taskId = "10001"
  159. # self.scripts = build_demo_script()
  160. self.user_asr_text_queue = queue.Queue(maxsize=100)
  161. self.message_queue = queue.Queue(maxsize=3)
  162. self.player_complete_dict = {}
  163. self.wait_time = None
  164. self.inputType = None #记录按键类型 1为长按键类型
  165. self.digit = '' # 存储长按键内容
  166. self.action = None
  167. self.node_id= 'start'
  168. self.cur_player_file = None #当前播放的文件
  169. from src.core.voip.asr import TestSt
  170. self.asr = TestSt(call_id, message_receiver=self.on_receiver_asr_result) # 创建ASR实例
  171. self.asr.start() # 启动ASR线程
  172. self.start_time = time.time() # 当前机器人对话开始时间
  173. # 超时设置
  174. self.play_start_time = time.time() # 倒计时开始时间
  175. self.play_complete_flag = False # 倒计时开始标志
  176. self.txtLock = False
  177. self.inputLongStart = time.time() #长按键开始时间
  178. self.inter_action_total = 0
  179. self.statistics_lock = False
  180. def wait_time_check(self, current_time, wait_time):
  181. try:
  182. # 确保 wait_time 是整数类型
  183. wait_time = int(wait_time)
  184. # 如果播放尚未完成,重置标志并返回
  185. if not self.play_complete_flag:
  186. self.play_complete_flag = True
  187. self.play_start_time = current_time
  188. # print(f"开始计时: {self.play_start_time}")
  189. elapsed_time = int(current_time - self.play_start_time)
  190. # print(f"当前时间: {current_time}, 已过时间: {elapsed_time}, 最大等待时间: {wait_time}")
  191. if elapsed_time > wait_time:
  192. # self.user_asr_text_queue.put("ASR408error")
  193. self.chat('ASR408error')
  194. registry.BOT_ASR_408.labels(self.taskId).inc()
  195. except ValueError as e:
  196. self.logger.info(f"无效的等待时间参数: {wait_time}, 错误: {e}")
  197. self.reset_wait_time()
  198. def reset_wait_time(self):
  199. self.play_complete_flag = False # 重置播放完成标志
  200. self.play_start_time = None # 重置开始计时时间
  201. def is_play_complete(self): #语音机器人是否播放结束
  202. if self.cur_player_file:
  203. player_id = murmur3_32(self.cur_player_file)
  204. return self.player_complete_dict.get(player_id)
  205. def onDtmfDigit(self, prm):
  206. # 判断是否播放完成 否则不记录用户说的内容
  207. if not self.is_play_complete():
  208. return
  209. digit = prm.digit
  210. self.reset_wait_time()
  211. # 假设为超长类型按键 把用户输入的按键进行拼接 如果为# 则把用户输入所有按键放入队列并发送文本机器人
  212. # 如果为非正常按键服务 输入以后直接发送文本机器人
  213. if self.inputType == '1.0':
  214. if digit != '#':
  215. self.digit += digit
  216. elif digit == '#':
  217. # self.user_asr_text_queue.put(f"DTMF({self.digit})DTMF")
  218. self.chat(f"DTMF({self.digit})DTMF")
  219. else:
  220. self.user_asr_text_queue.put(f"DTMF({digit})DTMF")
  221. def onCallState(self, prm):
  222. call_info = self.getInfo()
  223. # pj.PJSIP_INV_STATE_NULL
  224. # pj.PJSIP_INV_STATE_CALLING
  225. # pj.PJSIP_INV_STATE_INCOMING
  226. # pj.PJSIP_INV_STATE_EARLY
  227. # pj.PJSIP_INV_STATE_CONNECTING
  228. # pj.PJSIP_INV_STATE_CONFIRMED
  229. # pj.PJSIP_INV_STATE_DISCONNECTED
  230. if call_info.state == pj.PJSIP_INV_STATE_CONFIRMED:
  231. # 当呼叫状态为已确认(即接通)
  232. self.bot_say_hello()
  233. if call_info.state == pj.PJSIP_INV_STATE_DISCONNECTED:
  234. self.logger.info("通话结束:%s", self.user_part)
  235. self.release()
  236. def onCallMediaState(self, prm):
  237. call_info = self.getInfo()
  238. # print("Call Media state: ", call_info.stateText)
  239. for media in call_info.media:
  240. if media.type == pj.PJMEDIA_TYPE_AUDIO and \
  241. (media.status == pj.PJSUA_CALL_MEDIA_ACTIVE):
  242. self.logger.info("Call Media state 111: %s", call_info.stateText)
  243. self.aud_media = self.getAudioMedia(media.index)
  244. try:
  245. # 建立双向通道
  246. self.receive_user_speaker()
  247. # self.bot_say_hello()
  248. except Exception as e:
  249. traceback.print_exc()
  250. def receive_user_speaker(self):
  251. self.audio_port = MyAudioMediaPort(self, self.aud_media, self.asr)
  252. self.audio_port.createPort("Incoming Call Port", build_audio_format())
  253. self.aud_media.startTransmit(self.audio_port)
  254. def send_bot_speaker(self, player_file):
  255. if not player_file :
  256. return
  257. player_id = murmur3_32(player_file)
  258. self.player_complete_dict[player_id] = False
  259. # print('self.player_complete_dict[player_id]D:', player_id, player_file, self.player_complete_dict[player_id])
  260. self.logger.info(f"[DEBUG] Sending bot speaker, player_file: {player_file}, player_id: {player_id}")
  261. self.audio_player = MyAudioMediaPlayer(player_id, self.aud_media, on_complete=self.on_media_player_complete)
  262. # self.audio_player.createPlayer(player_file[0], pj.PJMEDIA_FILE_NO_LOOP)
  263. self.audio_player.createPlaylist(player_file, f'my_hello_playlist{player_id}', pj.PJMEDIA_FILE_NO_LOOP)
  264. self.audio_player.startTransmit(self.aud_media)
  265. def on_receiver_asr_result(self, message, *args):
  266. # 判断是否播放完成 否则不记录用户说的内容
  267. if not self.is_play_complete():
  268. return
  269. message = json.loads(message)
  270. if message["header"]["status"] == 20000000:
  271. if message["header"]["name"] == "SentenceEnd":
  272. result = message["payload"]["result"]
  273. # self.logger.info("asr返回内容Result:%s", result)
  274. self.user_asr_text_queue.put(result)
  275. elif message["header"]["name"] == "TranscriptionResultChanged":
  276. self.reset_wait_time()
  277. else:
  278. self.logger.info(f"Status is not {message['header']['status']}")
  279. registry.ASR_ERRORS.labels(message['header']['status']).inc()
  280. def on_media_player_complete(self, player_id):
  281. self.logger.info('player complete')
  282. self.player_complete_dict[player_id] = True
  283. self.digit = ''
  284. self.inputLongStart = time.time()
  285. #播放完毕执行的动作
  286. self.say_end_action(self.action)
  287. def bot_say_hello(self):
  288. self.chat(user_asr_text="start")
  289. def chat(self, user_asr_text=None):
  290. # 调用文本机器人接口
  291. ToTextBotAgent(user_asr_text,self)
  292. def say_end_action(self, action):
  293. self.logger.info('handling_release %s', action.action_code)
  294. action_code = action.action_code
  295. if action_code == 'hang': # 挂断
  296. self.agent.hangup(self.user_part)
  297. self.end_statistics()
  298. elif action_code == 'transfer': # 转人工
  299. self.agent.transfer(user_part=self.user_part, call_id=self.session_id, device_id=self.device_id)
  300. self.end_statistics()
  301. #更新通话记录
  302. self.agent.dataHandleServer.update_record(self.session_id, service_category=2)
  303. def end_statistics(self):
  304. if not self.statistics_lock:
  305. self.statistics_lock = True
  306. self.logger.info(f"self.inter_action_total:{self.inter_action_total}")
  307. latency = (time.time() - self.start_time)
  308. registry.BOT_CALL_DURATION.labels(self.taskId).observe(latency)
  309. registry.BOT_INTERACTION_ROUNDS.labels(self.taskId).observe(self.inter_action_total)
  310. def release(self):
  311. self.logger.info('liuwei::debugger::release:: come in ')
  312. if self.audio_port:
  313. # self.audio_port.stopTransmit()
  314. self.audio_port = None # 或调用相关销毁方法
  315. if self.audio_player:
  316. # self.audio_player.stopTransmit()
  317. self.audio_player = None # 或调用播放器停止方法
  318. if self.aud_media:
  319. # self.audio_media.stopTransmit()
  320. self.aud_media = None
  321. # self.asr.close()
  322. # 远程挂机之后要将分机号回收
  323. self.agent.hangup(self.user_part)
  324. # self.agent.release(self.user_part)
  325. self.end_statistics()
  326. class ToTextBotAgent:
  327. def __init__(self, user_asr_text, call_agent):
  328. if not user_asr_text or (call_agent.action and call_agent.action.action_code != 'normal'):
  329. # print("ASR文本为空,终止执行。")
  330. return
  331. self.call_agent = call_agent
  332. self.request_data = BotChatRequest(
  333. nodeId=self.call_agent.node_id,
  334. userId=self.call_agent.call_phone,
  335. sessionId= self.call_agent.session_id,
  336. recordId="",
  337. taskId=self.call_agent.taskId,
  338. asrText=user_asr_text,
  339. ext= None
  340. )
  341. self.call_agent.logger.info("user_asr_text发送结果: %s", user_asr_text)
  342. if user_asr_text != 'ASR408error':
  343. self.call_agent.inter_action_total += 1
  344. # 发送请求并处理响应
  345. # self.test_request(self.request_data)
  346. self.to_quest(self.request_data)
  347. def to_quest(self, request: BotChatRequest):
  348. headers = {'Content-Type': 'application/json'}
  349. request_data = request.to_json_string()
  350. url = f"http://{SERVE_HOST}:40072/botservice"
  351. start_time = time.time()
  352. self.call_agent.logger.info(f"请求数据:{request_data},url:{url}")
  353. try:
  354. response = requests.post(url=url, json=json.loads(request_data), headers=headers, timeout=10) # 使用占位URL
  355. self.call_agent.logger.info(f"chat::request:{request_data}, response:{response.text}")
  356. if response.status_code == 200:
  357. response_data = response.json()
  358. if "data" in response_data and response_data["code"]==0:
  359. data = response_data["data"]
  360. parsed_response = ChatMessage.from_json(data)
  361. self.call_agent.message_queue.put(parsed_response)
  362. else:
  363. self.call_agent.logger.info("响应中没有 'data' 字段")
  364. else:
  365. # 错误处理
  366. self.call_agent.logger.info(f"请求失败,状态码: {response.status_code}, 响应内容: {response.text}")
  367. except requests.RequestException as e:
  368. self.call_agent.logger.info(f"请求发生异常: {e}")
  369. finally:
  370. latency = (time.time() - start_time)
  371. registry.BOT_REQUEST_COUNT.inc()
  372. registry.BOT_REQUEST_LATENCY.labels(request.taskId).observe(latency)
  373. # 模拟接口请求返回
  374. def test_request(self, params: BotChatRequest):
  375. self.call_agent.logger.info("test_request::params= %s", params)
  376. response_data = {
  377. "node_id": "1.0",
  378. "contents": [],
  379. "wait_time": "6",
  380. "action": {
  381. "action_code": "normal",
  382. "action_content": "正常通话"
  383. },
  384. "inputType": "0"
  385. }
  386. self.call_agent.logger.info("asrText: %s", params.asrText)
  387. if params.asrText == 'start': #欢迎语
  388. response_data['contents'].append({
  389. "content_type": "voice",
  390. "content": "",
  391. "voice_url": '/code/src/core/voip/scripts/1_00.wav',
  392. "voice_content": "五一北京到上海的高铁票还有吗?"
  393. })
  394. response_data['inputType'] = '1.0'
  395. elif params.asrText == 'ASR408error': #超时执行
  396. response_data['contents'].append({
  397. "content_type": "voice",
  398. "content": "",
  399. "voice_url": '/code/src/core/voip/scripts/4_00.wav',
  400. "voice_content": "waitTime超时"
  401. })
  402. elif "DTMF" in params.asrText and self.call_agent.inputType =='1.0': #长按键超30s执行
  403. response_data['contents'].append({
  404. "content_type": "voice",
  405. "content": "",
  406. "voice_url": '/code/src/core/voip/scripts/2_00.wav',
  407. "voice_content": "sds"
  408. })
  409. else :
  410. response_data['contents'] = [
  411. {
  412. "content_type": "voice",
  413. "content": "",
  414. "voice_url": '/code/src/core/voip/test111.wav',
  415. "voice_content": "测试第二个录音文件"
  416. },
  417. {
  418. "content_type": "voice",
  419. "content": "",
  420. "voice_url": '/code/src/core/voip/test222.wav',
  421. "voice_content": "五一北京到上海的高铁票还有吗?"
  422. }
  423. ]
  424. try:
  425. parsed_response = ChatMessage.from_json(response_data)
  426. self.call_agent.message_queue.put(parsed_response)
  427. except Exception as e:
  428. traceback.print_exc() # 打印完整的错误信息
  429. return None
  430. @singleton_keys
  431. class BotAgent:
  432. def __init__(self, app, user_part_range=range(1001, 1011), host="192.168.100.159", port="5060", password="slibra@#123456"):
  433. self.app = app
  434. self.logger = app.logger
  435. self.user_part_range, self.host, self.port, self.password = user_part_range, host, port, password
  436. self.user_part_pool = queue.Queue(maxsize=len(user_part_range))
  437. self.accounts = {}
  438. self.calls = {}
  439. self.ep = pj.Endpoint()
  440. self.is_stopping = False
  441. self.acd_service = None
  442. self.cache = Cache(app)
  443. self.dataHandleServer = DataHandleServer(app)
  444. threading.Thread(target=self.create_pjsua2, daemon=True).start()
  445. def create_pjsua2(self):
  446. # Create and initialize the library
  447. ep_cfg = pj.EpConfig()
  448. ep_cfg.uaConfig.threadCnt = 12
  449. ep_cfg.uaConfig.mainThreadOnly = False
  450. ep_cfg.uaConfig.maxCalls = 20
  451. ep_cfg.uaConfig.maxAccounts = 20
  452. ep_cfg.medConfig.noVad = True
  453. ep_cfg.logConfig.level = 3
  454. ep_cfg.logConfig.consoleLevel = 3
  455. self.ep.libCreate()
  456. self.ep.libInit(ep_cfg)
  457. aud_dev_mgr = self.ep.audDevManager()
  458. aud_dev_mgr.setNullDev() # 使用虚拟音频设备(如果没有实际设备)
  459. # Set up media configuration, particularly jitter buffer
  460. media_cfg = pj.MediaConfig()
  461. media_cfg.jbMinPre = 4 # Minimum pre-fetch frames
  462. media_cfg.jbMaxPre = 16 # Maximum pre-fetch frames
  463. media_cfg.noVad = True # Disable Voice Activity Detection if needed
  464. self.ep.medConfig = media_cfg # Apply media config to endpoint
  465. # Create SIP transport. Error handling sample is shown
  466. sipTpConfig = pj.TransportConfig()
  467. sipTpConfig.port = 30506
  468. self.ep.transportCreate(pj.PJSIP_TRANSPORT_UDP, sipTpConfig)
  469. # Start the library
  470. self.ep.libStart()
  471. for user_part in self.user_part_range:
  472. acfg = pj.AccountConfig()
  473. acfg.idUri = f"sip:{user_part}@{self.host}:{self.port}"
  474. acfg.regConfig.registrarUri = f"sip:{self.host}:{self.port}"
  475. cred = pj.AuthCredInfo("digest", "*", f"{user_part}", 0, self.password)
  476. acfg.sipConfig.authCreds.append(cred)
  477. acfg.regConfig.timeoutSec = 86400 # 注册超时时间(秒)
  478. acfg.regConfig.retryIntervalSec = 10 # 重试间隔时间(秒)
  479. acfg.regConfig.firstRetryIntervalSec = 10 # 首次重试间隔时间(秒)
  480. # acfg.natConfig.iceEnabled = True
  481. # acfg.natConfig.turnEnabled = True
  482. # acfg.natConfig.turnServer = "stun:pbx.fuxicarbon.com:3478"
  483. # acfg.natConfig.turnUsername = "username"
  484. # acfg.natConfig.turnPassword = "password"
  485. # Create the account
  486. acc = Account(self, user_part=user_part)
  487. acc.create(acfg)
  488. self.user_part_pool.put(user_part)
  489. self.accounts[user_part] = acc
  490. while not self.is_stopping:
  491. registry.BOT_AGENT_LIVES.set(self.user_part_pool.qsize())
  492. self.logger.info("------------------>pjsua::%s", len(self.accounts))
  493. self.ep.libHandleEvents(100)
  494. def transfer(self, user_part, call_id, device_id, service_id='00000000000000000'):
  495. if self.acd_service:
  496. self.acd_service.transfer_to_agent(call_id, device_id, service_id)
  497. # sip_headers = {'P-LIBRA-HangUpReason': 'transferToAgent', 'P-LIBRA-ServiceId': service_id}
  498. try_count = 100
  499. while try_count >0:
  500. if self.cache.get_after_play_hold_music(call_id):
  501. self.hangup(user_part)
  502. break
  503. time.sleep(0.1)
  504. def hangup(self, user_part, reason="NORMAL_CLEARING", **sip_headers):
  505. call_op_param = pj.CallOpParam(True)
  506. call_op_param.statusCode = pj.PJSIP_SC_OK
  507. call_op_param.reason = reason
  508. call_op_param.txOption = pj.SipTxOption()
  509. sip_header_vector = pj.SipHeaderVector()
  510. for k, v in sip_headers.items():
  511. _sip_header = pj.SipHeader()
  512. _sip_header.hName = str(k)
  513. _sip_header.hValue = str(v)
  514. self.logger.info('hangup, header_name=%s, header_value=%s'%(k, v))
  515. sip_header_vector.push_back(_sip_header)
  516. call_op_param.txOption.headers = sip_header_vector
  517. acc = self.accounts.get(user_part)
  518. if acc:
  519. for k, v in acc.calls.items():
  520. try:
  521. v.hangup(call_op_param)
  522. except:
  523. traceback.print_exc()
  524. # 机器人主动挂机回收分机号
  525. self.release(user_part)
  526. def register(self, **kwargs):
  527. self.logger.info('register,come in, pool.size :%d', self.user_part_pool.qsize())
  528. user_part = self.user_part_pool.get()
  529. acc = self.accounts.get(user_part)
  530. self.logger.info('register, user_part :%d, pool.size :%d', user_part, self.user_part_pool.qsize())
  531. if acc:
  532. self.logger.info('register==========> %s', acc.getId())
  533. # ps = pj.PresenceStatus()
  534. # ps.status = pj.PJSUA_BUDDY_STATUS_ONLINE
  535. # ps.activity = pj.PJRPID_ACTIVITY_AWAY
  536. # ps.note = "Away"
  537. # acc.setOnlineStatus(ps)
  538. # acc.setRegistration(renew=True)
  539. acc.kwargs = kwargs
  540. return user_part
  541. def unregister(self, user_part):
  542. acc = self.accounts.get(user_part)
  543. if acc:
  544. acc.setRegistration(renew=False)
  545. # 用户远程挂机回收分机号
  546. self.release(user_part)
  547. def release(self, user_part):
  548. if not user_part:
  549. self.logger.info("release, user_part is None")
  550. return
  551. def element_in_queue(q, element):
  552. with q.mutex: # 确保线程安全
  553. for item in list(q.queue): # 将队列转换为列表进行遍历
  554. if item == element:
  555. return True
  556. return False
  557. if element_in_queue(self.user_part_pool, user_part):
  558. self.logger.info("release, already exists, user_part :%d, pool.size :%d", user_part, self.user_part_pool.qsize())
  559. return
  560. self.user_part_pool.put(user_part)
  561. self.logger.info("release, user_part :%d, pool.size :%d", user_part, self.user_part_pool.qsize())
  562. def destroy(self):
  563. self.is_stopping = True
  564. # Destroy the library
  565. self.ep.libDestroy()
  566. def __del__(self):
  567. self.destroy()
  568. # if __name__ == '__main__':
  569. # import logging
  570. # logger = logging.getLogger('voip')
  571. # bot = BotAgent(logger)