Need help creating custom context that sets caller ID based on header and redirects call based on header

Hey there,

I’m trying to create a custom context that will redirect a call from Trunk A to the number in the diversion header and sets the from number/caller ID to the number in the P-Asserted-Identity header. I’ve tried chatgpt but it just drops the call.

Here is what chatgpt generated:

exten => s,1,NoOp(Entering custom context)

; Extract caller ID from P-Asserted-Identity header
exten => s,n,Set(CALLER_ID_HEADER=${SIP_HEADER(P-Asserted-Identity)})
exten => s,n,Set(CALLER_ID=${REGEX("^\".*<sip:\\+([0-9]+);.*$" ${CALLER_ID_HEADER} dummy CALLER_ID_MATCH})})
exten => s,n,GotoIf($["${CALLER_ID_MATCH}" = "1"]?set_caller_id)
exten => s,n,Set(CALLER_ID=${REGEX("^<sip:\\+([0-9]+);.*$" ${CALLER_ID_HEADER} dummy CALLER_ID_MATCH})})
exten => s,n,GotoIf($["${CALLER_ID_MATCH}" = "1"]?set_caller_id)
exten => s,n,Hangup()

; Set caller ID
exten => set_caller_id,1,NoOp(Setting caller ID to ${CALLER_ID})
exten => set_caller_id,n,Set(CALLERID(num)=${CALLER_ID})

; Extract redirection number from Diversion header
exten => s,n,Set(DIVERSION_HEADER=${SIP_HEADER(Diversion)})
exten => s,n,Set(REDIRECTION_NUMBER=${REGEX("^<sip:\\+([0-9]+)@.*$" ${DIVERSION_HEADER} dummy REDIRECTION_MATCH})})
exten => s,n,GotoIf($["${REDIRECTION_MATCH}" = "1"]?redirect_call)
exten => s,n,Hangup()

; Redirect the call to the redirection number
exten => redirect_call,1,NoOp(Redirecting the call to ${REDIRECTION_NUMBER})
exten => redirect_call,n,Dial(SIP/${REDIRECTION_NUMBER}
exten => redirect_call,n,Hangup()

Is this possible? Is this context far off from what I’m trying to do? Thoughts? Thanks.