Python: Subscribe to channel

Examples

Listen to broadcast messages

channel = supabase.channel("room1")

def on_subscribe(status, err):
  if status == RealtimeSubscribeStates.SUBSCRIBED:
    channel.send_broadcast('cursor-pos', \{ "x": random.random(), "y": random.random() \})

def handle_broadcast(payload):
  print("Cursor position received!", payload)

channel.on_broadcast(event="cursor-pos", callback=handle_broadcast).subscribe(on_subscribe)

Listen to presence sync

channel = supabase.channel('room1')

def on_subscribe(status, err):
  if status == RealtimeSubscribeStates.SUBSCRIBED:
    channel.track(\{ "online_at": datetime.datetime.now().isoformat() \})

def handle_presence_sync():
  print('Synced presence state: ', channel.presence.state)

channel.on_presence_sync(callback=handle_presence_sync).subscribe(on_subscribe)

Listen to presence join

channel = supabase.channel('room1')

def handle_presence_join(key, current_presence, new_presence):
  print('Newly joined presences: ', new_presence)

def on_subscribe(status, err):
  if status == RealtimeSubscribeStates.SUBSCRIBED:
    channel.track(\{ "online_at": datetime.datetime.now().isoformat() \})

channel.on_presence_join(callback=handle_presence_join).subscribe(on_subscribe)

Listen to presence leave

channel = supabase.channel('room1')

def handle_presence_leave(key, current_presence, left_presence):
  print('Newly left presences: ', left_presence)

def on_subscribe(status, err):
  if status == RealtimeSubscribeStates.SUBSCRIBED:
    channel.track(\{ "online_at": datetime.datetime.now().isoformat() \})
    channel.untrack()

channel.on_presence_leave(callback=handle_presence_leave).subscribe(on_subscribe)

Listen to all database changes

supabase
  .channel('room1')
  .on_postgres_changes("*", schema="*", callback=handle_record_updated)
  .subscribe()

Listen to a specific table

supabase
  .channel('room1')
  .on_postgres_changes("*", schema="public", table="countries", callback=handle_record_updated)
  .subscribe()

Listen to inserts

supabase
  .channel('room1')
  .on_postgres_changes("INSERT", schema="public", table="countries", callback=handle_record_inserted)
  .subscribe()

Listen to updates

supabase
  .channel('room1')
  .on_postgres_changes("UPDATE", schema="public", table="countries", callback=handle_record_updated)
  .subscribe()

Listen to deletes

supabase
  .channel('room1')
  .on_postgres_changes("DELETE", schema="public", table="countries", callback=handle_record_deleted)
  .subscribe()

Listen to multiple events

supabase
  .channel('room1')
  .on_postgres_changes("INSERT", schema="public", table="countries", callback=handle_record_inserted)
  .on_postgres_changes("DELETE", schema="public", table="countries", callback=handle_record_deleted)
  .subscribe()

Listen to row level changes

supabase
  .channel('room1')
  .on_postgres_changes("UPDATE", schema="public", table="countries", filter="id=eq.200", callback=handle_record_updated)
  .subscribe()