Skip to content

Commit

Permalink
Merge pull request shamhi#84 from headNbyte/main
Browse files Browse the repository at this point in the history
fix
  • Loading branch information
shamhi authored Jun 15, 2024
2 parents 2cfaf7a + 3e26d1c commit c6c41b2
Show file tree
Hide file tree
Showing 12 changed files with 153 additions and 48 deletions.
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
webdriver
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,4 @@ cython_debug/
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
webdriver/
8 changes: 4 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
FROM python:3.10.11-alpine3.18

WORKDIR app/
WORKDIR /app

COPY requirements.txt requirements.txt
COPY . /app

RUN pip3 install --upgrade pip setuptools wheel
RUN pip3 install --no-warn-script-location --no-cache-dir -r requirements.txt

COPY . .
RUN apk add --no-cache firefox

CMD ["python3", "main.py", "-a", "2"]
CMD ["python3", "main.py", "-a", "2"]
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
~/TapSwapBot >>> pip3 install -r requirements.txt
~/TapSwapBot >>> cp .env-example .env
~/TapSwapBot >>> nano .env # Здесь вы обязательно должны указать ваши API_ID и API_HASH , остальное берется по умолчанию
~/TapSwapBot >>> sh install.sh
~/TapSwapBot >>> python3 main.py

# Windows
Expand Down
2 changes: 1 addition & 1 deletion bot/config/proxies.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ type://user:pass@ip:port
type://user:pass:ip:port
type://ip:port:user:pass
type://ip:port@user:pass
type://ip:port
type://ip:port
4 changes: 2 additions & 2 deletions bot/core/headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
'Sec-Ch-Ua-Mobile': '?1',
'Sec-Ch-Ua-Platform': '"Android"',
'X-App': 'tapswap_server',
'X-Cv': '621',
'X-bot': 'no'
'X-Bot': 'no',
'X-Cv': '624',
}
30 changes: 20 additions & 10 deletions bot/core/tapper.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
from time import time
from random import randint
import traceback
from urllib.parse import unquote

import aiohttp
Expand All @@ -19,10 +20,11 @@


class Tapper:
def __init__(self, tg_client: Client):
def __init__(self, tg_client: Client, lock: asyncio.Lock):
self.session_name = tg_client.name
self.tg_client = tg_client
self.user_id = 0
self.lock = lock

async def get_tg_web_data(self, proxy: str | None) -> str:
if proxy:
Expand Down Expand Up @@ -97,24 +99,32 @@ async def login(self, http_client: aiohttp.ClientSession, tg_web_data: str) -> t
response.raise_for_status()

response_json = await response.json()
wait_s = response_json.get('wait_s')
if wait_s:
logger.error(f"{self.session_name} | App overloaded, waiting for: {wait_s}")
await asyncio.sleep(delay=wait_s)
return self.login(http_client, tg_web_data)

chq = response_json.get('chq')

if chq:
chq_result = extract_chq(chq=chq)
async with self.lock:
chq_result = extract_chq(chq=chq)

response = await http_client.post(url='https://api.tapswap.ai/api/account/login',
json={"chr": chq_result, "init_data": tg_web_data, "referrer": ""})
response_text = await response.text()
response.raise_for_status()
response = await http_client.post(url='https://api.tapswap.ai/api/account/login',
json={"chr": chq_result, "init_data": tg_web_data, "referrer": ""})
response_text = await response.text()
response.raise_for_status()

response_json = await response.json()

access_token = response_json['access_token']
profile_data = response_json

return profile_data, access_token
except Exception as error:
traceback.print_exc()
logger.error(f"{self.session_name} | Unknown error while getting Access Token: {error} | "
f"Response text: {escape_html(response_text)[:128]}...")
f"Response text: {escape_html(response_text)}...")
await asyncio.sleep(delay=3)

async def apply_boost(self, http_client: aiohttp.ClientSession, boost_type: str) -> bool:
Expand Down Expand Up @@ -391,8 +401,8 @@ async def run(self, proxy: str | None) -> None:
await asyncio.sleep(delay=sleep_between_clicks)


async def run_tapper(tg_client: Client, proxy: str | None):
async def run_tapper(tg_client: Client, proxy: str | None, lock: asyncio.Lock):
try:
await Tapper(tg_client=tg_client).run(proxy=proxy)
await Tapper(tg_client=tg_client, lock=lock).run(proxy=proxy)
except InvalidSession:
logger.error(f"{tg_client.name} | Invalid Session")
9 changes: 6 additions & 3 deletions bot/utils/launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@

start_text = """
▀▀█▀▀ █▀▀█ █▀▀█ ░█▀▀▀█ █ █ █▀▀█ █▀▀█ ░█▀▀█ █▀▀█ ▀▀█▀▀
░█ █▄▄█ █ █ ▀▀▀▄▄ █▄█▄█ █▄▄█ █ █ ░█▀▀▄ █ █ █
░█ ▀ ▀ █▀▀▀ ░█▄▄▄█ ▀ ▀ ▀ ▀ █▀▀▀ ░█▄▄█ ▀▀▀▀ ▀
▀▀█▀▀ █▀▀█ █▀▀█ ░█▀▀▀█ █ █ █▀▀█ █▀▀█ ░█▀▀█ █▀▀█ ▀▀█▀▀
░█ █▄▄█ █ █ ▀▀▀▄▄ █▄█▄█ █▄▄█ █ █ ░█▀▀▄ █ █ █
░█ ▀ ▀ █▀▀▀ ░█▄▄▄█ ▀ ▀ ▀ ▀ █▀▀▀ ░█▄▄█ ▀▀▀▀ ▀
Select an action:
Expand Down Expand Up @@ -111,11 +111,14 @@ async def process() -> None:
async def run_tasks(tg_clients: list[Client]):
proxies = get_proxies()
proxies_cycle = cycle(proxies) if proxies else None
lock = asyncio.Lock()

tasks = [
asyncio.create_task(
run_tapper(
tg_client=tg_client,
proxy=next(proxies_cycle) if proxies_cycle else None,
lock=lock,
)
)
for tg_client in tg_clients
Expand Down
110 changes: 85 additions & 25 deletions bot/utils/scripts.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,66 @@
import re
import glob
import os
import asyncio
from typing import Union

from pyrogram import Client
from pyrogram.types import Message
from bs4 import BeautifulSoup

from bot.utils.emojis import num, StaticEmoji
from bot.utils import logger
from bs4 import BeautifulSoup

import pathlib
import shutil
from selenium import webdriver
from multiprocessing import Queue



def get_session_names() -> list[str]:
session_names = glob.glob("sessions/*.session")
session_names = [
os.path.splitext(os.path.basename(file))[0] for file in session_names
]

return session_names




if os.name == "posix":
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from webdriver_manager.firefox import GeckoDriverManager

web_options = FirefoxOptions
web_service = FirefoxService
web_manager = GeckoDriverManager
web_driver = webdriver.Firefox
else:
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options as ChromeOptions
from webdriver_manager.chrome import ChromeDriverManager

web_options = ChromeOptions
web_service = ChromeService
web_manager = ChromeDriverManager
web_driver = webdriver.Chrome

if not pathlib.Path("webdriver").exists() or len(list(pathlib.Path("webdriver").iterdir())) == 0:
logger.info("Downloading webdriver. It may take some time...")
pathlib.Path("webdriver").mkdir(parents=True, exist_ok=True)
webdriver_path = pathlib.Path(web_manager().install())
shutil.move(webdriver_path, f"webdriver/{webdriver_path.name}")
logger.info("Webdriver downloaded successfully")

webdriver_path = next(pathlib.Path("webdriver").iterdir()).as_posix()

options = web_options()
options.add_argument("--headless")
driver = None

session_queue = Queue()


def get_command_args(
Expand All @@ -16,18 +70,14 @@ def get_command_args(
) -> str:
if isinstance(message, str):
return message.split(f"{prefixes}{command}", maxsplit=1)[-1].strip()

if isinstance(command, str):
args = message.text.split(f"{prefixes}{command}", maxsplit=1)[-1].strip()
return args

elif isinstance(command, list):
for cmd in command:
args = message.text.split(f"{prefixes}{cmd}", maxsplit=1)[-1]

if args != message.text:
return args.strip()

return ""


Expand All @@ -54,6 +104,7 @@ def get_help_text():
</b>"""



