Database Connectivity Issue with Supabase Integration

I am experiencing a 404: NOT_FOUNDCode: NOT_FOUNDID: cdg1::jrnqx-1737508046559-0a0ea22d6922 error when trying to connect my Telegram bot (hosted on Vercel) to a Supabase database. Here are the key details:

  1. Supabase Configuration:
  • Supabase URL and Service Role Key are correctly set as environment variables.
  • The database project includes a users table, and Row Level Security (RLS) is enabled with appropriate policies for SELECT, INSERT, and UPDATE operations.
  • A storage bucket (william) has been created, and access policies for operations (SELECT, INSERT, etc.) have been configured.
  1. Vercel Configuration:
  • My Telegram bot is hosted on Vercel and uses the supabase-py library to connect to Supabase.
  • All necessary environment variables (SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY) have been added to Vercel’s project settings.
  1. Issue:
  • Database requests from the bot (such as inserting or fetching data) result in a 404: NOT_FOUND error.
  • Supabase logs do not show any activity, suggesting the requests are not reaching the database.
  1. Steps Taken to Troubleshoot:
  • Verified that the SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are correct and working locally.
  • Confirmed that the users table exists and has the proper schema for storing user data.
  • Tested Supabase policies to ensure RLS is not blocking access.
  • Confirmed that the william bucket exists and is accessible with valid policies.

Current Behavior:
My webhook, hosted on Vercel, is unable to connect to the Supabase database. It keeps returning the error:
404: NOT_FOUNDCode: NOT_FOUNDID: cdg1::jrnqx-1737508046559-0a0ea22d6922

Expected Behavior:
The webhook should successfully communicate with the Supabase database and return bot is running “Bot is running”

from http.server import BaseHTTPRequestHandler
import os
import json
import asyncio
import requests
import datetime
import io
from telebot.async_telebot import AsyncTelebot
from supabase import create_client, Client
from telebot import types
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo

# Initialize Bot
BOT_TOKEN = os.environ.get('BOT_TOKEN')
bot = AsyncTelebot(BOT_TOKEN)

# Initialize Supabase
SUPABASE_URL = os.environ.get("SUPABASE_URL")
SUPABASE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)

# Supabase storage bucket
bucket_name = "william"

def generate_start_keyboard():
    keyboard = InlineKeyboardMarkup()
    keyboard.add(InlineKeyboardButton("Open William app", web_app=WebAppInfo(url="https://williamfrontend.netlify.app/")))
    return keyboard

@bot.message_handler(commands=['start'])
async def start(message):
    user_id = str(message.from_user.id)
    user_first_name = str(message.from_user.first_name)
    user_last_name = message.from_user.last_name
    user_username = message.from_user.username
    user_language_code = str(message.from_user.language_code)
    is_premium = getattr(message.from_user, 'is_premium', False)
    text = message.text.split()

    welcome_message = (
        f"Hi, {user_first_name}! đź‘‹\n\n"
        f"Welcome to William Drop Memecoin Airdrop!\n\n"
        f"Here you can earn coins by mining or by spending!\n\n"
        f"Invite friends to earn more coins and level up faster! 🚀"
    )

    try:
        user_data = {
            'userImage': None,
            'firstName': user_first_name,
            'lastName': user_last_name,
            'username': user_username,
            'languageCode': user_language_code,
            'isPremium': is_premium,
            'referrals': {},
            'balance': 0,
            'mineRate': 0.001,
            'isMining': False,
            'miningStartedTime': None,
            'daily': {
                'claimedTime': None,
                'claimedDay': 0,
            },
            'links': None,
        }

        photos = await bot.get_user_profile_photos(user_id, limit=1)
        if photos.total_count > 0:
            file_id = photos.photos[0][-1].file_id
            file_info = await bot.get_file(file_id)
            file_path = file_info.file_path
            file_url = f"https://api.telegram.org/file/bot{BOT_TOKEN}/{file_path}"

            # Download the image
            response = requests.get(file_url)
            if response.status_code == 200:
                # Wrap content in a file-like object
                file_data = io.BytesIO(response.content)
                file_name = f"user_images/{user_id}.jpg"
                supabase.storage.from_(bucket_name).upload(file_name, file_data)

                # Generate public URL
                user_image = supabase.storage.from_(bucket_name).get_public_url(file_name)
                user_data['userImage'] = user_image

        # Handle referral code
        if len(text) > 1 and text[1].startswith('ref_'):
            referrer_id = text[1][4:]
            referrer = supabase.table('users').select("*").eq('id', referrer_id).execute()

            if referrer.data:
                referrer_data = referrer.data[0]
                user_data['referredBy'] = referrer_id

                bonus_amount = 500 if is_premium else 100
                new_balance = referrer_data['balance'] + bonus_amount
                referrals = referrer_data.get('referrals', {}) or {}

                referrals[user_id] = {
                    'addedValue': bonus_amount,
                    'firstName': user_first_name,
                    'lastName': user_last_name,
                    'userImage': user_data['userImage'],
                }

                # Update referrer in the database
                supabase.table('users').update({
                    'balance': new_balance,
                    'referrals': referrals,
                }).eq('id', referrer_id).execute()

        # Save user data to the database
        supabase.table('users').upsert(user_data).execute()

        keyboard = generate_start_keyboard()
        await bot.reply_to(message, welcome_message, reply_markup=keyboard)

    except Exception as e:
        error_message = "Error. Please try again!"
        await bot.reply_to(message, error_message)
        print(f"Error: {str(e)}")

