# Authentication

## Getting API ID and API HASH

Before working with Telegram’s API, you need to get your own API ID and hash:

1. [Login to your Telegram account](https://my.telegram.org/) with the phone number of the developer account to use.
2. Click under API Development tools.
3. A *Create new application* window will appear. Fill in your application details. There is no need to enter any *URL*, and only the first two fields (*App title* and *Short name*) can currently be changed later.
4. Click on *Create application* at the end. Remember that your **API hash is secret** and Telegram won’t let you revoke it. Don’t post it anywhere!

## Logging in as a Bot

Using GramJS you can use a bot token to log in. doing this is simple&#x20;

{% tabs %}
{% tab title="TypeScript" %}

```typescript
import {TelegramClient} from "telegram";
import {StringSession} from "telegram/sessions";

const stringSession = ''; // leave this empty for now
const BOT_TOKEN = ; // put your bot token here
(async () => {
    const client = new TelegramClient(new StringSession(stringSession),
        apiId, apiHash, {connectionRetries: 5});
    await client.start({
        botAuthToken: BOT_TOKEN 
    });
    console.log(client.session.save())
})();
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const {TelegramClient} = require("telegram");
const {StringSession} =require ("telegram/sessions");

const stringSession = ''; // leave this empty for now
const BOT_TOKEN = ; // put your bot token here
(async () => {
    const client = new TelegramClient(new StringSession(stringSession),
        apiId, apiHash, {connectionRetries: 5});
    await client.start({
        botAuthToken: BOT_TOKEN 
    });
    console.log(client.session.save())
})();

```

{% endtab %}
{% endtabs %}

Underneath this is just calling the RAW function `ImportBotAuthorization.` you can leave the string session empty for now.

## Logging in as a User

Logging in as a user is a bit more complex because you'll need to provide callbacks for when you receive the code from telegram. you can use the [input ](https://www.npmjs.com/package/input)package to manage that on Node or [prompt ](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt)on the browser

{% tabs %}
{% tab title="JavaScript" %}

```javascript
const { TelegramClient } = require('telegram')
const { StringSession } = require('telegram/sessions')
const input = require('input') // npm i input

const apiId = 123456
const apiHash = '123456abcdfg'
const stringSession = new StringSession(''); // fill this later with the value from session.save()
(async () => {
    console.log('Loading interactive example...')
    const client = new TelegramClient(stringSession, apiId, apiHash, { connectionRetries: 5 })
    await client.start({
        phoneNumber: async () => await input.text('number ?'),
        password: async () => await input.text('password?'),
        phoneCode: async () => await input.text('Code ?'),
        onError: (err) => console.log(err),
    });
    console.log('You should now be connected.')
    console.log(client.session.save()) // Save this string to avoid logging in again
    await client.sendMessage('me', { message: 'Hello!' });
})()
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import { TelegramClient } from 'telegram'
import { StringSession }  from 'telegram/sessions'
import input from 'input'; // npm i input

const apiId = 123456
const apiHash = '123456abcdfg'
const stringSession = new StringSession(''); // fill this later with the value from session.save()
(async () => {
    console.log('Loading interactive example...');
    const client = new TelegramClient(stringSession, apiId, apiHash, { connectionRetries: 5 });
    await client.start({
        phoneNumber: async () => await input.text('number ?'),
        password: async () => await input.text('password?'),
        phoneCode: async () => await input.text('Code ?'),
        onError: (err) => console.log(err),
    });
    console.log('You should now be connected.');
    console.log(client.session.save()) // Save this string to avoid logging in again
    await client.sendMessage('me', { message: 'Hello!' });
})()

```

{% endtab %}
{% endtabs %}

## Persistent Session

To avoid having to logging each time you'll need to save the session after logging in. \
There are multiple types of sessions with the easiest being `StringSession` that will provide an Authorization string for you to use again. You can create your own Session by subclassing the `MemorySession` class.

If you have async logic in your custom session put it in the `load()` function that's called before loading a session

## String Session

You can import it from `telegram/session`

{% tabs %}
{% tab title="TypeScript" %}

```typescript
import { StringSession }  from 'telegram/sessions'
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const { StringSession } = require('telegram/sessions')
```

{% endtab %}
{% endtabs %}

If you're using it for the first login you need to provide an empty String to the constructor

{% tabs %}
{% tab title="JavaScript" %}

```javascript
const stringSession = new StringSession('');
```

{% endtab %}
{% endtabs %}

After logging in you'll need to call the `.save()` method to receive the string&#x20;

You can either do that by calling it directly on the `stringSession` variable or by using `client.session`

{% tabs %}
{% tab title="JavaScript" %}

```javascript
console.log(client.session.save());
console.log(stringSession.save());
```

{% endtab %}
{% endtabs %}

## Store Session

Store session uses [store2](https://www.npmjs.com/package/store2) with the help of [node-localstorage](https://www.npmjs.com/search?q=node-localstorage) to save the session automatically in files.  it's useful to save entities so you can access them later with just their ID and lowers the amount of requests needed to the telegram server. You just need to provide a session name to save it with &#x20;

{% tabs %}
{% tab title="TypeScript" %}

```typescript
import { StoreSession }  from 'telegram/sessions'
const storeSession = new StoreSession("my_session");
const client = new TelegramClient(storeSession , apiId, apiHash,
                                  {connectionRetries: 5});

```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const { StoreSession } = require('telegram/sessions');
const storeSession = new StoreSession("my_session");
const client = new TelegramClient(storeSession , apiId, apiHash,
                                  {connectionRetries: 5});

```

{% endtab %}
{% endtabs %}

This session is still in Alpha and not tested that much so it might break. use carefully.&#x20;


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://painor.gitbook.io/gramjs/getting-started/authorization.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
