Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lucaimbalzano opened this issue Jun 26, 2024 · 5 comments
Open

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

lucaimbalzano opened this issue Jun 26, 2024 · 5 comments

Comments

@lucaimbalzano
Copy link

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
Copy link
Owner

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

@lucaimbalzano
Copy link
Author

lucaimbalzano commented Jun 27, 2024 via email

@peterolson
Copy link
Owner

@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
Copy link
Author

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
Copy link
Owner

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

  • Your code is not minimal because you are including code irrelevant to the problem at hand
  • It is not complete because I can't take your code directly and test it myself

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants