Is there any way to trigger an action based on the number of unread notifications? I want to add a widget that will display this to me, however, I don't know how to create a script that will allow me to do this
Unfortunately I don't think there is a good way. The notifications are grouped and not really accessible and getting the total count is relatively complex. It is possible in theory using Apple Script (You can get a list of all groups via this Java Script For Automation / Apple Script:
var app = Application('System Events');
var notificationCenter = app.processes.whose({ bundleIdentifier: 'com.apple.notificationcenterui', })[0];
notificationCenter.windows.groups().at(0).at(0).scrollAreas.at(0).uiElements.at(0).groups()
Then you'd need to sum up the counts of each group.
Sadly, I have an error.
Error: TypeError: undefined is not an object (evaluating 'notificationCenter.windows.groups().at(0).at')
Yes this code needs much edge case handling. I think it's not worth it
Undefined probably happens if there are no visible notifications currently.