OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Telegram Client Hangs Up on Connect

  • Thread starter Thread starter Aamir Khan
  • Start date Start date
A

Aamir Khan

Guest
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.

Code:
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.

Code:
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

Code:
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

Code:
localhost {
    reverse_proxy  http://telegram:5000
}

Any ideas?

Some observations:


  • I have checked Docker network and the containers are all connected and I could ping redis and caddy from within the telegram.


  • Changing to connectionRetries: -1 yields the result false on connect instead of hanging up. So, it doesn't connect and timeout.

<p>I've been trying to connect to telegram using TelegramClient in a worker thread. The worker hangs up at <code>await client.connect</code> and after retries throws connection error. Strange that it works locally but is a problem with Docker.</p>
<pre><code>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,
}
);
});
})();
</code></pre>
<p>The application has been dockerized. Here is the docker-compose.yml.</p>
<pre><code>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
</code></pre>
<p>DockerFile</p>
<pre><code>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
</code></pre>
<p>Finally, caddyfile for reverse proxy</p>
<pre><code>localhost {
reverse_proxy http://telegram:5000
}
</code></pre>
<p>Any ideas?</p>
<p>Some observations:</p>
<ul>
<li><p>I have checked Docker network and the containers are all connected and I could ping redis and caddy from within the telegram.</p>
</li>
<li><p>Changing to <code>connectionRetries: -1 </code> yields the result false on connect instead of hanging up. So, it doesn't connect and timeout.</p>
</li>
</ul>
 
Top