peterolson / BigInteger.js

An arbitrary length integer library for Javascript
The Unlicense
1.12k stars 187 forks source link

TypeError: (0 , big_integer_1.default) is not a function #244

Open lucaimbalzano opened 1 week ago

lucaimbalzano commented 1 week ago

This is my log where i have the error:

  ERROR [ExceptionsHandler] (0 , big_integer_1.default) is not a function
TypeError: (0 , big_integer_1.default) is not a function

Essentially i try to convert from a number to a BigInteger without success: const channelId = BigInteger(2052204449);

peterolson commented 1 week ago

Can you include a complete reproducible example of the error you are encountering?

lucaimbalzano commented 1 week ago

of course, here you are:

`` import bigInt from 'big-integer';

@Injectable() export class TelegramService { private client: TelegramClient; private stringSession: StringSession; {... code..}

async getChatByChannelId(channelNum: number) { const channelId = bigInt(2052204449); // Here is the error message

} } ``

Il giorno gio 27 giu 2024 alle ore 05:01 Peter Olson < @.***> ha scritto:

Can you include a complete reproducible example of the error you are encountering?

— Reply to this email directly, view it on GitHub https://github.com/peterolson/BigInteger.js/issues/244#issuecomment-2193117385, or unsubscribe https://github.com/notifications/unsubscribe-auth/AK3W5WXDDOZANNM3KHYWOB3ZJN6CLAVCNFSM6AAAAABJ6WZK7OVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDCOJTGEYTOMZYGU . You are receiving this because you authored the thread.Message ID: @.***>

--

Questo documento è formato esclusivamente per il destinatario. Tutte le informazioni ivi contenute, compresi eventuali allegati, sono da ritenere esclusivamente confidenziali e riservate secondo i termini del vigente D.Lgs. 196/2003 in materia di privacy e del Regolamento europeo 679/2016 - GDPR - e quindi ne è proibita l’utilizzazione ulteriore non autorizzata. Se avete ricevuto per errore questo messaggio, Vi preghiamo cortesemente di contattare immediatamente il mittente e cancellare la e-mail. Please don't print this e-mail. Confidentiality Notice This e-mail message including any attachments is for the sole use of the intended recipient and may contain confidential and privileged information pursuant to Legislative Decree 196/2003 and the European General Data Protection Regulation 679/2016 - GDPR Any unauthorized review, use, disclosure or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply e-mail and destroy all copies of the original message.

Grazie - Thank you *P*lease consider the environment before printing this email

peterolson commented 1 week ago

@lucaimbalzano That's not a complete reproducible example because I can't just copy it and run it myself.

If I do this:

import bigInt from "big-integer";

const channelId = bigInt(2052204449);

console.log(channelId.toString());

I do not get any errors.

As an aside, it's generally better to pass strings to bigInt because if you pass in a JavaScript number that is large enough, it will lose precision.

const channelId = bigInt("2052204449");
lucaimbalzano commented 1 week ago

okok, i'm using nestJs so you cannot litterally copy and paste.. i tried your suggestion passing the number as string but i got the same error: but here you are, here my service:


import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { TelegramClient } from 'telegram';
import { Api } from 'telegram/tl';
import { StringSession } from 'telegram/sessions';
import input from 'input';
import bigInt from 'big-integer';

@Injectable()
export class TelegramService {
  private client: TelegramClient;
  private stringSession: StringSession;

  constructor(private configService: ConfigService) {
    const apiId = this.configService.get<string>('TELEGRAM_API_ID');
    const apiHash = this.configService.get<string>('TELEGRAM_API_HASH');
    const stringSession = new StringSession(''); // You can save your session here

    this.client = new TelegramClient(stringSession, parseInt(apiId), apiHash, {
      connectionRetries: 5,
    });

    this.stringSession = stringSession;
  }

  async initialize() {
    console.log(`  

      ████████▓▓▓▓░░▒▒░░▒▒░░░░  ░░░░  ░░░░▒▒░░▒▒░░▓▓▓▓████████
      ██████▓▓▒▒▓▓▒▒  ▒▒░░░░  ░░    ░░  ░░░░▒▒  ▒▒▓▓▒▒▓▓██████
      ██▓▓██▓▓▓▓▒▒░░▒▒  ░░                ░░  ▒▒░░▒▒▓▓▓▓██▓▓██
      ██▓▓██▓▒▒=========== Initialization ===========▒▒▓██▓▓██
      `);
    await this.client.start({
      phoneNumber: '+add_your_number', // async () => await input.text(' ██▓▒▒ Please enter your number, within your prefix: '),
      password: async () =>
        await input.text('██▓▒▒ Please enter your password: '),
      phoneCode: async () =>
        await input.text('██▓▒▒Please enter the code you received: '),
      onError: (err) => console.log(err),
    });

    console.log('You are now connected.');
    console.log(`StringSession: ${this.client.session.save()}`);
  }

  async sendMessage(chatId: number, message: string) {
    await this.client.sendMessage(chatId, { message });
  }

  async sendMessageToUsername(username: string, message: string) {
    const chatId = await this.getChatIdByUsername(username);
    await this.sendMessage(chatId, message);
  }

  async readMessages(chatId: number) {
    const result = await this.client.getMessages(chatId, { limit: 10 });
    return result;
  }
  // async readMessagesWithOptions(chatId: number, limit: number) {
  //   // Correctly define the peerId object
  //   const peerId = {
  //     channelId: chatId, // Use the chatId parameter to make the function dynamic
  //     className: 'PeerChannel',
  //   };

  //   // Fetch the messages
  //   const result = await this.client.getMessages(
  //     { peer: peerId },
  //     { limit: limit },
  //   );
  //   return result;
  // }

