tgGroupAdder/index.js
2020-01-06 15:57:07 +03:30

138 lines
5.5 KiB
JavaScript

const ag = require('airgram');
(async () => {
const apiHash = "7c40bb32dca18a094d2240d4e00970b5";
const apiId = "199134";
const client = new ag.Airgram({
useTestDc: false,
useFileDatabase: false,
useSecretChats: false,
apiId, apiHash,
useMessageDatabase: false,
applicationVersion: 'beta',
databaseDirectory: '/tmp/td',
useChatInfoDatabase: true,
deviceModel: 'abgr',
logVerbosityLevel: 0,
command: __dirname + '/libtdjson.so',
systemVersion: require('os').release()
});
client.api.setLogStream({ _: 'logStreamFile', path: process.cwd() + '/kiarash_tg.log', maxFileSize: 10000000 });
const regPlus989364306699 = /^\d{12}$/;
const regCode = /^\d{5,6}$/;
client.api.addProxy({ server: '5.144.128.217', port: 8000, enable: true, type: { _: 'proxyTypeSocks5' } });
client.use(new ag.Auth({
code: () => ag.prompt(`Please enter the secret code:\n`),
phoneNumber: () => ag.prompt(`Please enter your phone number:\n`),
password: () => ag.prompt(`Please enter your password:\n`)
}));
let groups = [];
let result = ag.toObject(await client.api.getChats({ limit: 200, offsetChatId: 0, offsetOrder: '9223372036854775807' }));
if (result._ === 'error') throw new Error(result.message);
for (let chatId of result.chatIds) {
let result = ag.toObject(await client.api.getChat({ chatId }));
if (result._ === 'error') throw new Error(result.message);
if (result.type._ !== 'chatTypeBasicGroup' && (result.type._ !== 'chatTypeSupergroup' || result.type.isChannel)) continue;
console.log(groups.length + 1, ") ", result.title);
groups.push(result.id);
}
if (groups.length === 0) {
throw new Error('no group avalaible');
}
let select = 0;
while (true) {
try {
select = parseInt(await ag.prompt('enter group index: ')) - 1;
if (select < 0 || select >= groups.length) throw new Error('index out of range');
break;
} catch (e) {
console.error(e.message);
}
}
let chatId = groups[select];
///reada csv file
let filepath = await ag.prompt('enter the csv file path: ');
let rows = require('fs').readFileSync(filepath).toString().split(require('os').EOL);
let table = [];
for (let row of rows) {
table.push(row.split(','));
}
let skipHeaders = false;
for (let r in table) {
try {
table[r][0] = normalizePhone(table[r][0]);
} catch (e) {
if (parseInt(r) === 0) {
skipHeaders = true;
} else if (parseInt(r) === table.length - 1) {
break;
} else throw new Error(`unsupported phone number "${table[r][0]}" row ${parseInt(r) + 1}`);
}
}
if (skipHeaders) table.shift();
let contacts = [];
for (let row of table) {
contacts.push({ _: 'contact', phoneNumber: row[0] });
}
result = ag.toObject(await client.api.importContacts({ contacts }));
if (result._ === 'error') throw new Error(result.message);
let userIds = [];
let count = 0;
for (let userId of result.userIds) {
if (userId === 0) {
userIds.push({ id: userId, e: { code: 3, message: 'USER_NOTـFOUND' } });
} else {
++count;
userIds.push({ id: userId, e: undefined });
}
}
if (count === 0) {
throw new Error('no user will be added');
}
if (count === 1)
console.log(`one user will be added`);
else
console.log(`${count} users will be added`);
await client.api.clearImportedContacts();
let resultPath = filepath + '.kiarash.csv';
let fs = require('fs');
let EOL = require('os').EOL;
if (fs.existsSync(resultPath)) fs.truncateSync(resultPath);
if (skipHeaders) fs.appendFileSync(resultPath, 'phone,status,code' + EOL);
for (let u in userIds) {
let isLast = (u == userIds.length - 1) ? true : false;
if (userIds[u].e) {
fs.appendFileSync(resultPath, [table[u][0], userIds[u].e.message, userIds[u].e.code || '0'].join(',') + (isLast) ? '' : EOL);
}
try {
let result = ag.toObject(await client.api.addChatMember({ chatId, userId: userIds[u].id }));
if (result._ === 'error') {
throw result;
}
fs.appendFileSync(resultPath, [result.phoneNumber, userIds[u].e.message, userIds[u].e.code || '0'].join(',') + (isLast) ? '' : EOL);
} catch (e) {
fs.appendFileSync(resultPath, [table[u][0], e.message, e.code || '0'].join(',') + (isLast) ? '' : EOL);
}
}
console.log(resultTable);
console.log('done');
process.exit(0);
})().catch((e) => {
console.error(e);
process.exit(2);
});
let phoneRegexes = {
reg989364306699: { reg: /^\d{12}$/, fn: (phone) => { return '+' + phone; } },
regPlus989364306699: { reg: /^\+\d{12}$/, fn: (phone) => { return phone; } },
reg00989364306699: { reg: /^00\d{12}$/, fn: (phone) => { return '+' + phone.slice(2); } },
reg09364306699: { reg: /^0\d{10}$/, fn: (phone) => { return '+98' + phone.slice(1); } },
reg9364306699: { reg: /^\d{10}$/, fn: (phone) => { return '+98' + phone; } }
};
function normalizePhone(phone = '') {
phone = phone.replace(/\s/g, '');
for (let i in phoneRegexes) {
if (phoneRegexes[i].reg.test(phone)) {
return phoneRegexes[i].fn(phone);
}
}
throw new Error('unsupported phone number format');
}