Thanks for everything Sam! You really helped me a lot. How did you find these information regarding these functions? Is there a documentation somewhere?
In any case here is my complete code for future reference
//...Do stuff to create module object... // ... $moduleinfo = add_moduleinfo($newlabel, $section); //lets get all sections and modules of the course $coursemodinfo = get_fast_modinfo($course->id, 0, false); //get all sections of the course $coursesections = $coursemodinfo->get_sections(); //get the first section, get_section will return an array of sections so I get position 0 to get section 1 $section01 = $coursesections[0]; //get the first module in the section so we can add on top of it $firstmodid = $section01[0]; //We need to get cm_info for the specific mod $mod = $coursemodinfo->get_cm($moduleinfo->coursemodule); //we also need section_info for the section we want to move to $sectioninfo = $coursemodinfo->get_section_info(0); //move the newly created module to section 01 but before $firstmodid moveto_module($mod, $sectioninfo, $firstmodid);