Great question — answering as the UphillTech team:
I've had to do something similar, I ended up having to store the Call information into a temporary database (DynamoDB) and store the Call invite DateTime. Lets call this inviteDateTime Then anytime there was an event on that particular call, I'd use the CallSID to query my Call Table, calculate the call duration based on the currentTime() - inviteDateTime If the Time Elapsed is over the time I allow, I then use the API to overwrite the Twiml for that call. For example, I'll <Say> a message that we're too busy and to call back, then hangup the call.
Full answer by Moe: https://stackoverflow.stackexchange.com/a/79951159 (CC BY-SA 4.0).
Need it done for your business? UphillTech.