Jump to content
McKay Development

Recommended Posts

Posted

I'm getting the error "Invalid input SteamID [object Object]". I'm retrieving data from the database to handle multiple accounts, such as item prices and other information, without any issues. However, I cannot send a trade when I try to do so. The partnerSteamID in the database is in SteamID64 format, and the trade link is correct. Can anyone help?

const SteamUser = require('steam-user');
const SteamTotp = require('steam-totp');
const TradeOfferManager = require('steam-tradeoffer-manager');
const SteamID = require('steamid');
const mysql = require('mysql2/promise');
const axios = require('axios');
const tunnel = require('tunnel');
const SteamCommunity = require('steamcommunity');
const community = new SteamCommunity();


const SsAccounts = {
    host: 'h',
    user: 'u',
    password: 'p',
    database: 'd'
};
 

const SteamAccounts = {
    host: 'h',
    user: 'u',
    password: 'p',
    database: 'd'
};
 

async function getAccounts() {
    try {
        const db1Connection = await mysql.createConnection(SsAccounts);
        const [rows] = await db1Connection.execute("SELECT username, tradelink, partnerSteamID FROM users WHERE SSMmember = 'FA'");
        const users = rows.map(row => ({ username: row.username, tradelink: row.tradelink, partnerSteamID: row.partnerSteamID }));
        await db1Connection.end();
 

        if (users.length === 0) {
            console.log('Kriterlere uyan kullanıcı yok.');
            return [];
        }
 

        users.forEach(user => {
            console.log(`Username: ${user.username}, TradeLink: ${user.tradelink}, PartnerSteamID: ${user.partnerSteamID}`);
        });
 

        const db2Connection = await mysql.createConnection(SteamAccounts);
        const validAccounts = [];
 

        for (let user of users) {
            try {
                const [tables] = await db2Connection.execute(`SHOW TABLES LIKE '${user.username}'`);
                if (tables.length > 0) {
                    const [accounts] = await db2Connection.execute(`SELECT username, password, shared_secret, proxyip, proxyid, identity_secret FROM ${user.username}`);
                    accounts.forEach(account => {
                        if (account.shared_secret && account.shared_secret.trim() !== '') {
                            validAccounts.push({
                                ...account,
                                tableName: user.username,
                                tradelink: user.tradelink,
                                partnerSteamID: user.partnerSteamID
                            });
                        }
                    });
                }
            } catch (err) {
                console.error(`[${user.username}] Kullanıcı için veri alınırken hata oluştu:`, err);
            }
        }
 

        await db2Connection.end();
        validAccounts.sort((a, b) => a.username.localeCompare(b.username));
        return validAccounts;
    } catch (error) {
        console.error('Hata:', error);
        return [];
    }
}
 

async function getApiKey(cookies, proxyUrl) {
    try {
        const [proxyUser, proxyPass] = proxyUrl.match(/\/\/(.+):(.+)@/).slice(1, 3);
        const proxyHostPort = proxyUrl.split('@')[1];
        const [proxyHost, proxyPort] = proxyHostPort.split(':');
 

        const agent = tunnel.httpsOverHttp({
            proxy: {
                host: proxyHost,
                port: parseInt(proxyPort),
                proxyAuth: `${proxyUser}:${proxyPass}`
            }
        });
 

        const response = await axios.get('https://steamcommunity.com/dev/apikey', {
            headers: {
                Cookie: cookies.join('; ')
            },
            httpsAgent: agent,
            maxRedirects: 5
        });
 

        const apiKeyMatch = response.data.match(/<p>Key: ([A-Z0-9]{32})<\/p>/);
        if (apiKeyMatch) {
            return apiKeyMatch[1];
        }
    } catch (error) {
        if (error.response && error.response.status === 429) {
            console.log('API anahtarı alınırken 429 hatası: Too Many Requests');
        } else {
            console.error('API anahtarı alınırken hata oluştu:', error);
        }
    }
    return null;
}
 

async function getMarketPrice(marketHashName) {
    try {
        const response = await axios.get(`https://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=${encodeURIComponent(marketHashName)}`);
        if (response.data && response.data.success) {
            return parseFloat(response.data.lowest_price.replace('$', '').replace(',', '')) || 0;
        }
    } catch (error) {
        console.error(`Fiyat bilgisi alınırken hata oluştu: ${marketHashName}`, error);
    }
    return 0;
}
 

