add bot tasks support

This commit is contained in:
minicx 2022-12-12 00:44:05 +03:00
parent 0dd715917e
commit bc787d8bfe
5 changed files with 266 additions and 91 deletions

View File

@ -4,13 +4,13 @@ import { sleep } from "telegram/Helpers";
import { AccountInterface } from "./interfaces/databaseInterface";
import { prevTaskInterface } from "./interfaces/otherInterfaces";
import logger from "./logger";
import { waitNewMessages } from "./utils";
import { getMessagesByEntity, NoNewMessages, waitNewMessages } from "./utils";
import {settings} from './database'
import { isNull } from "lodash";
export const vertification=async function (client: telegram.TelegramClient,worker: AccountInterface,hero: Hero,url: string,botEntity: telegram.Api.Chat | telegram.Api.User,idOfLastMessage: number) {
await hero.goto(url,{timeoutMs:1300_000});
await hero.goto(url,{timeoutMs:2_000_000});
await hero.waitForLoad('AllContentLoaded',{timeoutMs:1180_000});
const captchaButton=hero.document.querySelector('button.g-recaptcha.btn.btn-primary');
if (captchaButton!=null){
@ -54,7 +54,7 @@ export const doSitesTasks=async function (client: telegram.TelegramClient,worker
const urlButton=task.buttons![0][0];
const skipButton=task.buttons![0][1];
await hero.goto(urlButton.url!,{timeoutMs:1300_000});
await hero.goto(urlButton.url!,{timeoutMs:2_000_000});
await hero.waitForLoad('AllContentLoaded',{timeoutMs:1180_000});
@ -129,7 +129,6 @@ export const doSitesTasks=async function (client: telegram.TelegramClient,worker
await waitNewMessages(client,worker,botEntity,task.id);
const afterTask:telegram.Api.Message=(await client.getMessages(botEntity,{
minId:task.id,
reverse:true,
limit:100
})).filter((value)=>{return value.message.includes(settings.botMessages.taskComplete)})[0];
prevTask.lastMessage=(await client.getMessages(botEntity,{
@ -181,7 +180,7 @@ export const doChatsTasks=async function (client: telegram.TelegramClient,worker
let groupLink='';
if (urlButton.url?.includes('hkbot')==true){
await hero.goto(urlButton.url,{timeoutMs:1300_000});
await hero.goto(urlButton.url,{timeoutMs:2_000_000});
await hero.waitForLoad('AllContentLoaded',{timeoutMs:1180_000});
let captchaButton=hero.document.querySelector('button.g-recaptcha.btn.btn-primary');
if (isNull(captchaButton)){
@ -323,7 +322,6 @@ export const doChatsTasks=async function (client: telegram.TelegramClient,worker
await waitNewMessages(client,worker,botEntity,task.id);
const afterTask=(await client.getMessages(botEntity,{
minId: task.id,
reverse:true,
limit:100
})).filter((value)=>{
if (value.message.includes(settings.botMessages.notInGroup) || value.message.includes(settings.botMessages.taskComplete)){
@ -373,4 +371,160 @@ export const doChatsTasks=async function (client: telegram.TelegramClient,worker
throw new Error(`Check out last message of ${worker.phoneNumber}`)
}
}
}
export const doBotTasks=async function(client: telegram.TelegramClient,worker: AccountInterface,hero: Hero,botEntity: telegram.Api.Chat | telegram.Api.User,tasksSelector: telegram.Api.Message) {
const taskBotsButton=tasksSelector.buttons![1][2];
let prevTask: prevTaskInterface={
task:tasksSelector,
lastMessage:tasksSelector
};
mainLoop:
while (true){
await sleep(2000);
await taskBotsButton.click({sharePhone: false});
await waitNewMessages(client,worker,botEntity,prevTask.lastMessage.id);
let task: telegram.Api.Message;
[(prevTask.lastMessage),task]=(await client.getMessages(botEntity,{
minId:prevTask.lastMessage.id,
limit:2
}));
if (task===undefined){
task=prevTask.lastMessage
}
if (task.buttonCount==3){
logger.info(`New bot task | ${worker.phoneNumber}`);
const urlButton=task.buttons![0][0];
const skipButton=task.buttons![0][1];
let botLink='@';
if (urlButton.url?.includes('hkbot')==true){
await hero.goto(urlButton.url,{timeoutMs:2_000_000});
await hero.waitForLoad('AllContentLoaded',{timeoutMs:1180_000});
let captchaButton=hero.document.querySelector('button.g-recaptcha.btn.btn-primary');
if (isNull(captchaButton)){
if (prevTask.task.message==task.message){
logger.warn(`Same tasks detected on ${worker.phoneNumber}... Skipping due captcha isnt detected......`);
await skipButton.click({sharePhone: false});
} else {
logger.warn(`Captcha isnt detected... | ${worker.phoneNumber}`);
}
await waitNewMessages(client,worker,botEntity,prevTask.lastMessage.id);
const cancelMessage=(await client.sendMessage(botEntity,{message:'/cancel'}));
await waitNewMessages(client,worker,botEntity,cancelMessage.id);
prevTask.lastMessage=(await client.getMessages(botEntity,{
minId:cancelMessage.id
}))[0];
prevTask.task=task;
continue mainLoop;
}
const now=new Date()
while (captchaButton!=null && await hero.activeTab.url==urlButton.url!){
if ((+(new Date())-+now)/1000>2*60){
if ( (await captchaButton.$isClickable)==false){
await skipButton.click({sharePhone: false});
await waitNewMessages(client,worker,botEntity,prevTask.lastMessage.id);
const cancelMessage=(await client.sendMessage(botEntity,{message:'/cancel'}));
await waitNewMessages(client,worker,botEntity,cancelMessage.id);
prevTask.lastMessage=(await client.getMessages(botEntity,{
minId:cancelMessage.id
}))[0];
prevTask.task=task;
continue mainLoop;
}
logger.warn(`Anomaly activity in browser. Please checkout`);
await hero.reload();
}
const isCaptchaPassed=hero.document.querySelector("input[id='recaptcha-token']");
if ((isCaptchaPassed==null || await isCaptchaPassed.$isVisible==false) ){
if (await captchaButton.$isClickable){
try {
await hero.interact({click:{element: captchaButton, verification: 'exactElement'}});
} catch( err){
logger.warn(`Some error due clicking | ${worker.phoneNumber}`);
continue mainLoop;
}
}
await sleep(1000);
captchaButton=hero.document.querySelector('button.g-recaptcha.btn.btn-primary');
} else {
logger.error("catpcha detected");
throw new Error("Auhtung captcha detected");
}
}
botLink+=(await hero.url).replace(/(^\w+:|^)\/\/(?:t|telegram)\.(?:me|dog)\//i,'')!.replace(/(?:\?start=)[A-Za-z0-9]+/i,'')!
} else {
botLink+=urlButton.url?.replace(/(^\w+:|^)\/\/(?:t|telegram)\.(?:me|dog)\//i,'')!.replace(/(?:\?start=)[A-Za-z0-9]+/i,'')!
}
await client.invoke(
new telegram.Api.contacts.Unblock({
id: botLink
}));
try{
await waitNewMessages(client,worker,botLink,(await client.sendMessage(botLink,{message:'/start'})).id);
} catch( err){
if (err instanceof NoNewMessages){
await skipButton.click({sharePhone: false});
await waitNewMessages(client,worker,botEntity,prevTask.lastMessage.id);
const cancelMessage=(await client.sendMessage(botEntity,{message:'/cancel'}));
await waitNewMessages(client,worker,botEntity,cancelMessage.id);
prevTask.lastMessage=(await client.getMessages(botEntity,{
minId:cancelMessage.id
}))[0];
prevTask.task=task;
continue mainLoop;
} else {
throw err
}
}
const forwardMessage=(await (await getMessagesByEntity(client,botLink,botLink,{
limit:1000
}))[0].forwardTo(botEntity))![0];
logger.debug(`Forwarded ID is ${forwardMessage.id}`)
await waitNewMessages(client,worker,botEntity,prevTask.lastMessage.id);
const afterTask=(await client.getMessages(botEntity,{
minId: prevTask.lastMessage.id,
limit:10
})).filter((value)=>{
console.log(value.message);
if (value.message.includes(settings.botMessages.taskComplete) || value.message.includes(settings.botMessages.oldMessage)){
return true
} else {
return false
}
})[0];
if (afterTask.message.includes(settings.botMessages.taskComplete)==true){
await client.invoke(new telegram.Api.messages.DeleteHistory({
justClear:true,
peer:botLink
}))
await client.invoke(
new telegram.Api.contacts.Block({
id: botLink,
})
);
logger.info(`Bot task complete | ${worker.phoneNumber}`);
} else if (afterTask.message.includes(settings.botMessages.oldMessage)){
logger.warn(`Forwarded message was old | ${worker.phoneNumber}`);
}
const cancelMessage=(await client.sendMessage(botEntity,{message:'/cancel'}));
await waitNewMessages(client,worker,botEntity,cancelMessage.id);
const lastMessage=(await client.getMessages(botEntity,{
minId: cancelMessage.id
}))[0];
prevTask.task=task;
prevTask.lastMessage=(lastMessage!==undefined) ? lastMessage: afterTask ;
continue;
} else if (task.message.includes(settings.botMessages.taskOver)==true){
logger.info(`Bots tasks completed | ${worker.phoneNumber}`)
break
} else {
logger.error(`Check out last message of ${worker.phoneNumber}`);
throw new Error(`Check out last message of ${worker.phoneNumber}`)
}
}
}

View File

@ -159,7 +159,8 @@ export class Settings implements interfacesSettings.settingsInterface {
tasksSelector: 'Choose an option to start earning your TRX',
taskOver: 'Sorry, there are no new ads available.',
taskComplete: 'Success, ',
notInGroup: 'not entered the chat'
notInGroup: 'not entered the chat',
oldMessage: 'forwarded is old'
},
botButtons: {
earn: '❇️ Earn cryptocurrency',
@ -181,7 +182,7 @@ export class Settings implements interfacesSettings.settingsInterface {
mainCrypto: "TRX";
minimalToWithdraw: number;
maxRefferals: number;
botMessages: { verification: string; tasksSelector: string; taskOver: string, taskComplete: string, notInGroup: string};
botMessages: { verification: string; tasksSelector: string; taskOver: string, taskComplete: string, notInGroup: string, oldMessage: string};
botButtons: { earn: string; balance: string; withdraw: string; };
telegramLinks: { botLink: string; groupsToJoin: string[]; };
bypassMode: boolean

View File

@ -12,7 +12,7 @@ import TorControl from "tor-control";
import Miner from '@ulixee/miner';
import Hero from '@ulixee/hero';
import { portsInterface, usedIPInterface } from "./interfaces/otherInterfaces"
import { doSitesTasks, vertification, doChatsTasks } from './automatization';
import { doSitesTasks, vertification, doChatsTasks, doBotTasks } from './automatization';
import ExecuteJsPlugin from '@ulixee/execute-js-plugin';
import _ from 'lodash';
import Docker from 'dockerode';
@ -371,13 +371,21 @@ const farm: () => Promise<void> = async () => {
}
try{
await doSitesTasks(client,worker,hero,botEntity,tasksSelector);
await doChatsTasks(client, worker, hero, botEntity, tasksSelector);
// await doSitesTasks(client,worker,hero,botEntity,tasksSelector);
// await doChatsTasks(client, worker, hero, botEntity, tasksSelector);
try{
await doBotTasks(client, worker, hero, botEntity, tasksSelector);
} catch (err){
await client.sendMessage(botEntity,{message:'/cancel'})
throw err
}
} catch (err){
logger.error(`Some error due doing tasks\n${err}\n${err.stack}`)
}
db.updateUser(worker);
await hero.close();
await client.disconnect();
await sleep(randomAB(settings.sleepTime.betweenSessions[0],settings.sleepTime.betweenSessions[1])*1_000);
}

View File

@ -12,7 +12,8 @@ export interface settingsInterface {
tasksSelector: string,
taskOver: string,
taskComplete: string,
notInGroup: string
notInGroup: string,
oldMessage: string
}
// to send
botButtons:{

169
utils.ts
View File

@ -9,142 +9,153 @@ import { AccountInterface } from "./interfaces/databaseInterface";
import * as telegram from 'telegram';
import axios from "axios";
import cliProgress from "cli-progress"
export const randomAB=function(a:number,b:number){
return Math.floor(Math.random() * (b - a + 1) + a)
export class NoNewMessages extends Error{}
export class DockerIsBrocken extends Error{}
export function randomAB(a: number, b: number) {
return Math.floor(Math.random() * (b - a + 1) + a);
}
export const isBannedByClient=async function(client:telegram.TelegramClient,username: string): Promise<boolean> {
const blockedUsers=(await client.invoke(new telegram.Api.contacts.GetBlocked({limit:2147483647}))).users as telegram.Api.User[];
for (const blockedUser of blockedUsers){
if (blockedUser.username!==undefined && blockedUser.username==username.replace('@','')){
export async function isBannedByClient(client: telegram.TelegramClient, username: string): Promise<boolean> {
const blockedUsers = (await client.invoke(new telegram.Api.contacts.GetBlocked({ limit: 2147483647 }))).users as telegram.Api.User[];
for (const blockedUser of blockedUsers) {
if (blockedUser.username !== undefined && blockedUser.username == username.replace('@', '')) {
return true;
}
}
return false;
}
export const getMessagesByEntity=async function(client:telegram.TelegramClient,chatEntity:telegram.Api.Chat | telegram.Api.User,entity: telegram.Api.User | telegram.Api.User,params={}){
var messages=new telegram.helpers.TotalList<telegram.Api.Message>;
for (const message of await client.getMessages(chatEntity,params)){
if ((message.sender as telegram.Api.User).username==entity.username){
messages.push(message);
export async function getMessagesByEntity(client: telegram.TelegramClient, chatEntity: telegram.Api.Chat | telegram.Api.User | string, entity: telegram.Api.User | string, params = {}) {
let messages = new telegram.helpers.TotalList<telegram.Api.Message>;
if (entity instanceof telegram.Api.User) {
for (const message of await client.getMessages(chatEntity, params)) {
if ((message.sender as telegram.Api.User).username == entity.username) {
messages.push(message);
}
}
} else {
for (const message of await client.getMessages(chatEntity, params)) {
if ((message.sender as telegram.Api.User).username!.includes(entity.replace('@', ''))) {
messages.push(message);
}
}
}
return messages;
}
export const arrayWithoutElementAtIndex = function (arr: AccountInterface[] | [], index: number) {
return arr.filter(function(value, arrIndex) {
return index !== arrIndex;
export function arrayWithoutElementAtIndex(arr: AccountInterface[] | [], index: number) {
return arr.filter(function (value, arrIndex) {
return index !== arrIndex;
});
}
export const getIP=async function (proxyPort: number): Promise<string | null> {
}
export async function getIP(proxyPort: number): Promise<string | null> {
// https://github.com/ulixee/unblocked/blob/main/plugins/default-browser-emulator/lib/helpers/lookupPublicIp.ts
let data: string | PromiseLike<string | null> | null
try{
data=(await axios.get('http://api.ipify.org',{
proxy:{
host:'127.0.0.1',
port:proxyPort
let data: string | PromiseLike<string | null> | null;
try {
data = (await axios.get('http://icanhazip.com/', {
proxy: {
host: '127.0.0.1',
port: proxyPort
},
timeout:100_000
timeout: 100000
})).data;
} catch (err){
} catch (err) {
logger.debug(err);
return null;
}
if ((await data)==null || (await data)!.trim()==""){
return null
}
return await data
}
export const waitNewMessages=async function(client: telegram.TelegramClient,worker: AccountInterface,chatEntity: telegram.Api.Chat | telegram.Api.User,idOfLastMessage: number,timeout: number=20): Promise<void>{
const start_time=new Date();
while ((await client.getMessages(chatEntity,{minId:idOfLastMessage,limit:2147483647})).length==0){
if ((+(new Date())-+start_time)/1000>=timeout){
if ((await data) == null || (await data)!.trim() == "") {
return null;
}
return await data;
}
export async function waitNewMessages(client: telegram.TelegramClient, worker: AccountInterface, chatEntity: telegram.Api.Chat | telegram.Api.User | string, idOfLastMessage: number, timeout: number = 20): Promise<void> {
const start_time = new Date();
while ((await getMessagesByEntity(client, chatEntity, chatEntity as telegram.Api.User | string, { minId: idOfLastMessage, limit: 2147483647 })).length == 0) {
if ((+(new Date()) - +start_time) / 1000 >= timeout) {
logger.error(`${worker.phoneNumber} | Bot didnt answer for ${timeout}s`);
throw new Error('Is bot working?');
throw new NoNewMessages('Is bot working?');
}
}
logger.debug(`${worker.phoneNumber} | Bot answered`);
}
export const startNewTorDocker=async function(proxyPort: number,socksPort: number,controlPort: number,mainProgressBar: cliProgress.MultiBar,timeout: number=200): Promise<Docker.Container>{
timeout*=2;
let docker = new Docker({socketPath: '/var/run/docker.sock'});
let isPulled=false;
mainLoop:
for (const image of await docker.listImages()){
const tags=image.RepoTags;
if (tags!==undefined)
for (const repoTag of tags){
if (repoTag.search('dperson/torproxy:latest')!=-1){
isPulled=true;
export async function startNewTorDocker(proxyPort: number, socksPort: number, controlPort: number, mainProgressBar: cliProgress.MultiBar, timeout: number = 200): Promise<Docker.Container> {
timeout *= 2;
let docker = new Docker({ socketPath: '/var/run/docker.sock' });
let isPulled = false;
mainLoop: for (const image of await docker.listImages()) {
const tags = image.RepoTags;
if (tags !== undefined)
for (const repoTag of tags) {
if (repoTag.search('dperson/torproxy:latest') != -1) {
isPulled = true;
break mainLoop;
}
}
}
}
if (isPulled!=true){
if (isPulled != true) {
await docker.pull('dperson/torproxy:latest');
}
// bugy shit
const options: Docker.ContainerCreateOptions={
Image:'dperson/torproxy',
Env:[
const options: Docker.ContainerCreateOptions = {
Image: 'dperson/torproxy',
Env: [
"PASSWORD=qwerty",
"LOCATION=US",
"TOR_NewCircuitPeriod=50",
],
ExposedPorts:{},
HostConfig:{
PortBindings:{
'8118/tcp':[{
ExposedPorts: {},
HostConfig: {
PortBindings: {
'8118/tcp': [{
HostPort: `${proxyPort}`
}],
'9050/tcp':[{
'9050/tcp': [{
HostPort: `${socksPort}`
}],
'9051/tcp':[{
'9051/tcp': [{
HostPort: `${controlPort}`
}]
}
},
Healthcheck:{
Interval:2*1_000_000_000,
Timeout:50*1_000_000_000,
StartPeriod:50*1_000_000_000,
Healthcheck: {
Interval: 2 * 1000000000,
Timeout: 50 * 1000000000,
StartPeriod: 50 * 1000000000,
// Test:['CMD_SHELL',`curl -sx localhost:8118 'https://check.torproject.org/' | grep -qm1 Congratulations`]
}
}
const container=await docker.createContainer(options);
};
const container = await docker.createContainer(options);
await container.start();
const progressBar=mainProgressBar.create(timeout/2, 0,{status:`Starting docker${(settings.logLevel=='debug') ? ` ${proxyPort} ${socksPort} ${controlPort}` : ''}`});
while ((await container.inspect())!.State.Health!.Status!='healthy'){
const state=(await container.inspect())!.State.Health!.Status
if (progressBar.getProgress()>=timeout){
const progressBar = mainProgressBar.create(timeout / 2, 0, { status: `Starting docker${(settings.logLevel == 'debug') ? ` ${proxyPort} ${socksPort} ${controlPort}` : ''}` });
while ((await container.inspect())!.State.Health!.Status != 'healthy') {
const state = (await container.inspect())!.State.Health!.Status;
if (progressBar.getProgress() >= timeout) {
await container.kill();
progressBar.update(timeout/2,{status:'Failed'})
progressBar.update(timeout / 2, { status: 'Failed' });
progressBar.stop();
throw new Error(`Docker ${container.id} is broken`);
throw new DockerIsBrocken(`Docker ${container.id} is broken`);
}
if (state=='unhealthy'){
if (state == 'unhealthy') {
await container.kill();
progressBar.update(timeout/2,{status:'Docker is unhealthy...'})
progressBar.update(timeout / 2, { status: 'Docker is unhealthy...' });
progressBar.stop();
return await startNewTorDocker(proxyPort,socksPort,controlPort,mainProgressBar,timeout/2);
return await startNewTorDocker(proxyPort, socksPort, controlPort, mainProgressBar, timeout / 2);
}
progressBar.increment();
await sleep(2000);
}
progressBar.update(0,{status:'Started'})
progressBar.update(0, { status: 'Started' });
progressBar.stop();
return container;
}