When the robot is going to fall the motor starts and moves the robot to the direction it is going to fall, so the motor torque about the center of gravity that is higher than the motor makes the robot balanced.
Step 1: Things You Need
small electric motor
(or a motor with gearbox)
some sheets of plastic to make bearings and the robot neck
two battery holders
4 AA batteries
one button cell
one SPDT (single pole double throw) switch with a metal lever
one toggle switch for the on/off switchs
Step 2: Motor, Grears, Shaft, and Wheels
You can also use a motor and gearbox.
It does not matter how you make it.
Step 3: Attach Robot Neck and Head
Then put some glue on one side of battery holders and attach them to the top of the plastic sheet.
Step 4: Making the Sensor
Make the nail head hot on a flame and put it on the plastic sheet on the motor in a position that when the robot stands vertically the button cell touches the ground.
Then attach the switch to the robot with glue.
Step 5: Connecting the Switch
Then attach the other side of the switch to the motor.
Step 6: Wiring
Note that you must solder the wires in a way that robot moves to the direction that is going to fall.
Step 7: Testing
Put 4 batteries into the battery holders and turn on the switch.
Try to change the position of the sensor to make the robot works better.
If the robot works inverted swap the red and blue wires on the sensor or on the battery holders.