telegram-session-generator
Version:
🚀 A secure and easy-to-use CLI tool for generating Telegram session strings. Perfect for Telegram client development and automation projects.
155 lines • 5.53 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TelegramSessionGenerator = void 0;
const telegram_1 = require("telegram");
const sessions_1 = require("telegram/sessions");
/**
* TelegramSessionGenerator - A class to manage Telegram session creation and authentication
*/
class TelegramSessionGenerator {
constructor(config) {
this.client = null;
/**
* Default phone number prompt (throws error - must be overridden)
*/
this.defaultPhonePrompt = async () => {
throw new Error('Phone number prompt not provided. Please provide a phoneNumber function in AuthenticationOptions.');
};
/**
* Default verification code prompt (throws error - must be overridden)
*/
this.defaultCodePrompt = async () => {
throw new Error('Verification code prompt not provided. Please provide a phoneCode function in AuthenticationOptions.');
};
/**
* Default password prompt (returns empty string)
*/
this.defaultPasswordPrompt = async () => {
return '';
};
/**
* Default error handler
*/
this.defaultErrorHandler = (error) => {
console.error('Authentication error:', error.message);
};
this.validateConfig(config);
this.config = {
connectionRetries: 3,
...config,
};
}
/**
* Validate the configuration
*/
validateConfig(config) {
if (!config.apiId || config.apiId <= 0) {
throw new Error('Invalid API ID. Please provide a valid Telegram API ID.');
}
if (!config.apiHash || config.apiHash.trim() === '') {
throw new Error('Invalid API Hash. Please provide a valid Telegram API Hash.');
}
}
/**
* Create a new session string through interactive authentication
*/
async createSession(options = {}) {
try {
// Create client with empty session
this.client = new telegram_1.TelegramClient(new sessions_1.StringSession(this.config.sessionString || ''), this.config.apiId, this.config.apiHash, {
connectionRetries: this.config.connectionRetries,
});
// Start authentication process
await this.client.start({
phoneNumber: options.phoneNumber || this.defaultPhonePrompt,
phoneCode: options.phoneCode || this.defaultCodePrompt,
password: options.password || this.defaultPasswordPrompt,
onError: options.onError || this.defaultErrorHandler,
});
// Get session string
const sessionString = this.client.session.save();
return {
sessionString,
success: true,
};
}
catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
return {
sessionString: '',
success: false,
error: errorMessage,
};
}
}
/**
* Verify an existing session string
*/
async verifySession(sessionString) {
try {
const client = new telegram_1.TelegramClient(new sessions_1.StringSession(sessionString), this.config.apiId, this.config.apiHash, {
connectionRetries: this.config.connectionRetries,
});
await client.connect();
// Try to get current user info to verify session
await client.getMe();
await client.disconnect();
return {
sessionString,
success: true,
};
}
catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Session verification failed';
return {
sessionString,
success: false,
error: errorMessage,
};
}
}
/**
* Get user information from session string
*/
async getUserInfo(sessionString) {
try {
const session = sessionString || this.config.sessionString;
if (!session) {
throw new Error('No session string provided');
}
const client = new telegram_1.TelegramClient(new sessions_1.StringSession(session), this.config.apiId, this.config.apiHash, {
connectionRetries: this.config.connectionRetries,
});
await client.connect();
const me = await client.getMe();
await client.disconnect();
return {
id: me.id.toString(),
firstName: me.firstName || '',
lastName: me.lastName || undefined,
username: me.username || undefined,
phone: me.phone || undefined,
};
}
catch (error) {
console.error('Failed to get user info:', error);
return null;
}
}
/**
* Disconnect the current client
*/
async disconnect() {
if (this.client && this.client.connected) {
await this.client.disconnect();
}
}
/**
* Check if client is connected
*/
isConnected() {
return this.client?.connected || false;
}
}
exports.TelegramSessionGenerator = TelegramSessionGenerator;
//# sourceMappingURL=TelegramSessionGenerator.js.map