Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to get Player's random friend ID?

Asked by 2 years ago

How i can get A player random friend userId?

....

1 answer

Log in to vote
0
Answered by
imKirda 4491 Moderation Voter Community Moderator
2 years ago

Players:GetFriendsAsync returns pages of friends of specified user, when you get the pages, extract all user ids from them and insert them into a table in array form, when you have the table, you know size of it and you know that every user id has it's own whole index in range from 1 to amount of user ids in table, you can generate random number in this range and select index that matches randomly generated number from the array.

local Players = game:GetService("Players")

local function getRandomElement(array)
  if #array == 0 then
    return nil
  end

  return array[math.random(#array)]
end

local function getFriends(userId)
  local friends = {}

  local friendPages = Players:GetFriendsAsync(userId)

  while true do
    local currentPage = friendPages:GetCurrentPage()

    for _, friend in pairs(currentPage) do
      table.insert(friends, friend.Id)
    end

    if friendPages.IsFinished then
      break
    end

    friendPages:AdvanceToNextPageAsync()
  end

  return friends
end

local friends = getFriends(652793987)
print(friends)
print(getRandomElement(friends))

If you want to get id of random friend that is currently in this server, you can loop through every player in the server and check if Player:IsFriendsWith the original player.

local Players = game:GetService("Players")

local function getRandomElement(array)
  if #array == 0 then
    return nil
  end

  return array[math.random(#array)]
end

local function getFriendsInServerAsync(userId)
  local friends = {}

  for _, player in ipairs(Players:GetPlayers()) do
    if player:IsFriendsWith(userId) then
      table.insert(friends, player.UserId)
    end
  end

  return friends
end

local friends = getFriendsInServerAsync(652793987)
print(friends)
print(getRandomElement(friends))
Ad

Answer this question