0

I have error code 401 response while uploading, so I want to make when I send template of shirt or pants then it will upload to my roblox group. So when I am typing !uploadshirt (I want to upload my shirt template) Usage is: !uploadshirt name:Name of the shirt description:Description of the shirt price:5 Works good but in the end it says Uploading... then Error code response 401. It's the problem with aiohttp session?

The code:

@bot.command()
async def uploadshirt(ctx, *, args):
    name = ""
    description = ""
    price = ""

    for arg in args.split():
        if arg.startswith("name:"):
            name = arg.split("name:")[1].strip()
        elif arg.startswith("description:"):
            description = arg.split("description:")[1].strip()
        elif arg.startswith("price:"):
            price = arg.split("price:")[1].strip()
    
    price = re.sub(r"[^\d.]", "", price)

    await handle_upload(ctx, 'shirt', name, description, price)

@bot.command()
async def uploadpants(ctx, *, args):
    name = ""
    description = ""
    price = ""

    for arg in args.split():
        if arg.startswith("name:"):
            name = arg.split("name:")[1].strip()
        elif arg.startswith("description:"):
            description = arg.split("description:")[1].strip()
        elif arg.startswith("price:"):
            price = arg.split("price:")[1].strip()

    price = re.sub(r"[^\d.]", "", price)

    print("Extracted price:", price)

    await handle_upload(ctx, 'pants', name, description, price)

async def handle_upload(ctx, item_type, name, description, price):
    if ctx.author.id != int(WHITELISTED_ID):
        await ctx.send(f"You are not allowed to upload {item_type}.")
        return

    if not COOKIE:
        await ctx.send(f"Error: Cookie not configured.")
        return

    session = requests.Session()
    session.cookies[".ROBLOSECURITY"] = COOKIE

    req = session.post(url="https://auth.roblox.com/")
    if "X-CSRF-Token" in req.headers:
        session.headers["X-CSRF-Token"] = req.headers["X-CSRF-Token"]

    if not check_robux_balance(COOKIE):
        robux_balance = get_robux_balance(COOKIE)
        await ctx.send(f"Cannot upload. Please send some Robux to the cookie. Robux balance: {robux_balance}")
        return

    await ctx.send(f"Lets start, {ctx.author.name} has {get_robux_balance(COOKIE)} Robux! Please send the {item_type} template.")

    try:
        confirm = await bot.wait_for('message', check=lambda m: m.author == ctx.author and m.channel == ctx.channel, timeout=10)

        if confirm.attachments and confirm.attachments[0].filename.endswith('.png'):
            await ctx.send("Are you sure you want to upload this template? Reply with 'yes' or 'no'.")

            def check_reply(m):
                return m.author == ctx.author and m.channel == ctx.channel and m.content.lower() in ['yes', 'no']

            reply = await bot.wait_for('message', check=check_reply, timeout=10)

            if reply.content.lower() == 'yes':
                await ctx.send("Uploading...")

                if item_type == 'shirt':
                    upload_url = 'https://itemconfiguration.roblox.com/v1/avatar-assets/12/upload'
                elif item_type == 'pants':
                    upload_url = 'https://itemconfiguration.roblox.com/v1/avatar-assets/11/upload'
                else:
                    await ctx.send("Invalid item type.")
                    return

                headers = {
                    'Cookie': COOKIE,
                    'x-csrf-token': get_csrf_token()
                }

                payload = {
                    'name': name,
                    'description': description,
                    'price': price,
                    'groupId': int(GROUP_ID),
                    'isPublic': True
                }

                response = session.post(upload_url, headers=headers, json=payload)
                if response.status_code != 200:
                    await ctx.send(f"Error! Code: {response.status_code}")
                    return

                template = await confirm.attachments[0].read()
                files = {
                    'file': ('template.png', template, 'image/png')
                }

                response = session.post(upload_url, files=files)
                if response.status_code != 200:
                    await ctx.send(f"Error! Code: {response.status_code}")
                    return

                robux_balance = get_robux_balance(COOKIE)
                await ctx.send(f"{item_type.capitalize()} uploaded successfully! Robux balance: {robux_balance}")

            else:
                await ctx.send("Upload canceled.")

        else:
            await ctx.send("No PNG template file found.")

    except asyncio.TimeoutError:
        await ctx.send("Command timeouted. Please run the command again.")
    except (asyncio.TimeoutError, asyncio.CancelledError):
        await ctx.send("Command timeouted or canceled. Please run the command again.")
    except Exception as e:
        await ctx.send(f"Error! Code: {str(e)}")

def check_robux_balance(COOKIE):
    session = requests.Session()
    session.cookies[".ROBLOSECURITY"] = COOKIE
    req = session.post(url="https://auth.roblox.com/")

    if "X-CSRF-Token" in req.headers:
        session.headers["X-CSRF-Token"] = req.headers["X-CSRF-Token"]

    req2 = session.post(url="https://auth.roblox.com/")

    response = session.get("https://economy.roblox.com/v1/user/currency")

    if response.status_code == 200:
        data = response.json()
        robux_balance = data['robux']

        return robux_balance > 0

    return False

def get_robux_balance(COOKIE):
    session = requests.Session()
    session.cookies[".ROBLOSECURITY"] = COOKIE
    req = session.post(url="https://auth.roblox.com/")
    
    if "X-CSRF-Token" in req.headers:
        session.headers["X-CSRF-Token"] = req.headers["X-CSRF-Token"]
    
    req2 = session.post(url="https://auth.roblox.com/")
    
    response = session.get("https://economy.roblox.com/v1/user/currency")
    
    if response.status_code == 200:
        data = response.json()
        robux_balance = data.get("robux", 0)
        return robux_balance
    else:
        print("Response status code:", response.status_code)
    
    return 0

def get_csrf_token():
    response = requests.post('https://auth.roblox.com/')
    csrf_token = response.headers.get('x-csrf-token')

    return csrf_token

Is there any way to fix response error 401 and improve code? does it need X-CSRF-TOKEN for uploading?

0 Answers0