class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        update_dict = json.loads(post_data.decode('utf-8'))

        asyncio.run(self.process_update(update_dict))

        self.send_response(200)
        self.end_headers()

    async def process_update(self, update_dict):
        update = types.Update.de_json(update_dict)
        await bot.process_new_updates([update])

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write("Bot is running".encode())

Configuration:

  • Environment variables are set in Vercel:
    • SUPABASE_URL
    • SUPABASE_SERVICE_ROLE_KEY
  • Database users table schema has been created in Supabase.
  • Row-Level Security (RLS) is enabled for the users table, and appropriate policies for INSERT and SELECT operations are in place.

Steps to Reproduce:

  • Deploy the webhook to Vercel.
  • Trigger any operation that communicates with the Supabase database (e.g., inserting a new user).

github for links https://github.com/Mhatem1995/Williambackend/tree/main/api

Project Information

Framework: Python, http.server for handling requests, using supabase-py for database interaction.

Environment: Deployed on Vercel, environment variables are configured properly in the Vercel dashboard.

Project Settings: The users table is in the public schema. Realtime is enabled, and RLS policies have been configured to allow authenticated access.

screens:-

https://williambackend.vercel.app

There’s another community post with 404 debugging tips that might be helpful. Please give these solutions a try and let us know how it goes.

A human should be around soon to offer more advice. But you can also get helpful information quickly by asking v0.

Hi @mhatem1995, welcome to the Vercel Community!

Sorry that you’re facing this issue. I must say you did a good writeup for the issue, kudos for that :raised_hands:

Now, from your code I see you get a 404 error which is usually related to your application not being deployed correctly.

Can you try changing your vercel.json to this:

{
  "rewrites": [{ "source": "/webhook", "destination": "api/webhook.py" }]
}

The project structure should also be different. The api folder and requirements.txt, vercel.json files should be at the same level, as follows:

Also, please redeploy your application after making this change.

If the issue still persists, I’d request you to share the URL you are setting up for the webhook.

1 Like

i did what you advised me to do and new error’s appeared i checked environment variables (BOT_TOKEN, SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY) are configured in the Vercel project

Hi @mhatem1995, thanks for sharing this information. Have you checked the server logs to see anything useful?

I’d recommend adding error handling to your function and logging the error to console.

1 Like

thank you for trying to help me after checking webook.py i found what causing the serveless function crashed error was from the AsyncTelebot class cannot be imported from telebot.async_telebot. The problem may be due to a typo or incorrect import statement. Specifically, the error message is to import AsyncTeleBot (with an uppercase “B” in TeleBot) instead of AsyncTelebot. after doing it worked bout still geting this

no errors in the log now bout i noticed the id for problem changed ID: cdg1::slsb8-1737541510510-11985de6adf7

Hi @mhatem1995, glad that you found the initial issue.

The 404 errors usually means that the URL is not pointing to a function. Are you sure that the function is configured correctly?

If you need more help, please share your public repo or a minimal reproducible example. That will let us all work together from the same code to figure out what’s going wrong.

I tested the changes with curl and it works. But when I visit the URL i get an error:

I added the api for the bot with Vercel link to see if telegram see it and it worked but I still see the 404 error :rofl: :sweat_smile:

okay this is weird when i go here https://william-backend.vercel.app/api/webhook
i see the bot is running bout when i remove /api/webhook and go for the main directory it show the 404 error did i installed the project wrong or something ???! i add small fix for Content-Type Header: It tells the browser that the response is JSON (application/json).
JSON Response: Browsers can correctly render or handle JSON objects. and here is repo link https://github.com/Mhatem1995/WilliamBackend/tree/main

iam very sorry for the to any messages i found the problem was root route (/) is not properly set up, while the specific /api/webhook route works as expected. so i fixed the vercel.json file with this

{
  "version": 2,
  "builds": [
    {
      "src": "api/webhook.py",
      "use": "@vercel/python"
    }
  ],
  "routes": [
    {
      "src": "/",
      "dest": "api/webhook.py"
    },
    {
      "src": "/api/webhook",
      "dest": "api/webhook.py"
    }
  ]
}


and worked just as i wanted hope no new erros appear :pray: :rofl:

1 Like

Hi @mhatem1995, glad to see you found a solution and thanks for sharing it here.

I see you are using legacy configuration options such as routes and builds in your vercel.json file. While these options may not cause issues directly, it’s better to use the updated options to make use of the latest features and avoid issues.

If I understand correctly, you want all requests to be routed to the /api/webhook endpoint? If so, your updated vercel.json should look like this:

{
    "rewrites": [{ "source": "/(.*)", "destination": "/api/webhook" }],
}

To learn more, see Upgrading legacy route guide.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.