Search code examples
pythondiscorddiscord.pysupabase

I can't understand why user data isn't being entered into the database


I'm creating a discord bot that will enter user data from the server into the database, such as id, username, nickname and roles. For this I use discord.py and Supabase. It doesn't show any errors in the console.

import discord
from discord.ext import commands

from supabase import create_client, Client

url: str = "my_url"
key: str = "my_key"
supabase: Client = create_client(url, key)

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@bot.event
async def on_ready():
    print("Бот запущен!")

    for  guild in bot.guilds:
        for member in guild.members:
            post = {
                "id": member.id,
                "username": member.name,
                "nickname": member.display_name,
                "role": member.roles
            }

            response = supabase.table("usersDiscord").select("*").eq("id", member.id).execute()
            if response == []:
               response = supabase.table("usersDiscord").insert(post).execute()

@bot.event
async def on_member_join(member):
    post = {
        "id": member.id,
        "username": member.name,
        "nickname": member.display_name,
        "role": member.roles
    }

    response = supabase.table("usersDiscord").select("*").eq("id", member.id).execute()
    if response == []:
        response = supabase.table("usersDiscord").insert(post).execute()

bot.run("my_token")

Perhaps the problem occurs in the place where I am trying to check whether there is already a user with a given id in the database. The purpose of this check is that if such a user exists, then he is not added to the database, and if there is no such user, then he needs to be added.

response = supabase.table("usersDiscord").select("*").eq("id", member.id).execute()
    if response == []:
        response = supabase.table("usersDiscord").insert(post).execute()

Solution

  • There could be several reasons why this is not working. On first sight it doesn't look like it's a code issue.

    • First (and most likely) I would check on the RLS policies (Enable Row Level Security (RLS)) and see if they are correcly setup (you should be able to read/write to the table you want to make operations to)

    • Another reason could be that you are saving on fields that are supposed to be of a format that is not correct (for example ID set to be INT(8) and you are saving a string there)

    • Another reason could be that the fields you are trying to write to are already propagated, or they are part of some other table constrain like a primary key on another table that doesn't have that entry.

    • Usually if there is an error on the Supabase side they tend to tell you what's going on with a reply message. Is there something in the logs that you forgot to post?