You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
private static void SteamAddFriend()
{
string previouslyStoredGuardData = null; // For the sake of this sample, we do not persist guard data
// create our steamclient instance
var steamClient = new SteamClient();
// create the callback manager which will route callbacks to function calls
var manager = new CallbackManager(steamClient);
// get the steamuser handler, which is used for logging on after successfully connecting
var steamUser = steamClient.GetHandler<SteamUser>();
var steamFriends = steamClient.GetHandler<SteamFriends>();
// register a few callbacks we're interested in
// these are registered upon creation to a callback manager, which will then route the callbacks
// to the functions specified
manager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
manager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
manager.Subscribe<SteamFriends.FriendsListCallback>(OnFriendsList);
manager.Subscribe<SteamFriends.PersonaStateCallback>(OnPersonaState);
manager.Subscribe<SteamFriends.FriendAddedCallback>(OnFriendAdded);
var isRunning = true;
Console.WriteLine("Connecting to Steam...");
// initiate the connection
steamClient.Connect();
// create our callback handling loop
while (isRunning)
{
// in order for the callbacks to get routed, they need to be handled by the manager
manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
}
async void OnConnected(SteamClient.ConnectedCallback callback)
{
Console.WriteLine("Connected to Steam! Logging in '{0}'...", _steamAccount.Username);
var shouldRememberPassword = false;
using JsonDocument doc = JsonDocument.Parse(_steamAccount.MaFile);
JsonElement root = doc.RootElement;
string sharedSecret = root.GetProperty("shared_secret").GetString();
SteamGuardAccount steamGuardAccount = new SteamGuardAccount();
steamGuardAccount.SharedSecret = sharedSecret;
string gcode = steamGuardAccount.GenerateSteamGuardCode();
// Begin authenticating via credentials
var authSession = await steamClient.Authentication.BeginAuthSessionViaCredentialsAsync(new AuthSessionDetails
{
Username = _steamAccount.Username,
Password = _steamAccount.Password,
IsPersistentSession = shouldRememberPassword,
// See NewGuardData comment below
GuardData = previouslyStoredGuardData,
/// <see cref="UserConsoleAuthenticator"/> is the default authenticator implemention provided by SteamKit
/// for ease of use which blocks the thread and asks for user input to enter the code.
/// However, if you require special handling (e.g. you have the TOTP secret and can generate codes on the fly),
/// you can implement your own <see cref="SteamKit2.Authentication.IAuthenticator"/>.
Authenticator = new UserConsoleAuthenticator(gcode),
});
// Starting polling Steam for authentication response
var pollResponse = await authSession.PollingWaitForResultAsync();
if (pollResponse.NewGuardData != null)
{
// When using certain two factor methods (such as email 2fa), guard data may be provided by Steam
// for use in future authentication sessions to avoid triggering 2FA again (this works similarly to the old sentry file system).
// Do note that this guard data is also a JWT token and has an expiration date.
previouslyStoredGuardData = pollResponse.NewGuardData;
}
// Logon to Steam with the access token we have received
// Note that we are using RefreshToken for logging on here
steamUser.LogOn(new SteamUser.LogOnDetails
{
Username = pollResponse.AccountName,
AccessToken = pollResponse.RefreshToken,
ShouldRememberPassword = shouldRememberPassword, // If you set IsPersistentSession to true, this also must be set to true for it to work correctly
});
// This is not required, but it is possible to parse the JWT access token to see the scope and expiration date.
ParseJsonWebToken(pollResponse.AccessToken, nameof(pollResponse.AccessToken));
ParseJsonWebToken(pollResponse.RefreshToken, nameof(pollResponse.RefreshToken));
}
void OnDisconnected(SteamClient.DisconnectedCallback callback)
{
Console.WriteLine("Disconnected from Steam");
isRunning = false;
}
void OnLoggedOn(SteamUser.LoggedOnCallback callback)
{
if (callback.Result != EResult.OK)
{
Console.WriteLine("Unable to logon to Steam: {0} / {1}", callback.Result, callback.ExtendedResult);
isRunning = false;
return;
}
Console.WriteLine("Successfully logged on!");
// at this point, we'd be able to perform actions on Steam
// for this sample we'll just log off
steamUser.LogOff();
}
void OnLoggedOff(SteamUser.LoggedOffCallback callback)
{
Console.WriteLine("Logged off of Steam: {0}", callback.Result);
}
// This is simply showing how to parse JWT, this is not required to login to Steam
void ParseJsonWebToken(string token, string name)
{
// You can use a JWT library to do the parsing for you
var tokenComponents = token.Split('.');
// Fix up base64url to normal base64
var base64 = tokenComponents[1].Replace('-', '+').Replace('_', '/');
if (base64.Length % 4 != 0)
{
base64 += new string('=', 4 - base64.Length % 4);
}
var payloadBytes = Convert.FromBase64String(base64);
// Payload can be parsed as JSON, and then fields such expiration date, scope, etc can be accessed
var payload = JsonDocument.Parse(payloadBytes);
// For brevity we will simply output formatted json to console
var formatted = JsonSerializer.Serialize(payload, new JsonSerializerOptions
{
WriteIndented = true,
});
Console.WriteLine($"{name}: {formatted}");
Console.WriteLine();
}
void OnFriendsList(SteamFriends.FriendsListCallback callback)
{
// at this point, the client has received it's friends list
int friendCount = steamFriends.GetFriendCount();
Console.WriteLine("We have {0} friends", friendCount);
for (int x = 0; x < friendCount; x++)
{
// steamids identify objects that exist on the steam network, such as friends, as an example
SteamID steamIdFriend = steamFriends.GetFriendByIndex(x);
// we'll just display the STEAM_ rendered version
Console.WriteLine("Friend: {0}", steamIdFriend.ConvertToUInt64());
}
var sid = new SteamID();
sid.SetFromUInt64(76561198155072315);
steamFriends.AddFriend(sid);
}
void OnFriendAdded(SteamFriends.FriendAddedCallback callback)
{
// someone accepted our friend request, or we accepted one
Console.WriteLine("{0} is now a friend", callback.PersonaName);
}
static void OnPersonaState(SteamFriends.PersonaStateCallback callback)
{
// this callback is received when the persona state (friend information) of a friend changes
// for this sample we'll simply display the names of the friends
Console.WriteLine("State change: {0}", callback.Name);
}
}
privatestaticvoidSteamAddFriend(){stringpreviouslyStoredGuardData=null;// For the sake of this sample, we do not persist guard data// create our steamclient instancevarsteamClient=new SteamClient();// create the callback manager which will route callbacks to function callsvarmanager=new CallbackManager(steamClient);// get the steamuser handler, which is used for logging on after successfully connectingvarsteamUser= steamClient.GetHandler<SteamUser>();varsteamFriends= steamClient.GetHandler<SteamFriends>();// register a few callbacks we're interested in// these are registered upon creation to a callback manager, which will then route the callbacks// to the functions specified
manager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
manager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
manager.Subscribe<SteamFriends.FriendsListCallback>(OnFriendsList);
manager.Subscribe<SteamFriends.PersonaStateCallback>(OnPersonaState);
manager.Subscribe<SteamFriends.FriendAddedCallback>(OnFriendAdded);varisRunning=true;
Console.WriteLine("Connecting to Steam...");// initiate the connection
steamClient.Connect();// create our callback handling loopwhile(isRunning){// in order for the callbacks to get routed, they need to be handled by the manager
manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));}asyncvoidOnConnected(SteamClient.ConnectedCallback callback){
Console.WriteLine("Connected to Steam! Logging in '{0}'...", _steamAccount.Username);varshouldRememberPassword=false;usingJsonDocumentdoc= JsonDocument.Parse(_steamAccount.MaFile);JsonElementroot= doc.RootElement;stringsharedSecret= root.GetProperty("shared_secret").GetString();SteamGuardAccountsteamGuardAccount=new SteamGuardAccount();
steamGuardAccount.SharedSecret =sharedSecret;stringgcode= steamGuardAccount.GenerateSteamGuardCode();// Begin authenticating via credentialsvarauthSession=await steamClient.Authentication.BeginAuthSessionViaCredentialsAsync(new AuthSessionDetails
{Username= _steamAccount.Username,Password= _steamAccount.Password,IsPersistentSession=shouldRememberPassword,// See NewGuardData comment belowGuardData=previouslyStoredGuardData,/// <see cref="UserConsoleAuthenticator"/> is the default authenticator implemention provided by SteamKit/// for ease of use which blocks the thread and asks for user input to enter the code./// However, if you require special handling (e.g. you have the TOTP secret and can generate codes on the fly),/// you can implement your own <see cref="SteamKit2.Authentication.IAuthenticator"/>.Authenticator=new UserConsoleAuthenticator(gcode),});// Starting polling Steam for authentication responsevarpollResponse=await authSession.PollingWaitForResultAsync();if(pollResponse.NewGuardData !=null){// When using certain two factor methods (such as email 2fa), guard data may be provided by Steam// for use in future authentication sessions to avoid triggering 2FA again (this works similarly to the old sentry file system).// Do note that this guard data is also a JWT token and has an expiration date.previouslyStoredGuardData= pollResponse.NewGuardData;}// Logon to Steam with the access token we have received// Note that we are using RefreshToken for logging on here
steamUser.LogOn(new SteamUser.LogOnDetails
{Username= pollResponse.AccountName,AccessToken= pollResponse.RefreshToken,ShouldRememberPassword=shouldRememberPassword,// If you set IsPersistentSession to true, this also must be set to true for it to work correctly});// This is not required, but it is possible to parse the JWT access token to see the scope and expiration date.
ParseJsonWebToken(pollResponse.AccessToken, nameof(pollResponse.AccessToken));
ParseJsonWebToken(pollResponse.RefreshToken, nameof(pollResponse.RefreshToken));}voidOnDisconnected(SteamClient.DisconnectedCallback callback){
Console.WriteLine("Disconnected from Steam");isRunning=false;}voidOnLoggedOn(SteamUser.LoggedOnCallback callback){if(callback.Result != EResult.OK){
Console.WriteLine("Unable to logon to Steam: {0} / {1}", callback.Result, callback.ExtendedResult);isRunning=false;return;}
Console.WriteLine("Successfully logged on!");// at this point, we'd be able to perform actions on Steam// for this sample we'll just log off
steamUser.LogOff();}voidOnLoggedOff(SteamUser.LoggedOffCallback callback){
Console.WriteLine("Logged off of Steam: {0}", callback.Result);}// This is simply showing how to parse JWT, this is not required to login to SteamvoidParseJsonWebToken(stringtoken,stringname){// You can use a JWT library to do the parsing for youvartokenComponents= token.Split('.');// Fix up base64url to normal base64varbase64= tokenComponents[1].Replace('-','+').Replace('_','/');if(base64.Length %4!=0){base64+=newstring('=',4- base64.Length %4);}varpayloadBytes= Convert.FromBase64String(base64);// Payload can be parsed as JSON, and then fields such expiration date, scope, etc can be accessedvarpayload= JsonDocument.Parse(payloadBytes);// For brevity we will simply output formatted json to consolevarformatted= JsonSerializer.Serialize(payload,new JsonSerializerOptions
{WriteIndented=true,});
Console.WriteLine($"{name}: {formatted}");
Console.WriteLine();}voidOnFriendsList(SteamFriends.FriendsListCallback callback){// at this point, the client has received it's friends listintfriendCount= steamFriends.GetFriendCount();
Console.WriteLine("We have {0} friends", friendCount);for(intx=0;x<friendCount;x++){// steamids identify objects that exist on the steam network, such as friends, as an exampleSteamIDsteamIdFriend= steamFriends.GetFriendByIndex(x);// we'll just display the STEAM_ rendered version
Console.WriteLine("Friend: {0}", steamIdFriend.ConvertToUInt64());}varsid=new SteamID();
sid.SetFromUInt64(76561198155072315);
steamFriends.AddFriend(sid);}voidOnFriendAdded(SteamFriends.FriendAddedCallback callback){// someone accepted our friend request, or we accepted one
Console.WriteLine("{0} is now a friend", callback.PersonaName);}staticvoidOnPersonaState(SteamFriends.PersonaStateCallback callback){// this callback is received when the persona state (friend information) of a friend changes// for this sample we'll simply display the names of the friends
Console.WriteLine("State change: {0}", callback.Name);}}
Additional Information
No response
The text was updated successfully, but these errors were encountered:
What did you expect to happen?
addfriend request doesn't work
Instead of that, what actually happened?
addfriend request doesn't work
Which operating system are you running on?
Windows
Which .NET Runtime are you running on?
.NET Core or .NET 5 or higher.
Version
.NET 8
Relevant log output
Example Code
Additional Information
No response
The text was updated successfully, but these errors were encountered: