How do u make it so a player gets a badge when inviting their friends

While making my game realized why not add a feature where people get a badge and a title that says “Good friend” but i don’t really know how to achieve this.
I tried my best but still haven’t found a solution.

local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")

local GOOD_FRIEND_BADGE_ID = 12345678 -- Replace with your badge ID
local dataStore = DataStoreService:GetDataStore("GoodFriendTitles") -- Data storage for titles

-- Function to give the Billboard UI
local function giveBillboardUI(character)
    if not character then return end
    local head = character:FindFirstChild("Head")
    if not head then return end

    local billboard = Instance.new("BillboardGui")
    billboard.Size = UDim2.new(4, 0, 1, 0)
    billboard.StudsOffset = Vector3.new(0, 3, 0)
    billboard.Adornee = head
    billboard.Parent = character

    local textLabel = Instance.new("TextLabel")
    textLabel.Size = UDim2.new(1, 0, 1, 0)
    textLabel.BackgroundTransparency = 1
    textLabel.Text = "Good Friend"
    textLabel.TextColor3 = Color3.fromRGB(255, 255, 0) -- Yellow text
    textLabel.Font = Enum.Font.Cartoon
    textLabel.TextScaled = true
    textLabel.Parent = billboard
end

-- Function to check and give title to inviter
local function checkAndGiveTitle(player)
    -- Check if the player already has the badge
    if not BadgeService:UserHasBadgeAsync(player.UserId, GOOD_FRIEND_BADGE_ID) then
        -- Award badge to player
        BadgeService:AwardBadge(player.UserId, GOOD_FRIEND_BADGE_ID)
        print(player.Name .. " has been awarded the Good Friend badge!")

        -- Set leaderstats for the title
        local leaderstats = player:FindFirstChild("leaderstats")
        if not leaderstats then
            leaderstats = Instance.new("Folder")
            leaderstats.Name = "leaderstats"
            leaderstats.Parent = player
        end

        local title = leaderstats:FindFirstChild("Title")
        if not title then
            title = Instance.new("StringValue")
            title.Name = "Title"
            title.Parent = leaderstats
        end

        title.Value = "Good Friend"

        -- Give the inviter a Billboard UI
        player.CharacterAdded:Connect(function(character)
            giveBillboardUI(character)
        end)
    end
end

-- When a player joins, check if they invited someone
Players.PlayerAdded:Connect(function(player)
    -- Get the referrer (who invited the player)
    local joinData = player:GetJoinData()
    local inviterId = joinData.Referrer

    if inviterId then
        local inviter = Players:GetPlayerByUserId(inviterId)
        if inviter then
            -- If the inviter hasn't already received the badge, give them the badge and title
            checkAndGiveTitle(inviter)
        end
    end
end)
1 Like