It’s a known issue with the API that is being worked on, so it’s not your code that is at fault.
The best way I can suggest to mitigate the issue is to keep a cache on your end of the user id’s and their corresponding usernames, that way when you need to make use of the username, such as in a Discord post, you get the username from your cache or database for that user_id and use that rather than attempting to use the user_name field which is sometimes missing.