async function updateAccountInfo(tableName, username, itemCount, totalPrice) {
    try {
        const db2Connection = await mysql.createConnection(SteamAccounts);
        await db2Connection.execute(`UPDATE ${tableName} SET stitemcount = ?, stitemprice = ? WHERE username = ?`, [itemCount, totalPrice, username]);
        await db2Connection.end();
        console.log(`[${username}] Envanter bilgileri güncellendi: Item Sayısı = ${itemCount}, Toplam Fiyat = ${totalPrice}`);
    } catch (error) {
        console.error(`[${username}] Envanter bilgileri güncellenirken hata oluştu:`, error);
    }
}
 

async function parseTradeLink(tradeLink) {
    const url = new URL(tradeLink.trim());
    const token = url.searchParams.get('token');
    const partner = url.searchParams.get('partner');
 

    if (!partner || !token) {
        throw new Error("Invalid Trade Link");
    }
 

    return { partnerSteamID: new SteamID(`[U:1:${partner}]`).getSteamID64(), token };
}
 

async function sendTradeOffer(account, items, partnerSteamID, token) {
    return new Promise((resolve, reject) => {
        const proxyUrl = `http://${account.proxyid}@${account.proxyip}`;
        const agent = tunnel.httpsOverHttp({
            proxy: {
                host: account.proxyip.split(':')[0],
                port: parseInt(account.proxyip.split(':')[1]),
                proxyAuth: `${account.proxyid}`
            }
        });
 

        const manager = new TradeOfferManager({
            steam: new SteamUser(),
            domain: 'example.com',
            language: 'en',
            proxy: proxyUrl
        });
 

        console.log(`[${account.username}] Partner SteamID: ${partnerSteamID}`);
 

        let steamID;
        try {
            steamID = new SteamID(partnerSteamID);
        } catch (error) {
            console.error(`[${account.username}] Invalid SteamID format: ${partnerSteamID}`, error);
            reject(error);
            return;
        }
 

        const offer = manager.createOffer({ partner: steamID, accessToken: token });
 

        items.forEach(item => offer.addMyItem(item));
 

        offer.send(async (err, status) => {
            if (err) {
                console.error(`[${account.username}] Trade offer gönderilirken hata oluştu:`, err);
                reject(err);
                return;
            }
 

            console.log(`[${account.username}] Trade offer gönderildi: ${status}`);
            resolve(offer.id);
        });
    });
}
 

async function confirmTradeOffer(account, offerId) {
    return new Promise((resolve, reject) => {
        const proxyUrl = `http://${account.proxyid}@${account.proxyip}`;
        const agent = tunnel.httpsOverHttp({
            proxy: {
                host: account.proxyip.split(':')[0],
                port: parseInt(account.proxyip.split(':')[1]),
                proxyAuth: `${account.proxyid}`
            }
        });
 

        community.getConfirmations(account.identity_secret, (err, confirmations) => {
            if (err) {
                console.error(`[${account.username}] Onaylar alınırken hata oluştu:`, err);
                reject(err);
                return;
            }
 

            const offerConf = confirmations.find(conf => conf.creator === offerId);
            if (!offerConf) {
                console.error(`[${account.username}] İlgili onay bulunamadı: ${offerId}`);
                reject(new Error('İlgili onay bulunamadı'));
                return;
            }
 

            community.acceptConfirmationForObject(account.identity_secret, offerConf.id, { proxy: agent }, (err) => {
                if (err) {
                    console.error(`[${account.username}] Trade offer onaylanırken hata oluştu:`, err);
                    reject(err);
                    return;
                }
 

                console.log(`[${account.username}] Trade offer onaylandı: ${offerId}`);
                resolve();
            });
        });
    });
}
 

