How to get a player's random friend?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want to get a player’s random friend
  2. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    Yes, but I understood none
7 Likes

I suggest you using: GetFriendsAsync() or GetFriendsOnline() on the player.

I tried that but I didn’t understand how to use it.

Players:GetFriendsAsync() gives a FriendPages object, which functions similar to regular Pages. In a page are necessary infos of a user’s friend.

Indexing a Page can be hard, so I suggest to iterate the page into a table before using it. If you want to get a random user’s friend details, this can be an example.

local players=game:GetService('Players')
local userId=players:GetUserIdFromNameAsync('YOUR USERNAME')
local friendPage=players:GetFriendsAsync(userId)

local friends={}
while not friends.IsFinished do
    table.insert(friends,friendPage:GetCurrentPage())
    friendPage:AdvanceToNextPage()
end

local randomFriend=friends[math.random(1,#friends)]
5 Likes

Sorry for the late reply, It didn’t work here is the error AdvanceToNextPage is not a valid member of FriendPages “Instance”

Oh, my bad. It’s :AdvanceToNextPageAsync()

I will try that soon. Thank you!

Nope, still giving me an error on this line table.insert(friends,friendPage:GetCurrentPage()) attempt to call a nil value

I’m not sure of the nil value, since Players:GetFriendAsync() yields the code until it has the page. Try replacing the loop with this.

while not friendPage.IsFinished do
    table.insert(friends,friendPage:GetCurrentPage())
    friendPage:AdvanceToNextPage()
end

I will try that right now. Thanks!

Nope, it is still not working.

here is how u get a random players friend id

local Players = game:GetService("Players")

local USERNAME = Players.LocalPlayer.Name

local function iterPageItems(pages)
	return coroutine.wrap(function()
		local pagenum = 1
		
		while true do
			for _, item in ipairs(pages:GetCurrentPage()) do
				coroutine.yield(item, pagenum)
			end
			if pages.IsFinished then
				break
			end
			pages:AdvanceToNextPageAsync()
			pagenum = pagenum + 1
		end
	end)
end
local userId = Players:GetUserIdFromNameAsync(USERNAME)

local friendPages = Players:GetFriendsAsync(userId)

local usernames = {}

for item, _pageNo in iterPageItems(friendPages) do
	table.insert(usernames, item.Username)
end

local random = usernames[math.random(1, #usernames)]

local randomuserid = Players:GetUserIdFromNameAsync(random)

print(randomuserid)

credit to FriendPages | Roblox Creator Documentation

5 Likes