TypeError: API.Payments.sendStars не является конструктором при отправке подарков Telegram Stars с Gramjs (Telegram.js)Javascript

Форум по Javascript
Ответить Пред. темаСлед. тема
Anonymous
 TypeError: API.Payments.sendStars не является конструктором при отправке подарков Telegram Stars с Gramjs (Telegram.js)

Сообщение Anonymous »

Я пытаюсь написать сценарий Nodejs, используя

Код: Выделить всё

telegram
[/b] библиотека (v2.x), чтобы купить подарок Telegram Stars для моей собственной учетной записи пользователя.
Я могу успешно подключиться, войти в систему и получить список доступных подарков, используя

Код: Выделить всё

Api.payments.GetStarGifts
[/b]. Проблема возникает, когда я пытаюсь купить подарок, используя

Код: Выделить всё

Api.payments.SendStars
[/b].
Вот минимальный, воспроизводимый пример моего кода:

Код: Выделить всё

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
[/b].
Когда я запускаю этот код, скрипт успешно входит в систему и получает список подарков, но затем он сбои со следующей ошибкой:

Код: Выделить всё

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)
Я дважды проверил официальную документацию MTProto для payments.sendstars и параметры кажутся правильными.

Код: Выделить всё

GetStarGifts
[/b] конструктор работает нормально, поэтому [/b] объект импортируется правильно.

Код: Выделить всё

Api.payments.SendStars
, чтобы отправить себе подарок, используя клиента пользователя с

Код: Выделить всё

telegram
[/b] библиотека?

Подробнее здесь: https://stackoverflow.com/questions/797 ... legram-sta
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Платеж Telegram Stars недействителен
    Anonymous » » в форуме Python
    0 Ответы
    38 Просмотры
    Последнее сообщение Anonymous
  • Платеж Telegram Stars недействителен
    Anonymous » » в форуме Python
    0 Ответы
    35 Просмотры
    Последнее сообщение Anonymous
  • Платеж Telegram Stars недействителен
    Anonymous » » в форуме Python
    0 Ответы
    77 Просмотры
    Последнее сообщение Anonymous
  • Проблема с IAP (Telegram Stars) на Android
    Anonymous » » в форуме Android
    0 Ответы
    13 Просмотры
    Последнее сообщение Anonymous
  • Telegram WebApp Stars Integration Integration
    Anonymous » » в форуме Python
    0 Ответы
    11 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Javascript»