RetroPie is just a RaspiOS Lite image underneath, so a regular Linux/Debian installation.
You can add your code to the autostart.sh script that RetroPie uses to start EmulationStation (see here how to access the script) or just create your own service to start on boot (see here).