Drop
Drop

Reputation: 1592

How to Send a Message on Telegram with Only Public User ID (Without Access Hash)?

I'm working on a Telegram integration as userClient and need to send messages to users, but I only have their public user IDs. Typically, sending messages requires both the user ID and the access hash. Here are my specific questions:

  1. Is it possible to send a message to a user knowing only their public user ID without the access hash? If so, how?
  2. If not, how can I obtain the access hash given only the public user ID?

Here’s what I've tried so far:

const { TelegramClient } = require('telegram');
const { StringSession } = require('telegram/sessions');
const { Api } = require('telegram/tl');

const apiId = YOUR_API_ID;
const apiHash = 'YOUR_API_HASH';
const stringSession = new StringSession(''); // Session

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

async function sendMessage(userId, message) {
    try {
        await client.connect();
        const user = await client.invoke(new Api.users.GetUsers({
            id: [new Api.InputUser({ userId, accessHash: 0 })]
        }));
        const accessHash = user[0].accessHash;
        
        const inputPeer = new Api.InputPeerUser({
            userId: userId,
            accessHash: accessHash,
        });
        await client.sendMessage(inputPeer, { message: message });
        console.log(`Message sent to ${userId}`);
    } catch (error) {
        console.error(`Failed to send message: ${error}`);
    } finally {
        await client.disconnect();
    }
}

sendMessage(USER_ID, 'Hello from gram.js!');

However, this code fails if the user’s access hash is not already cached or known.

Specific Questions:

  1. Is there any way to send messages without needing the access hash?

  2. How can I programmatically obtain the access hash given only the public user ID using gram.js or any other method?

  3. Are there alternative methods or workarounds that could solve this problem?

It doesn't matter which library or framework is used as long as it works with MTProto. I'm open to solutions involving other libraries like telethon, telegram-mtproto, tdlib, etc.

Any guidance or suggestions would be greatly appreciated.

Upvotes: 0

Views: 588

Answers (1)

Lonami
Lonami

Reputation: 7141

The answer to all your questions is no, you can't. And there are no alternatives.

The purpose of the access hash is precisely to prevent anyone of obtaining (or guessing, or scanning) an ID and using it. The access hash exists so you can prove to Telegram you can interact with another user (or channel, or media).

Upvotes: 1

Related Questions