gram-js / gramjs

NodeJS/Browser MTProto API Telegram client library,
MIT License
1.18k stars 171 forks source link

Telegram Client Hangs Up on Connect #691

Open Aamir-K11 opened 1 week ago

Aamir-K11 commented 1 week ago

I've been trying to connect to telegram using TelegramClient in a worker thread. The worker hangs up at await client.connect and after retries throws connection error. Strange that it works locally but is a problem with Docker.

import { Api, TelegramClient } from "telegram";
import accounts from "./accounts";
import redisClient from "./redis";
import { Worker } from "bullmq";

(async function init() {
  accounts.forEach((account, index) => {
    new Worker(
      `message-queue-${index}`,
      async (job) => {
        const { recipient, message } = job.data;

        console.log(`Processing job for recipient: ${recipient}`);

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

        try {
          console.log("Connecting telegram client...");
          await client.connect();
          console.log("Telegram client connected...");

          await client.invoke(
            new Api.messages.SendMessage({
              peer: recipient,
              message: message,
              randomId: BigInt(`${Date.now()}`) as any,
              noWebpage: true,
              noforwards: true,
            })
          );

          console.log("Message sent...");
        } catch (error) {
          console.log("Failed to send message:", error);
        } finally {
          await client.disconnect();
          console.log("Telegram client disconnected...");
        }

        console.log(`Message sent...`);
      },
      {
        limiter: {
          max: 1,
          duration: 10000,
        },
        connection: redisClient,
      }
    );
  });
})();

The application has been dockerized. Here is the docker-compose.yml.

version: "3.8"

services:
  caddy:
    image: caddy:latest
    ports:
      - "8080:80"    
      - "443:443"
      - "88:88"
    volumes:
      - ./caddy/:/etc/caddy/
      - caddy_data:/data
      - caddy_config:/config
    depends_on:
      - telegram
    networks:
      - telegram_net

  redis:
    image: redis:latest
    volumes:
      - redis_data:/data
    networks:
      - telegram_net

  telegram:
    build: .
    ports:
      - "5000:5000"  # Ensure Telegram service is exposed on port 5000
    environment:
      - PORT=5000
      - REDIS_URI=redis://redis:6379
    depends_on:
      - redis
    networks:
      - telegram_net

volumes:
  caddy_data:
  caddy_config:
  redis_data:

networks:
  telegram_net:
    driver: bridge

DockerFile

FROM node:20-alpine3.18

WORKDIR /app

RUN apk update && apk add bash

RUN npm install -g pm2

COPY . .

RUN npm install

RUN npm run build

EXPOSE 5000

CMD npm run start

Finally, caddyfile for reverse proxy

localhost {
    reverse_proxy  http://telegram:5000
}

Any ideas?

Some observations:

elja commented 5 days ago

having similar issue, the only thing that differs that I initialize it a bit differently

const session = new StringSession(account.session)
const tgClient = new TelegramClient(session, account.api_id, account.api_hash, {
  connectionRetries: 5,
  floodSleepThreshold: 0,
  useWSS: true,
  testServers: false,
})

tgClient.setLogLevel(LogLevel.DEBUG)
await tgClient.connect()

and got this:

[2024-07-03T23:58:53.010] [INFO] - [Started reconnecting]
[2024-07-03T23:58:53.011] [DEBUG] - [Closing current connection...]
[2024-07-03T23:58:53.011] [WARN] - [[Reconnect] Closing current connection...]
[2024-07-03T23:58:53.011] [INFO] - [Disconnecting from venus.web.telegram.org:443/TCPFull...]
[2024-07-03T23:58:53.011] [DEBUG] - [Closing current connection...]
[2024-07-03T23:58:53.011] [INFO] - [Connecting to venus.web.telegram.org:443/TCPFull...]
[2024-07-03T23:58:53.011] [DEBUG] - [Connecting]
[2024-07-03T23:58:53.012] [DEBUG] - [Got undefined message(s) to send]
[2024-07-03T23:58:53.012] [DEBUG] - [Reconnecting]
[2024-07-03T23:58:53.050] [DEBUG] - [Finished connecting]
[2024-07-03T23:58:53.051] [DEBUG] - [Connection success!]
[2024-07-03T23:58:53.051] [DEBUG] - [Already have an auth key ...]
[2024-07-03T23:58:53.051] [DEBUG] - [Starting send loop]
[2024-07-03T23:58:53.051] [DEBUG] - [Waiting for messages to send... false]
[2024-07-03T23:58:53.051] [DEBUG] - [Starting receive loop]
[2024-07-03T23:58:53.051] [DEBUG] - [Receiving items from the network...]
[2024-07-03T23:58:53.051] [INFO] - [Connection to venus.web.telegram.org:443/TCPFull complete!]
[2024-07-03T23:58:53.051] [INFO] - [Handling reconnect!]
[2024-07-03T23:58:53.051] [DEBUG] - [Assigned msgId = 7387532440122215640 to InvokeWithLayer]
[2024-07-03T23:58:53.051] [DEBUG] - [Got 1 message(s) to send]
[2024-07-03T23:58:53.051] [DEBUG] - [Encrypting 1 message(s) in 72 bytes for sending]
[2024-07-03T23:58:53.051] [DEBUG] - [Sending   InvokeWithLayer]
[2024-07-03T23:58:53.052] [DEBUG] - [Encrypted messages put in a queue to be sent]
[2024-07-03T23:58:53.052] [DEBUG] - [Waiting for messages to send... false]
[2024-07-03T23:58:53.092] [INFO] - [connection closed]
[2024-07-03T23:58:53.092] [WARN] - [Connection closed while receiving data]
Error: Not connected
    at ConnectionTCPFull.recv (.../node_modules/telegram/network/connection/Connection.js:71:15)
    at MTProtoSender._recvLoop (.../node_modules/telegram/network/MTProtoSender.js:365:24)