shamhi / TapSwapBot

Bot that mines coins in Tapswap
https://t.me/tapswap_bot
295 stars 115 forks source link

Bad Request and How to Solve Them #35

Closed enolife closed 5 months ago

enolife commented 5 months ago

Lets begin...

enolife commented 5 months ago
async def login(self, http_client: aiohttp.ClientSession, tg_web_data: str) -> tuple[dict, str]:
            try:
                payload = {
                    "init_data": tg_web_data,
                    "referrer": "",
                    "bot_key": "app_bot_0"
                }
                response = await http_client.post(
                    url='https://api.tapswap.ai/api/account/login',
                    headers=headers,
                    json=payload  # correctly passing the Python dictionary
                )
                response.raise_for_status()
                response_json = await response.json()
                access_token = response_json["access_token"]
                http_client.headers["Authorization"] = f"Bearer {access_token}"
                profile_data = response_json

                return profile_data, access_token
            except Exception as error:
                logger.error(f"{self.session_name} | Unknown error while getting Access Token: {error}")
                await asyncio.sleep(3)
                raise
enolife commented 5 months ago
async def get_tg_web_data(self, proxy: str | None) -> str:
        if proxy:
            proxy = Proxy.from_str(proxy)
            proxy_dict = dict(
                scheme=proxy.protocol,
                hostname=proxy.host,
                port=proxy.port,
                username=proxy.login,
                password=proxy.password
            )
        else:
            proxy_dict = None

        self.tg_client.proxy = proxy_dict

        try:
            with_tg = True

            if not self.tg_client.is_connected:
                with_tg = False
                try:
                    await self.tg_client.connect()
                except (Unauthorized, UserDeactivated, AuthKeyUnregistered):
                    raise InvalidSession(self.session_name)

            while True:
                try:
                    peer = await self.tg_client.resolve_peer('tapswap_bot')
                    break
                except FloodWait as fl:
                    fls = fl.value

                    logger.warning(f"{self.session_name} | FloodWait {fl}")
                    logger.info(f"{self.session_name} | Sleep {fls}s")

                    await asyncio.sleep(fls+3)

            web_view = await self.tg_client.invoke(RequestWebView(
                peer=peer,
                bot=peer,
                platform='android',
                from_bot_menu=False,
                url='https://app.tapswap.club/'
            ))

            auth_url = web_view.url
            try:
                raw_tg_web_data = auth_url.split('tgWebAppData=', maxsplit=1)[1].split('&tgWebAppVersion', maxsplit=1)[0]
                # Decode the data twice
                decoded_tg_web_data = unquote(unquote(raw_tg_web_data)) 
                # Parse the decoded data
                tg_web_data_parts = decoded_tg_web_data.split('&')
                new_tg_web_data_parts = []
                for part in tg_web_data_parts:
                    if not part.startswith("user="):
                        new_tg_web_data_parts.append(part)
                    else:
                        user_data = json.loads(unquote(part.split('=', 1)[1]))
                        updated_user_data = f"user={quote(json.dumps(user_data))}"
                        new_tg_web_data_parts.append(updated_user_data)
                # Reconstruct the tgWebAppData
                updated_tg_web_data = "&".join(new_tg_web_data_parts)
                # Convert to JSON-compatible string
                tg_web_data = updated_tg_web_data.replace('%20', '')
            except IndexError as e:
                logger.error(f"Failed to extract tgWebAppData from auth_url: {auth_url}. Error: {e}")
            except json.JSONDecodeError as e:
                logger.error(f"Failed to decode user data. Error: {e}")

            if with_tg is False:
                await self.tg_client.disconnect()

            return tg_web_data

        except InvalidSession as error:
            raise error

        except Exception as error:
            logger.error(f"{self.session_name} | Unknown error during Authorization: {error}")
            await asyncio.sleep(delay=3)
enolife commented 5 months ago

send_taps poc with request library

import requests

# Replace with your actual access token
access_token = "access token value"

url = "https://api.tapswap.ai/api/player/submit_taps"
 new_headers = {
            'Authorization': http_client.headers["Authorization"],
            'x-app': 'tapswap_server',
            'Content-Id': '6821615445',
            'Content-Type': 'application/json',
        }
current_time_ms = int(time() * 1000)
number_of_taps = 21
data = {"taps": number_of_taps, "time": current_time_ms}

response = requests.post(url, headers=new_headers, json=data)

print(response.text)
shamhi commented 5 months ago

fixed