Jump to content
McKay Development

HTTP error 403 when trying to relog after session expires


Recommended Posts

Posted (edited)
const SteamUser = require('steam-user');
const SteamCommunity = require('steamcommunity');
const TradeOfferManager = require('steam-tradeoffer-manager');
const allowedSteamID = "blabla";
const SteamTotp = require('steam-totp');  // Import the steam-totp package
const webhooklink = "link"
const https = require('https');

class SteamBot {
  constructor(logOnOptions) {
    const self = this;  // Store the reference to 'this'
    this.isLoggingIn = false;  // Initialize the flag to indicate log-in status

    this.client = new SteamUser();
    this.community = new SteamCommunity();
    this.manager = new TradeOfferManager({
      steam: this.client,
      community: this.community,
      language: 'en',
      pollInterval: 30000,
      useAccessToken: true
    });

    this.client.setOption('autoRelogin', true);

    if (logOnOptions.sharedSecret) {
      const twoFactorCode = SteamTotp.getAuthCode(logOnOptions.sharedSecret);
      logOnOptions.twoFactorCode = twoFactorCode;  // Include 2FA code in logOnOptions
  }

    this.client.logOn(logOnOptions);
    this.isLoggingIn = true;  // Set the flag to true on first login attempt

    
    this.client.on('loggedOn', () => {
      console.log('Logged into Steam');
      this.isLoggingIn = false;  // Reset flag after successful login


      this.client.setPersona(SteamUser.EPersonaState.Online);
    });

    this.client.on('friendRelationship', (steamID, relationship) => {
      // Check if we received a friend request
      if (relationship === SteamUser.Steam.EFriendRelationship.RequestRecipient) {
          console.log(`Accepting friend request from ${steamID.getSteam3RenderedID()}`);
          client.addFriend(steamID); // Automatically accept the friend request
      }
  });


    this.client.on('webSession', (sessionID, cookies) => {
      this.manager.setCookies(cookies, (err) => {
        if (err) {
          console.error('Error setting cookies for TradeOfferManager:', err);
        } else {
          console.log('Cookies set for TradeOfferManager');
        }
      });

      this.community.setCookies(cookies);
      this.community.startConfirmationChecker(10000, '=');
    });

    this.community.on("sessionExpired", async function (err) {
      if (err) {
          console.log('Session Expired: ' + err);
      }

      if (!self.isLoggingIn) {
        self.isLoggingIn = true;  // Prevent concurrent logins
  
        // Check if the bot is connected to the Steam network
        if (self.client.steamID) {  // Checks if logged on
            self.client.webLogOn();
            console.log('called weblogon');
        } else {
            console.log('Bot is not connected to the Steam network. Cannot call webLogOn.');
            const lop = {
              accountName: "",   // Replace with your Steam account name
              password: "#",          // Replace with your Steam password
              sharedSecret: "="  // Optional: Only if your account has 2FA enabled
          };
            
            // Check if 2FA is needed, generate the 2FA code if `sharedSecret` is provided
        if (lop.sharedSecret) {
          const twoFactorCode = SteamTotp.getAuthCode(lop.sharedSecret);
          lop.twoFactorCode = twoFactorCode;  // Include 2FA code in logOnOptions
        }

        // Attempt to log in with the provided credentials
        self.client.logOn(lop);

        self.client.once('loggedOn', () => {
          self.isLoggingIn = false;  // Reset flag after successful re-login
        });

        self.client.on('error', (error) => {
          console.error("Login error:", error.message);

          // Send POST request to the Discord webhook if login fails
          const webhookUrl = "link";
          const errorMessage = `Steam Bot Login Error: ${error.message}`;

          // Prepare the message payload for Discord
          const data = JSON.stringify({
              content: errorMessage
          });

        // Parse the webhook URL
        const url = new URL(webhookUrl);
        const options = {
            hostname: url.hostname,
            path: url.pathname + url.search,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': data.length
            }
        };

        // Send HTTPS request to Discord webhook
        const req = https.request(options, (res) => {
            console.log(`Discord webhook responded with status: ${res.statusCode}`);
        });

        req.on('error', (e) => {
            console.error(`Problem with Discord webhook request: ${e.message}`);
        });

        req.write(data);  // Write data to request body
        req.end();
      });

    }
    }
    
});


    

    this.client.on('loginKey', (key) => {
      logOnOptions.loginKey = key;  // Store login key for future logins
      console.log('Login key saved for future logins:', key);
  });

    


    this.manager.on('newOffer', (offer) => {
      console.log('Incoming trade offer received'); // Log when a new offer is received
      if (offer.partner.getSteamID64() === allowedSteamID) {
        offer.accept((err, status) => {
          if (err) {
            console.error(`Unable to accept offer: ${err.message}`);
          } else {
            console.log(`Offer accepted: ${status}`);
          }
        });
      } else {
        console.log(`Offer from unauthorized Steam ID: ${offer.partner.getSteamID64()}`);
        
      }
    });
  }

  


  sendDepositTrade(assetIds, unique_code, tradeLink, steamID, callback) {
    //const { partner, token } = this.manager.getPartnerAndToken(tradeLink);

    const urlParams = new URLSearchParams(new URL(tradeLink).search);
    const partner = urlParams.get('partner');  // Extract the partner SteamID from the URL
    const token = urlParams.get('token');      // Extract the token from the URL
    const offer = this.manager.createOffer(tradeLink);


    this.manager.getUserInventoryContents(steamID, 730, 2, true, (err, inv) => {
      if (err) {
        console.log('Error fetching user inventory:', err);
        callback(err, false); // Invoke the callback with the error
      } else {
        const itemsToAdd = inv.filter((item) => {
          const itemAssetId = String(item.assetid);
          return assetIds && assetIds.includes(itemAssetId);
        });
  
        if (itemsToAdd.length > 0) {
          //console.log('Items found in inventory matching assetIds:', itemsToAdd);
  
          itemsToAdd.forEach((item) => {
            offer.addTheirItem(item);
            //console.log("Added item to trade offer:", item);
          });
  
          offer.setMessage(`Acceptera för omedelbar utbetalning via Swish. Verifieringskoden är: ${unique_code}`);
          offer.send((err, status) => {
            console.log("offer status " + status);
            if (err) {
              console.error('Error sending trade offer:', err);
              callback(err, false, offer); // Invoke the callback with the error
            } else {
                
                callback(null, true, offer.id); // Trade sent successfully
          
          }
          });
        }
      }
    });
  }


  
}
  
  

module.exports = SteamBot; 

With this code I get Session Expired: Error: HTTP error 403 upon session expiry

 
Edited by dawe
Formatted code

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...