async function loginAndFetchInventory(account) {
    return new Promise((resolve) => {
        const client = new SteamUser();
        const proxyUrl = `http://${account.proxyid}@${account.proxyip}`;
 

        const manager = new TradeOfferManager({
            steam: client,
            domain: 'example.com',
            language: 'en',
            httpProxy: proxyUrl
        });
 

        const guardCode = SteamTotp.generateAuthCode(account.shared_secret);
 

        const logOnOptions = {
            accountName: account.username,
            password: account.password,
            twoFactorCode: guardCode,
            httpProxy: proxyUrl
        };
 

        client.logOn(logOnOptions);
 

        client.on('loggedOn', () => {
            console.log(`[${account.username}] Başarıyla giriş yapıldı`);
            client.setPersona(SteamUser.EPersonaState.Online);
        });
 

        client.on('webSession', async (sessionID, cookies) => {
            console.log(`[${account.username}] Cookies:`, cookies);
 

            const apiKey = await getApiKey(cookies, proxyUrl);
            console.log(`[${account.username}] API Key: ${apiKey}`);
 

            if (apiKey) {
                const agent = tunnel.httpsOverHttp({
                    proxy: {
                        host: account.proxyip.split(':')[0],
                        port: parseInt(account.proxyip.split(':')[1]),
                        proxyAuth: `${account.proxyid}`
                    }
                });
 

                manager.setCookies(cookies, async (err) => {
                    if (err) {
                        console.log(`[${account.username}] TradeOfferManager cookies set error:`, err);
                        resolve();
                        return;
                    }
 

                    console.log(`[${account.username}] Cookies set for TradeOfferManager`);
                    manager.apiKey = apiKey; // Set the API key
 

                    const appId = 730;
                    const contextId = 2;
 

                    const fetchInventory = async (retryCount = 0) => {
                        if (retryCount >= 3) {
                            console.log(`[${account.username}] Envanter alınamadı, maksimum deneme sayısına ulaşıldı.`);
                            resolve();
                            return;
                        }
 

                        manager.getUserInventoryContents(client.steamID, appId, contextId, true, async (err, inventory) => {
                            if (err) {
                                if (err.message.includes('403') || err.message.includes('500')) {
                                    console.log(`[${account.username}] Envanter alınırken hata oluştu, ${retryCount + 1}. yeniden deneme:`, err);
                                    await new Promise(res => setTimeout(res, 2000)); // 2 saniye bekleme süresi
                                    await fetchInventory(retryCount + 1);
                                } else {
                                    console.error(`[${account.username}] Envanter alınırken hata oluştu:`, err);
                                    resolve();
                                }
                                return;
                            }
 

                            const items = inventory.map(item => ({
                                assetid: item.id,
                                appid: item.appid,
                                contextid: item.contextid,
                                amount: item.amount
                            }));
 

                            const { partnerSteamID, token } = await parseTradeLink(account.tradelink);
                            try {
                                const offerId = await sendTradeOffer(account, items, partnerSteamID, token);
                                await confirmTradeOffer(account, offerId);
                            } catch (err) {
                                console.error(`[${account.username}] Trade offer gönderilirken veya onaylanırken hata oluştu:`, err);
                            }
 

                            let itemCount = inventory.length;
                            let totalPrice = 0;
 

                            for (let item of inventory) {
                                let marketPrice = await getMarketPrice(item.market_hash_name);
                                totalPrice += marketPrice;
                            }
 

                            await updateAccountInfo(account.tableName, account.username, itemCount, totalPrice.toFixed(2));
                            resolve();
                        });
                    };
 

                    await fetchInventory();
                }, { proxy: agent });
 

                community.setCookies(cookies, { proxy: agent });
            } else {
                console.log(`[${account.username}] API anahtarı alınamadı.`);
                resolve();
            }
        });
 

        client.on('error', (err) => {
            console.error(`[${account.username}] Giriş yapılırken hata oluştu:`, err);
            resolve();
        });
    });
}
 

(async () => {
    const accounts = await getAccounts();
 

    for (let account of accounts) {
        await loginAndFetchInventory(account);
    }
 

    console.log('Tüm işlemler tamamlandı.');
})();
Posted
On 6/12/2024 at 8:58 PM, ggforces said:

I'm getting the error "Invalid input SteamID [object Object]". I'm retrieving data from the database to handle multiple accounts, such as item prices and other information, without any issues. However, I cannot send a trade when I try to do so. The partnerSteamID in the database is in SteamID64 format, and the trade link is correct. Can anyone help?

