Here is some code that works for me on MacOS Monterey.
on closeNotifs(numTimes)
repeat numTimes times
try
tell application "System Events" to tell application process "NotificationCenter"
set boxes to groups of UI element 1 of scroll area 1 of window 1
set numBoxes to count boxes
repeat with i from numBoxes to 1 by -1
try
perform item 1 of (actions of item i of boxes whose name starts with "Name")
end try
end repeat
end tell
end try
end repeat
end closeNotifs
closeNotifs(2)
Instead of whose name starts with "Name"
you may use whose name description is "Close"
but I don't have English settings. I think this should work for any language.
I haven't solved the problem that the last notification is not closed automatically, so I basically run it twice.
This has been a PITA for so long.