Here’s the basic idea. I’m assuming you’ll need to add some condition to the function so that all users don’t get added to the moderators group when their role changes.
function add_user_to_discourse_group_on_role_change( $user_id, $role ) {
$sso_params = array(
'external_id' => $user_id,
'moderator' => 'true', // the booleans 'true' and 'false' need to be set as strings!
'add_groups' => 'volunteers' // comma separated list, with no spaces after commas
);
DiscourseUtilities::sync_sso_record( $sso_params );
}