Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: addfriend request doesn't work #1408

Open
scx1125 opened this issue Aug 27, 2024 · 0 comments
Open

[Bug]: addfriend request doesn't work #1408

scx1125 opened this issue Aug 27, 2024 · 0 comments
Labels

Comments

@scx1125
Copy link

scx1125 commented Aug 27, 2024

What did you expect to happen?

addfriend request doesn't work

        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);
            }
        }

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

Connecting to Steam...
Connected to Steam! Logging in 'usaqt363'...
AccessToken: {
  "iss": "r:1058_24F7F713_A0242",
  "sub": "76561199684915857",
  "aud": [
    "client",
    "web"
  ],
  "exp": 1724887689,
  "nbf": 1716160755,
  "iat": 1724800755,
  "jti": "1055_24F7F71C_9FF57",
  "oat": 1724800755,
  "rt_exp": 1727380531,
  "per": 0,
  "ip_subject": "122.245.168.69",
  "ip_confirmer": "122.245.168.69"
}

RefreshToken: {
  "iss": "steam",
  "sub": "76561199684915857",
  "aud": [
    "client",
    "web",
    "renew",
    "derive"
  ],
  "exp": 1727380531,
  "nbf": 1716160755,
  "iat": 1724800755,
  "jti": "1058_24F7F713_A0242",
  "oat": 1724800755,
  "per": 0,
  "ip_subject": "122.245.168.69",
  "ip_confirmer": "122.245.168.69"
}

Successfully logged on!
We have 0 friends
Disconnected from Steam

Example Code

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);
            }
        }

Additional Information

No response

@scx1125 scx1125 added the bug label Aug 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant