How to add components to the canvas using Rhino Python

Hello,
I’m currently testing Rhino and Grasshopper. In one of my tests I’m opening a Grasshopper document from outside (Rhino) using Python. Then I would like to add components and connect their outputs to the nodes of the opened document (active canvas). So far I managed to open the GH document and created a slider, but I couldn’t find a way to add another component like a “curve_primitive_polygon” onto the canvas. Every example I found, creates a slider which is part of the Grasshopper.Kernel.Special library. In the future I would like to add custom, native and plugin components to the canvas and connect them. Is this even possible?

Have you checked this one?

Here is a small example for Rhino Python:
Farhad

import clr
clr.AddReferenceToFileAndPath(r"C:\Program Files\Rhino 7\Plug-ins\Grasshopper\Components\CurveComponents.gha")
from CurveComponents import Component_Polygon, Component_OffsetCurve
from Grasshopper import Instances
from System.Drawing import PointF
import rhinoscriptsyntax as rs
gh = rs.GetPlugInObject('Grasshopper')
if gh.IsEditorLoaded():
    doc = Instances.ActiveCanvas.Document
    if doc:
        polygon_comp = Component_Polygon()
        polygon_comp.CreateAttributes()
        polygon_comp.Attributes.Pivot = PointF(100, 100)
        doc.AddObject(polygon_comp, False)
        
        offset_comp = Component_OffsetCurve()
        offset_comp.CreateAttributes()
        offset_comp.Attributes.Pivot = PointF(200, 100)
        doc.AddObject(offset_comp, False)
        
        offset_comp.Params.Input[0].AddSource(polygon_comp.Params.Output[0])
        gh.RunSolver(True)

Farhad.py (915 Bytes)

I was not aware that the Components need to be referenced. Your snippet is very helpful.
Thank you @Mahdiyar !

It’s also possible to add components using their GUIDs’, Here is another example using InstantiateNewObject.
Farhad

import rhinoscriptsyntax as rs
import clr
from Grasshopper import Instances, Kernel
from System import Guid, Drawing
polygon_component_id = '845527a6-5cea-4ae9-a667-96ae1667a4e8'
offset_instance_id = '2eeaae3b-3de0-4d80-9707-29d7b9a60700'
gh = rs.GetPlugInObject('Grasshopper')
if gh.IsEditorLoaded():
    canvas = Instances.ActiveCanvas
    if canvas:
        canvas.InstantiateNewObject(Guid(polygon_component_id), Drawing.PointF(100,100), True)
        polygon_comp = canvas.Document.Objects[canvas.Document.Objects.Count-1]
        offset_comp = canvas.Document.FindObject(Guid(offset_instance_id), True)
        
        offset_comp.Params.Input[0].AddSource(polygon_comp.Params.Output[0])
        gh.RunSolver(True)

In this example I tried to show how you can do that, obviously you need to know the Instance GUID of the target object; Here is a small C# components that helps you find this kind of information:
GUID
GUID.gh (3.2 KB)

Thank you very much @Mahdiyar. Your examples are very insightful. Much appreciated!