  async getAllChatIds() {
    const dialogs = await this.client.getDialogs();
    const chatIds = dialogs.map((dialog) => dialog.id);
    return chatIds;
  }

  async getAllChats() {
    const dialogs = await this.client.getDialogs();
    const chatIds = dialogs.map((dialog) => dialog.id);
    const allChats = [];
    let count = 0;
    for (const id of chatIds) {
      count++;
      if (count > 20) break;
      const result = await this.client.getMessages(id, { limit: 10 });
      allChats.push(result);
    }
    return allChats;
  }

  async getChatIdByUsername(username: string): Promise<number> {
    const result = await this.client.invoke(
      new Api.contacts.ResolveUsername({ username }),
    );
    if (result && result.users && result.users.length > 0) {
      return Number(result.users[0].id.toString());
    }
    throw new Error('User not found');
  }

  async getChatByChannelId() {
    let channelId;
    try {
      channelId = bigInt('2052204449');
      // const accessHashs = bigInt(1);
      const channel = await this.client.getEntity(channelId);
      console.log(channel);
    } catch (error) {
      console.error('Error fetching messages:', error);
    }
    const channel = await this.client.getEntity(channelId);
    console.log(channel);
  }

  async processMissions(): Promise<void> {
    // try {
    /*
      Telegram
      *      "peerId": {
        "userId": "777000",
        "className": "PeerUser"
      },
      */
    // 5219882605 paymentbot --> channel id
    // 2052204449 cjmaingroup -- channel id
    //🔼Missione video
    // let messagesCjMainGroup = await this.readMessagesWithOptions(
    //   2052204449,
    //   100,
    // );

    const messagesCjMainGroup = await this.getChatByChannelId();
    // for (const msg of messagesCjMainGroup) {
    //   if (msg.message.includes('🔼Missione video')) {
    //     console.log(msg);
    //   }
    // }
    console.log(messagesCjMainGroup);
  }
}

here my controller:


import { Controller, Get, Param, Post, Body } from '@nestjs/common';
import { TelegramService } from './telegram.service';
import { SendMessageByUsername } from './dto/send-message-by-username.dto';

@Controller('telegram')
export class TelegramController {
  constructor(private readonly telegramService: TelegramService) {}

  @Get('initialize')
  async initialize() {
    await this.telegramService.initialize();
    return 'Initialized';
  }

  @Post('send/:chatId')
  async sendMessage(
    @Param('chatId') chatId: number,
    @Body('message') message: string,
  ) {
    await this.telegramService.sendMessage(chatId, message);
    return 'Message sent';
  }

  @Post('send-username/:username')
  async sendMessageToUsername(
    @Param('username') username: string,
    @Body('message') sender: SendMessageByUsername,
  ) {
    await this.telegramService.sendMessageToUsername(username, sender.message);
    return 'Message sent';
  }

  @Get('read/:chatId')
  async readMessages(@Param('chatId') chatId: number) {
    const messages = await this.telegramService.readMessages(chatId);
    return messages;
  }

  @Get('/get-all-chat-ids')
  async getAllChatIds() {
    return await this.telegramService.getAllChatIds();
  }

  @Get('/get-all-chats')
  async getAllChats() {
    return await this.telegramService.getAllChats();
  }

  @Get('/get-chat-id-by-username/:username')
  async getChatIdByUsername(@Param('username') username: string) {
    return await this.telegramService.getChatIdByUsername(username);
  }

  @Get('/start-worker')
  async startWorker() {
    return await this.telegramService.processMissions();
  }
}

here my server log:

[Nest] 62838  - 06/27/2024, 6:35:29 PM     LOG [NestApplication] Nest application successfully started +1ms
Error fetching messages: TypeError: (0 , big_integer_1.default) is not a function
    at TelegramService.getChatByChannelId (/Users/lucaimbalzano/Documents/Workspaces/Private/cjaffiliate/src/telegram/telegram.service.ts:112:25)
    at TelegramService.processMissions (/Users/lucaimbalzano/Documents/Workspaces/Private/cjaffiliate/src/telegram/telegram.service.ts:140:44)
    at TelegramController.startWorker (/Users/lucaimbalzano/Documents/Workspaces/Private/cjaffiliate/src/telegram/telegram.controller.ts:56:39)
    at /Users/lucaimbalzano/Documents/Workspaces/Private/cjaffiliate/node_modules/@nestjs/core/router/router-execution-context.js:38:29
    at InterceptorsConsumer.intercept (/Users/lucaimbalzano/Documents/Workspaces/Private/cjaffiliate/node_modules/@nestjs/core/interceptors/interceptors-consumer.js:12:20)
    at /Users/lucaimbalzano/Documents/Workspaces/Private/cjaffiliate/node_modules/@nestjs/core/router/router-execution-context.js:46:60
    at /Users/lucaimbalzano/Documents/Workspaces/Private/cjaffiliate/node_modules/@nestjs/core/router/router-proxy.js:9:23
    at Layer.handle [as handle_request] (/Users/lucaimbalzano/Documents/Workspaces/Private/cjaffiliate/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/lucaimbalzano/Documents/Workspaces/Private/cjaffiliate/node_modules/express/lib/router/route.js:149:13)
    at Route.dispatch (/Users/lucaimbalzano/Documents/Workspaces/Private/cjaffiliate/node_modules/express/lib/router/route.js:119:3)
peterolson commented 1 week ago

@lucaimbalzano Please provide a minimal, complete, reproducible example of the error.

Try to create the smallest program possible that can reproduce the issue. If the issue only happens with NestJS, please link to a repo demonstrating the problem with minimal setup.