I’m not sure what this line in your code is doing:
$groupname = DiscourseUtilities::get_discourse_user( $user_id, false );
That will set $groupname to a Discourse user object. I think you need to remove that line and use the $group_name variable that you are setting in the first line of your code.