How to get Player's random friend UserID

The title explains everything, how would i get the ID of a random friend of the user?

First you get a FriendsPages with Players:GetFriendsAsync.

https://developer.roblox.com/en-us/api-reference/function/Players/GetFriendsAsync

Then you go through the FriendsPages, adding the friends to a table/array (getting the friends from each page with FriendsPages:GetCurrentPage(), moving to the next page with FriendsPages:AdvanceToNextPageAsync(), and stopping after FriendsPages.IsFinished is true).

Once you get this list of friends, it’s pretty straight forward. You just need to get the length of the array (you can do that with a #) then generate a random index between 1 and the length.

6 Likes

What @PersonifiedPizza described, in code:

local Players = game:GetService("Players")
local player = Players.LocalPlayer -- or however you obtain your player instance
local friends = Players:GetFriendsAsync(player.UserId)

local ids = table.create(200) -- max friends limit
local count = 0

while true do
	for _, item in ipairs(friends:GetCurrentPage()) do
        count += 1
		ids[count] = item.Id
	end
	
	if friends.IsFinished then
		break
	end
	
	friends:AdvanceToNextPageAsync()
end

local randomFriendId = ids[math.random(1,count)] -- nil if no pages are available :(
3 Likes

It Doesn’t seems to work, Nothing in output

Oh, in that case please give me a second to test and debug – I’ll update this post when I find something.

Alright, thanks !

This text will be blurred

Hey! Edited the code - fixed it up a bit and edited the previous post. Let me know if your issue has been fixed.

It seems that it still’s doesnt work, nothing in output

Try copying Abi’s code again and checking where you’re trying to run the code from. I tested it in studio and it works:

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local friends = Players:GetFriendsAsync(player.UserId)

local ids = table.create(200) -- max friends limit
local count = 1

while true do
	for _, item in ipairs(friends:GetCurrentPage()) do
		ids[count] = item.Id
		count += 1
	end

	if friends.IsFinished then
		break
	end

	friends:AdvanceToNextPageAsync()
end

local randomFriendId = ids[math.random(1,count)] -- nil if no pages are available :(
if not randomFriendId then
	print("No friends")
else
	print(Players:GetNameFromUserIdAsync(randomFriendId))
end
7 Likes