async def stop_tasks(client: Client = None) -> None:
if client:
all_tasks = asyncio.all_tasks(loop=client.loop)
Expand All @@ -70,12 +121,16 @@ async def stop_tasks(client: Client = None) -> None:
except:
...


def escape_html(text: str) -> str:
return text.replace('<', '\\<').replace('>', '\\>')


def extract_chq(chq: str) -> int:
global driver

if driver is None:
driver = web_driver(service=web_service(webdriver_path), options=options)

chq_length = len(chq)

bytes_array = bytearray(chq_length // 2)
Expand All @@ -85,28 +140,33 @@ def extract_chq(chq: str) -> int:
bytes_array[i // 2] = int(chq[i:i + 2], 16)

xor_bytes = bytearray(t ^ xor_key for t in bytes_array)
decoded_xor = xor_bytes.decode('unicode_escape')
decoded_xor = xor_bytes.decode('utf-8')

driver.execute_script("""
var chrStub = document.createElement("div");
chrStub.id = "_chr_";
document.body.appendChild(chrStub);
""")

html = re.search(r'innerHTML.+?=(.+?);', decoded_xor, re.DOTALL | re.I | re.M).group(1).strip()
html = re.sub(r"\'\+\'", "", html, flags=re.M | re.I)
soup = BeautifulSoup(html, 'html.parser')
fixed_xor = repr(decoded_xor).replace("`", "\\`")

div_elements = soup.find_all('div')
codes = {}
for div in div_elements:
if 'id' in div.attrs and '_v' in div.attrs:
codes[div['id']] = div['_v']
k = driver.execute_script(f"""
try {{
return eval(`{fixed_xor[1:-1]}`);
}} catch (e) {{
return e;
}}
""")

va = re.search(r'''var(?:\s+)?i(?:\s+)?=.+?\([\'\"](\w+)[\'\"]\).+?,''', decoded_xor, flags=re.M | re.I).group(1)
vb = re.search(r'''\,(?:\s+)?j(?:\s+)?=.+?\([\'\"](\w+)[\'\"]\).+?,''', decoded_xor, flags=re.M | re.I).group(1)
r = re.search(r'''k(?:\s+)?%=(?:\s+)?(\w+)''', decoded_xor, flags=re.M | re.I).group(1)
session_queue.put(1)

i = int(codes[va])
j = int(codes[vb])
k = int(i)
if len(get_session_names()) == session_queue.qsize():
logger.info("All sessions are closed. Quitting driver...")
driver.quit()
driver = None

k *= k
k *= j
k %= int(r, 16)
while session_queue.qsize() > 0:
session_queue.get()

return k

4 changes: 1 addition & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
version: '3'
services:
bot:
tapswap-bot:
container_name: 'TapSwapBot'
build:
context: .
stop_signal: SIGINT
restart: unless-stopped
command: "python3 main.py -a 2"
volumes:
- .:/app
31 changes: 31 additions & 0 deletions install.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/bin/bash

# Update package list and install prerequisites
echo "Updating package list and installing prerequisites..."
sudo apt update
sudo apt install -y software-properties-common

# Add Mozilla Team PPA
echo "Adding Mozilla Team PPA..."
sudo add-apt-repository -y ppa:mozillateam/ppa

# Set package pinning preferences
echo "Setting package pinning preferences..."
sudo tee /etc/apt/preferences.d/mozilla-firefox <<EOF
Package: *
Pin: release o=LP-PPA-mozillateam
Pin-Priority: 1001
EOF

# Configure unattended upgrades for Mozilla Team PPA
echo "Configuring unattended upgrades for Mozilla Team PPA..."
sudo tee /etc/apt/apt.conf.d/51unattended-upgrades-firefox <<EOF
Unattended-Upgrade::Allowed-Origins:: "LP-PPA-mozillateam:\${distro_codename}";
EOF

# Update package list again and install Firefox
echo "Updating package list and installing Firefox..."
sudo apt update
sudo apt install -y firefox

echo "Installation complete!"
Binary file modified requirements.txt
Binary file not shown.

0 comments on commit c6c41b2

Please sign in to comment.