Untitled
unknown
javascript
10 months ago
8.2 kB
12
Indexable
const { Telegraf } = require('telegraf');
const { TelegramClient } = require('telegram');
const { StringSession } = require('telegram/sessions');
const { Api } = require('telegram/tl');
const fs = require('fs');
const input = require('input');
// Telegram Bot Token
const BOT_TOKEN = 'YOUR_BOT_TOKEN_HERE';
// Initialize Telegraf Bot
const bot = new Telegraf(BOT_TOKEN);
// Session file for Telegram Client
const sessionFile = 'session.txt';
let stringSession = fs.existsSync(sessionFile) ? fs.readFileSync(sessionFile, 'utf-8') : '';
let client; // Telegram Client instance
let userSessions = {}; // Store user-specific session data
// Function to start Telegram client
async function startTelegramClient(userId) {
const { apiId, apiHash, phoneNumber } = userSessions[userId];
if (!client) {
client = new TelegramClient(new StringSession(stringSession), apiId, apiHash, {
connectionRetries: 1,
useWSS: true,
baseDC: 2,
});
await client.start({
phoneNumber: async () => phoneNumber,
password: async () => await input.text('Enter your password (if 2FA is enabled): '),
phoneCode: async () => await input.text('Enter the code you received: '),
onError: (err) => console.log(err),
});
fs.writeFileSync(sessionFile, client.session.save());
console.log('Telegram client connected.');
}
return client;
}
// Command: /start
bot.command('start', (ctx) => {
ctx.reply('Welcome! Use the following commands:\n\n' +
'/scrap_channel - Scrape members from a channel\n' +
'/scrap_group - Scrape members from a group');
});
// Command: /scrap_channel
bot.command('scrap_channel', async (ctx) => {
const userId = ctx.from.id;
userSessions[userId] = {};
ctx.reply('Enter your API ID:');
bot.on('text', async (ctx) => {
userSessions[userId].apiId = Number(ctx.message.text);
ctx.reply('Enter your API Hash:');
bot.on('text', async (ctx) => {
userSessions[userId].apiHash = ctx.message.text;
ctx.reply('Enter your phone number (with country code):');
bot.on('text', async (ctx) => {
userSessions[userId].phoneNumber = ctx.message.text;
await startTelegramClient(userId);
ctx.reply('Fetching channels...');
const result = await client.invoke(
new Api.messages.GetDialogs({
offsetDate: 0,
offsetId: 0,
offsetPeer: new Api.InputPeerEmpty(),
limit: 2000,
hash: 0,
})
);
const channels = result.chats.filter(chat => chat instanceof Api.Channel && !chat.megagroup);
userSessions[userId].channels = channels;
if (channels.length === 0) {
ctx.reply('No channels found.');
return;
}
const buttons = channels.map((channel, index) => [{
text: `${channel.title} (ID: ${channel.id})`,
callback_data: `channel_${index}`
}]);
ctx.reply('Choose a channel to scrape members from:', {
reply_markup: { inline_keyboard: buttons },
});
});
});
});
});
// Handle channel selection
bot.action(/channel_(\d+)/, async (ctx) => {
const userId = ctx.from.id;
const index = parseInt(ctx.match[1]);
const targetChannel = userSessions[userId].channels[index];
ctx.reply(`Fetching members from ${targetChannel.title}...`);
const participants = await client.getParticipants(targetChannel);
ctx.reply(`Found ${participants.length} members in ${targetChannel.title}.\nEnter the target group ID to add them:`);
bot.on('text', async (ctx) => {
const targetGroupId = ctx.message.text;
const targetGroupObj = await client.getEntity(targetGroupId);
const usersToAdd = participants.map(user => user.id);
const chunkSize = 10; // Avoid mass adding to prevent bans
for (let i = 0; i < usersToAdd.length; i += chunkSize) {
const chunk = usersToAdd.slice(i, i + chunkSize);
try {
await client.invoke(
new Api.channels.InviteToChannel({
channel: targetGroupObj,
users: chunk.map(userId => new Api.InputUser({ userId })),
})
);
ctx.reply(`Added ${chunk.length} users.`);
} catch (error) {
ctx.reply(`Failed to add some users. Error: ${error.message}`);
}
await new Promise(resolve => setTimeout(resolve, 3000)); // Rate-limit to avoid bans
}
ctx.reply('Finished adding members.');
});
});
// Command: /scrap_group
bot.command('scrap_group', async (ctx) => {
const userId = ctx.from.id;
userSessions[userId] = {};
ctx.reply('Enter your API ID:');
bot.on('text', async (ctx) => {
userSessions[userId].apiId = Number(ctx.message.text);
ctx.reply('Enter your API Hash:');
bot.on('text', async (ctx) => {
userSessions[userId].apiHash = ctx.message.text;
ctx.reply('Enter your phone number (with country code):');
bot.on('text', async (ctx) => {
userSessions[userId].phoneNumber = ctx.message.text;
await startTelegramClient(userId);
ctx.reply('Fetching groups...');
const result = await client.invoke(
new Api.messages.GetDialogs({
offsetDate: 0,
offsetId: 0,
offsetPeer: new Api.InputPeerEmpty(),
limit: 2000,
hash: 0,
})
);
const groups = result.chats.filter(chat => chat instanceof Api.Channel && chat.megagroup);
userSessions[userId].groups = groups;
if (groups.length === 0) {
ctx.reply('No groups found.');
return;
}
const buttons = groups.map((group, index) => [{
text: `${group.title} (ID: ${group.id})`,
callback_data: `group_${index}`
}]);
ctx.reply('Choose a group to scrape members from:', {
reply_markup: { inline_keyboard: buttons },
});
});
});
});
});
// Handle group selection
bot.action(/group_(\d+)/, async (ctx) => {
const userId = ctx.from.id;
const index = parseInt(ctx.match[1]);
const targetGroup = userSessions[userId].groups[index];
ctx.reply(`Fetching members from ${targetGroup.title}...`);
const participants = await client.getParticipants(targetGroup);
ctx.reply(`Found ${participants.length} members in ${targetGroup.title}.\nEnter the target group ID to add them:`);
bot.on('text', async (ctx) => {
const targetGroupId = ctx.message.text;
const targetGroupObj = await client.getEntity(targetGroupId);
const usersToAdd = participants.map(user => user.id);
const chunkSize = 10;
for (let i = 0; i < usersToAdd.length; i += chunkSize) {
const chunk = usersToAdd.slice(i, i + chunkSize);
try {
await client.invoke(
new Api.channels.InviteToChannel({
channel: targetGroupObj,
users: chunk.map(userId => new Api.InputUser({ userId })),
})
);
ctx.reply(`Added ${chunk.length} users.`);
} catch (error) {
ctx.reply(`Failed to add some users. Error: ${error.message}`);
}
await new Promise(resolve => setTimeout(resolve, 3000));
}
ctx.reply('Finished adding members.');
});
});
// Start the bot
bot.launch();
console.log('Bot started...');Editor is loading...
Leave a Comment