Gateway event occasionally error when execute Project libary script : NameError: name is not defined

I've had a problem like this before. I'm not sure if it's the same thing here, but it would be worth a check.

If you can safely call this script from the Script Console, then your script is compiling and this isn't the solution to your issue.

If it is a compile error, a common culprit is spacing. It doesn't matter if you use tabs or spaces, so long as you're consistent. I'd recommend turning on whitespace characters when looking through the script to find invisible errors. To see them, right-click in the script editor to find the setting.
image

Once it's selected, you'll see tabs as arrows and spaces as tiny dots:
image

This can help you find errors that would otherwise be easy to miss:
image