const SteamUser = require('steam-user');
const SteamTotp = require('steam-totp');
const TradeOfferManager = require('steam-tradeoffer-manager');
const SteamID = require('steamid');
const mysql = require('mysql2/promise');
const axios = require('axios');
const tunnel = require('tunnel');
const SteamCommunity = require('steamcommunity');
const community = new SteamCommunity();


const SsAccounts = {
    host: 'h',
    user: 'u',
    password: 'p',
    database: 'd'
};
 

const SteamAccounts = {
    host: 'h',
    user: 'u',
    password: 'p',
    database: 'd'
};
 

async function getAccounts() {
    try {
        const db1Connection = await mysql.createConnection(SsAccounts);
        const [rows] = await db1Connection.execute("SELECT username, tradelink, partnerSteamID FROM users WHERE SSMmember = 'FA'");
        const users = rows.map(row => ({ username: row.username, tradelink: row.tradelink, partnerSteamID: row.partnerSteamID }));
        await db1Connection.end();
 

        if (users.length === 0) {
            console.log('Kriterlere uyan kullanıcı yok.');
            return [];
        }
 

        users.forEach(user => {
            console.log(`Username: ${user.username}, TradeLink: ${user.tradelink}, PartnerSteamID: ${user.partnerSteamID}`);
        });
 

        const db2Connection = await mysql.createConnection(SteamAccounts);
        const validAccounts = [];
 

        for (let user of users) {
            try {
                const [tables] = await db2Connection.execute(`SHOW TABLES LIKE '${user.username}'`);
                if (tables.length > 0) {
                    const [accounts] = await db2Connection.execute(`SELECT username, password, shared_secret, proxyip, proxyid, identity_secret FROM ${user.username}`);
                    accounts.forEach(account => {
                        if (account.shared_secret && account.shared_secret.trim() !== '') {
                            validAccounts.push({
                                ...account,
                                tableName: user.username,
                                tradelink: user.tradelink,
                                partnerSteamID: user.partnerSteamID
                            });
                        }
                    });
                }
            } catch (err) {
                console.error(`[${user.username}] Kullanıcı için veri alınırken hata oluştu:`, err);
            }
        }
 

        await db2Connection.end();
        validAccounts.sort((a, b) => a.username.localeCompare(b.username));
        return validAccounts;
    } catch (error) {
        console.error('Hata:', error);
        return [];
    }
}
 

async function getApiKey(cookies, proxyUrl) {
    try {
        const [proxyUser, proxyPass] = proxyUrl.match(/\/\/(.+):(.+)@/).slice(1, 3);
        const proxyHostPort = proxyUrl.split('@')[1];
        const [proxyHost, proxyPort] = proxyHostPort.split(':');
 

        const agent = tunnel.httpsOverHttp({
            proxy: {
                host: proxyHost,
                port: parseInt(proxyPort),
                proxyAuth: `${proxyUser}:${proxyPass}`
            }
        });
 

        const response = await axios.get('https://steamcommunity.com/dev/apikey', {
            headers: {
                Cookie: cookies.join('; ')
            },
            httpsAgent: agent,
            maxRedirects: 5
        });
 

        const apiKeyMatch = response.data.match(/<p>Key: ([A-Z0-9]{32})<\/p>/);
        if (apiKeyMatch) {
            return apiKeyMatch[1];
        }
    } catch (error) {
        if (error.response && error.response.status === 429) {
            console.log('API anahtarı alınırken 429 hatası: Too Many Requests');
        } else {
            console.error('API anahtarı alınırken hata oluştu:', error);
        }
    }
    return null;
}
 

async function getMarketPrice(marketHashName) {
    try {
        const response = await axios.get(`https://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=${encodeURIComponent(marketHashName)}`);
        if (response.data && response.data.success) {
            return parseFloat(response.data.lowest_price.replace('$', '').replace(',', '')) || 0;
        }
    } catch (error) {
        console.error(`Fiyat bilgisi alınırken hata oluştu: ${marketHashName}`, error);
    }
    return 0;
}
 

async function updateAccountInfo(tableName, username, itemCount, totalPrice) {
    try {
        const db2Connection = await mysql.createConnection(SteamAccounts);
        await db2Connection.execute(`UPDATE ${tableName} SET stitemcount = ?, stitemprice = ? WHERE username = ?`, [itemCount, totalPrice, username]);
        await db2Connection.end();
        console.log(`[${username}] Envanter bilgileri güncellendi: Item Sayısı = ${itemCount}, Toplam Fiyat = ${totalPrice}`);
    } catch (error) {
        console.error(`[${username}] Envanter bilgileri güncellenirken hata oluştu:`, error);
    }
}
 

async function parseTradeLink(tradeLink) {
    const url = new URL(tradeLink.trim());
    const token = url.searchParams.get('token');
    const partner = url.searchParams.get('partner');
 

    if (!partner || !token) {
        throw new Error("Invalid Trade Link");
    }
 

    return { partnerSteamID: new SteamID(`[U:1:${partner}]`).getSteamID64(), token };
}
 

async function sendTradeOffer(account, items, partnerSteamID, token) {
    return new Promise((resolve, reject) => {
        const proxyUrl = `http://${account.proxyid}@${account.proxyip}`;
        const agent = tunnel.httpsOverHttp({
            proxy: {
                host: account.proxyip.split(':')[0],
                port: parseInt(account.proxyip.split(':')[1]),
                proxyAuth: `${account.proxyid}`
            }
        });
 

        const manager = new TradeOfferManager({
            steam: new SteamUser(),
            domain: 'example.com',
            language: 'en',
            proxy: proxyUrl
        });
 

        console.log(`[${account.username}] Partner SteamID: ${partnerSteamID}`);
 

        let steamID;
        try {
            steamID = new SteamID(partnerSteamID);
        } catch (error) {
            console.error(`[${account.username}] Invalid SteamID format: ${partnerSteamID}`, error);
            reject(error);
            return;
        }
 

        const offer = manager.createOffer({ partner: steamID, accessToken: token });
 

        items.forEach(item => offer.addMyItem(item));
 

        offer.send(async (err, status) => {
            if (err) {
                console.error(`[${account.username}] Trade offer gönderilirken hata oluştu:`, err);
                reject(err);
                return;
            }
 

            console.log(`[${account.username}] Trade offer gönderildi: ${status}`);
            resolve(offer.id);
        });
    });
}
 

async function confirmTradeOffer(account, offerId) {
    return new Promise((resolve, reject) => {
        const proxyUrl = `http://${account.proxyid}@${account.proxyip}`;
        const agent = tunnel.httpsOverHttp({
            proxy: {
                host: account.proxyip.split(':')[0],
                port: parseInt(account.proxyip.split(':')[1]),
                proxyAuth: `${account.proxyid}`
            }
        });
 

        community.getConfirmations(account.identity_secret, (err, confirmations) => {
            if (err) {
                console.error(`[${account.username}] Onaylar alınırken hata oluştu:`, err);
                reject(err);
                return;
            }
 

            const offerConf = confirmations.find(conf => conf.creator === offerId);
            if (!offerConf) {
                console.error(`[${account.username}] İlgili onay bulunamadı: ${offerId}`);
                reject(new Error('İlgili onay bulunamadı'));
                return;
            }
 

            community.acceptConfirmationForObject(account.identity_secret, offerConf.id, { proxy: agent }, (err) => {
                if (err) {
                    console.error(`[${account.username}] Trade offer onaylanırken hata oluştu:`, err);
                    reject(err);
                    return;
                }
 

                console.log(`[${account.username}] Trade offer onaylandı: ${offerId}`);
                resolve();
            });
        });
    });
}
 

async function loginAndFetchInventory(account) {
    return new Promise((resolve) => {
        const client = new SteamUser();
        const proxyUrl = `http://${account.proxyid}@${account.proxyip}`;
 

        const manager = new TradeOfferManager({
            steam: client,
            domain: 'example.com',
            language: 'en',
            httpProxy: proxyUrl
        });
 

        const guardCode = SteamTotp.generateAuthCode(account.shared_secret);
 

        const logOnOptions = {
            accountName: account.username,
            password: account.password,
            twoFactorCode: guardCode,
            httpProxy: proxyUrl
        };
 

        client.logOn(logOnOptions);
 

        client.on('loggedOn', () => {
            console.log(`[${account.username}] Başarıyla giriş yapıldı`);
            client.setPersona(SteamUser.EPersonaState.Online);
        });
 

        client.on('webSession', async (sessionID, cookies) => {
            console.log(`[${account.username}] Cookies:`, cookies);
 

            const apiKey = await getApiKey(cookies, proxyUrl);
            console.log(`[${account.username}] API Key: ${apiKey}`);
 

            if (apiKey) {
                const agent = tunnel.httpsOverHttp({
                    proxy: {
                        host: account.proxyip.split(':')[0],
                        port: parseInt(account.proxyip.split(':')[1]),
                        proxyAuth: `${account.proxyid}`
                    }
                });
 

                manager.setCookies(cookies, async (err) => {
                    if (err) {
                        console.log(`[${account.username}] TradeOfferManager cookies set error:`, err);
                        resolve();
                        return;
                    }
 

                    console.log(`[${account.username}] Cookies set for TradeOfferManager`);
                    manager.apiKey = apiKey; // Set the API key
 

                    const appId = 730;
                    const contextId = 2;
 

                    const fetchInventory = async (retryCount = 0) => {
                        if (retryCount >= 3) {
                            console.log(`[${account.username}] Envanter alınamadı, maksimum deneme sayısına ulaşıldı.`);
                            resolve();
                            return;
                        }
 

                        manager.getUserInventoryContents(client.steamID, appId, contextId, true, async (err, inventory) => {
                            if (err) {
                                if (err.message.includes('403') || err.message.includes('500')) {
                                    console.log(`[${account.username}] Envanter alınırken hata oluştu, ${retryCount + 1}. yeniden deneme:`, err);
                                    await new Promise(res => setTimeout(res, 2000)); // 2 saniye bekleme süresi
                                    await fetchInventory(retryCount + 1);
                                } else {
                                    console.error(`[${account.username}] Envanter alınırken hata oluştu:`, err);
                                    resolve();
                                }
                                return;
                            }
 

                            const items = inventory.map(item => ({
                                assetid: item.id,
                                appid: item.appid,
                                contextid: item.contextid,
                                amount: item.amount
                            }));
 

                            const { partnerSteamID, token } = await parseTradeLink(account.tradelink);
                            try {
                                const offerId = await sendTradeOffer(account, items, partnerSteamID, token);
                                await confirmTradeOffer(account, offerId);
                            } catch (err) {
                                console.error(`[${account.username}] Trade offer gönderilirken veya onaylanırken hata oluştu:`, err);
                            }
 

                            let itemCount = inventory.length;
                            let totalPrice = 0;
 

                            for (let item of inventory) {
                                let marketPrice = await getMarketPrice(item.market_hash_name);
                                totalPrice += marketPrice;
                            }
 

                            await updateAccountInfo(account.tableName, account.username, itemCount, totalPrice.toFixed(2));
                            resolve();
                        });
                    };
 

                    await fetchInventory();
                }, { proxy: agent });
 

                community.setCookies(cookies, { proxy: agent });
            } else {
                console.log(`[${account.username}] API anahtarı alınamadı.`);
                resolve();
            }
        });
 

        client.on('error', (err) => {
            console.error(`[${account.username}] Giriş yapılırken hata oluştu:`, err);
            resolve();
        });
    });
}
 

(async () => {
    const accounts = await getAccounts();
 

    for (let account of accounts) {
        await loginAndFetchInventory(account);
    }
 

    console.log('Tüm işlemler tamamlandı.');
})();

brother in order to send the tradeoffer u need the trade link the assetid of the item u want to send and a message i srsly dont know y u are parsing steam if so many times ifu have the complete trade url just use that if the partner in the trade url is missing and u need it then parse thesteamid 64 to get the id32 assuming u have the trade token already 
The error is caused due to u are calling the send offer with the wrong data most likely the steamid mistake or wrong format as ur error says or calling it where u are not supposed to or with incomplete data try to console,log what data are u sending when u are calling the send offer method.

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...