Код: Выделить всё
telegram
Я могу успешно подключиться, войти в систему и получить список доступных подарков, используя
Код: Выделить всё
Api.payments.GetStarGifts
Код: Выделить всё
Api.payments.SendStars
Вот минимальный, воспроизводимый пример моего кода:
Код: Выделить всё
import "dotenv/config";
import { TelegramClient, Api } from "telegram";
import { StringSession } from "telegram/sessions/index.js";
import fs from "fs/promises";
// --- CONFIGURATION ---
// These are loaded from a .env file
const API_ID = Number(process.env.API_ID);
const API_HASH = process.env.API_HASH;
const SESSION_FILE = "./my_session.txt";
// --- MAIN SCRIPT ---
(async () => {
// 1. Initialize session from file
let sessionString = "";
try {
sessionString = await fs.readFile(SESSION_FILE, { encoding: "utf-8" });
} catch {
console.log("Session file not found. A new one will be created after login.");
}
const client = new TelegramClient(
new StringSession(sessionString),
API_ID,
API_HASH,
{ connectionRetries: 5 }
);
// 2. Connect and save the session if it's new
await client.connect();
// This will prompt for login only if the session is invalid or missing
if (!await client.isAuthenticated()) {
// Handle login logic here (omitted for brevity, assume session is valid)
console.error("Session is not valid. Please generate a session first.");
return;
}
const me = await client.getMe();
console.log(`Logged in as: ${me.firstName} (@${me.username})`);
// 3. Fetch the list of gifts (this part works correctly)
console.log("Fetching gift list...");
const allGifts = await client.invoke(new Api.payments.GetStarGifts({}));
const unlimitedGifts = allGifts.gifts.filter((g) => g.availabilityRemains == null);
if (!unlimitedGifts.length) {
console.log("No unlimited gifts found.");
return;
}
const giftToBuy = unlimitedGifts[0]; // Let's just buy the first one
console.log(`Attempting to buy gift ID: ${giftToBuy.id} for ${Number(giftToBuy.stars)} stars.`);
// 4. Attempt to send the gift (this is where the error occurs)
try {
const request = new Api.payments.SendStars({
peer: new Api.InputPeerUser({
userId: me.id,
accessHash: me.accessHash,
}),
gift: true,
id: giftToBuy.id,
randomId: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
});
// The error is thrown on the next line
await client.invoke(request);
console.log("Gift purchased successfully!");
} catch (error) {
console.error("Failed to purchase gift:", error);
}
await client.disconnect();
})();
< /code>
Чтобы воспроизвести проблему, вам нужна действительная строка сеанса. Я генерирую его с отдельным сценарием и сохраняю в [b]my_session.txt
Когда я запускаю этот код, скрипт успешно входит в систему и получает список подарков, но затем он сбои со следующей ошибкой:
Код: Выделить всё
Attempting to buy gift ID: 5170145012310081615 for 15 stars.
Failed to purchase gift: TypeError: Api.payments.SendStars is not a constructor
at file:///path/to/your/project/index.js:63:25
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Код: Выделить всё
GetStarGifts
Код: Выделить всё
Api
Код: Выделить всё
Api.payments.SendStars
Код: Выделить всё
telegram
Подробнее здесь: https://stackoverflow.com/questions/797 ... legram-sta