Need help for talk to human agent custom action

hi, i’m trying to create a custom action for talk to human agent and here i have to connect first the chat and wait for message from human agent and if some message get from chatbot then i have to send the message to human agent and get the message from human agent every 10 sec or 5 sec

here is my code , can anybody help me please…


from cgitb import text
from cmath import log
import logging
from operator import index
from unittest import result
from webbrowser import get
import requests
import json
import datetime
from time import time, sleep
from typing import Any, Text, Dict, List
from random import randint, randrange
from rasa_sdk import Action, Tracker
from rasa_sdk.events import SlotSet, ReminderScheduled, ConversationPaused, ConversationResumed, FollowupAction, Restarted, UserUtteranceReverted
from rasa_sdk.executor import CollectingDispatcher
import threading
#import jsonify

logger = logging.getLogger(__name__)

class StepOne(Action):

    def name(self):
        return 'action_transfer_agent'
    
    def getAndsendMessagetoAget(self, p_id, header, tracker, dispatcher, message, cookie):
        user_message=tracker.latest_message['text']
        if user_message is not None:
            url_send_message = 'https://xxxx.xxx/web-chat/send-message/'+p_id
            payload_message = { 
                                "message": user_message,
                                "contentType": "text/plain"
                            }
            result_code=requests.post(url_send_message, data=json.dumps(payload_message), headers=header, verify=False, cookies=cookie)
            #return result_code.status_code
            
        else:
            """
            GET
            retry 10 times with 10 sec sleeps to fetch info
            """
            replies = 0
            url_get_message = 'https://xxxx.xxx/web-chat/message-history/'+p_id
            res_get_message=requests.post(url_get_message, headers=header, verify=False)
            get_response=res_get_message.json()
            mesg=get_response['messages'].pop()
            if(mesg['p_id']!=p_id):
                replies = mesg['value']
            ## poll on replies to fetch the message
            while len(replies) == 0:
                time.sleep(1)
            message = replies
            return {"message": message}
        

    def sendMessagetoAgent(self, p_id, header, message_to_send, cookie):
        url_send_message = 'https://xxxx.xxx/web-chat/send-message/'+p_id
        payload_message = { 
                            "message": message_to_send,
                            "contentType": "text/plain"
                         }
        result_code=requests.post(url_send_message, data=json.dumps(payload_message), headers=header, verify=False, cookies=cookie)
        return result_code.status_code

    def run(self, dispatcher, tracker, domain):

        #SESSION CONNECTION
        headers = {'content-type': 'application/json','Accept-Language':'en-us'}
        url = 'https://xxxx.xxx/connection'
        payload = {
                "userID": "xxxx",
                "password": "xxxxxx"
                }
        res=requests.post(url, data=json.dumps(payload), headers=headers, verify=False)
        get_res=res.json()
        csrfToken=get_res['csrfToken']
        sessionId=get_res['sessionId']
        statusCode= res.status_code

        #CREATE AND CHECK SCHEDULE
        #tracker.update(ConversationPaused()) #converstion paused
        if csrfToken and sessionId:
            gen_full_name=tracker.get_slot("gen_full_name")
            gen_phone_number=tracker.get_slot("gen_phone_number")
            gen_email=tracker.get_slot("gen_email")
            get_programe_type=tracker.get_slot("get_programe_type")
            headers_noti={'Content-Type': 'application/json','Accept-Language':'en-us','token': csrfToken}
            check_scedule_url='https://xxxx.xxx/'+sessionId+'/system/handler-notification'
            payload_schedule={
                "objectId": "sdfasdfasdf",
                "eventId": "xxxxxx",
                "data": [
                    "test 0",
                    "test 1"
                ]
            }
            response_notification=requests.post(check_scedule_url, data=json.dumps(payload_schedule), headers=headers_noti, verify=False, cookies=res.cookies)
            if response_notification.status_code==202:
                #START CHAT
                url_start_chat = 'https://xxxx.xxx/web-chat/startsss'
                payload_chat = {
                            "participantName":"xxxx",
                            "additionalAttributes":{
                                "MobileNumber":"xxxxx",
                                "EmailID":"xxxx"
                            }
                        }
                res_chat=requests.post(url_start_chat, data=json.dumps(payload_chat), headers=headers, verify=False)
                get_res_chat=res_chat.json()
                if get_res_chat['p_id']:
                    ConversationPaused()
                    p_id=get_res_chat['p_id']
                    chatId=get_res_chat['chatId']
                    pollWaitSuggestion=get_res_chat['ccccc']
                    message_to_send= "from dev trying to  Reaching out to a human agent"
                    snd_msg=self.sendMessagetoAgent(p_id, headers, message_to_send, res.cookies)

                    #send & get message
                    message=""
                    while message != "unpause":
                      message=self.getAndsendMessagetoAget(p_id, headers, tracker, dispatcher, message, res.cookies)
                      print(message)
                      if message != "unpause":
                          dispatcher.utter_message("Human agent: {}".format(message))
                          return [ConversationResumed()]
                    #   else:
                    #       message_to_send= tracker.latest_message['text']
                    #       #self.resume_conversation(tracker.sender_id)
                    #       return [ConversationResumed()]
                    

                    
                else:
                    dispatcher.utter_message(text = "some message")  
                #else:
                #    dispatcher.utter_message(text = "No agent available at this time please try after sometime")
                
            else:
                dispatcher.utter_message(text = "handler-notification error")

        return []

    def pause_conversation(sender_id):
      url = f"http://localhost:5005/conversations/{sender_id}/tracker/events"
      headers = {"Content-Type": "application/json"}
      data = [{"event": "pause"}]

      return requests.post(url=url, data=json.dumps(data), headers=headers)


    def resume_conversation(sender_id):
      url = f"http://localhost:5005/conversations/{sender_id}/tracker/events"
      headers = {"Content-Type": "application/json"}
      data = [{"event": "resume"}]

      return requests.post(url=url, data=json.dumps(data), headers=headers)

You shouldn’t take the approach of handing handoff via a custom action. Rasa should not be involved in the communication with the live agent. You’ll find existing posts on this topic with more details: