Randomized keyframe move script

Hello,
I am currently working on looping various ambient particle systems and thought that this would be much easier to do with a script.
Briefly about my manual approach.
I call the function to select random objects.
with: bpy.ops.object.select_random(seed=1). So far no problem.
Then from all the selected objects I want to shift all the keyframes by a random value.
(x = random.choice(range(0, 180))
However, this already doesn’t seem to work.

After that I want to select all keframes from behind minus the shifted random value and move them to the beginning of the animation so that the loop is complete again.
I baked all the keyframes in advance so there are no interpolation errors.

If I just copy the executed commands from the info panel I also get lots of errors. Maybe because the mouse cursor for some actions is in the wrong window?

Does anyone have any tips on how I can implement such a script?


import bpy
import random

bpy.ops.object.select_random(seed=1)
x = random.choice(range(0, 180))
print("The Random Number is: ", x)
bpy.ops.action.select_all(action='SELECT')

bpy.ops.transform.transform(mode='TIME_TRANSLATE', value=(x, 0, 0, 0), orient_axis='Z', orient_type='VIEW', orient_matrix=((-1, -0, -0), (-0, -1, -0), (-0, -0, -1)), orient_matrix_type='VIEW', mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)

bpy.ops.action.select_all(action='DESELECT')
bpy.context.scene.frame_current = 200 - x
bpy.ops.action.select_leftright(mode='RIGHT', extend=False)

I figured it out.


import bpy
import random

for i in range(100):
    bpy.ops.object.select_all(action='DESELECT')
    y = random.choice(range(0, 80))
    bpy.ops.object.select_random(seed=y)
    x = random.choice(range(25, 175))
    bpy.context.area.ui_type = 'TIMELINE'
    bpy.ops.action.select_all(action='SELECT')
    bpy.ops.transform.transform(mode='TIME_TRANSLATE', value=(x, 0, 0, 0), orient_axis='Z', orient_type='VIEW', orient_matrix=((-1, -0, -0), (-0, -1, -0), (-0, -0, -1)), orient_matrix_type='VIEW', mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)
    bpy.ops.action.select_all(action='DESELECT')
    bpy.context.scene.frame_current = 201
    bpy.context.area.type = 'DOPESHEET_EDITOR'
    bpy.ops.action.select_leftright(mode='RIGHT', extend=False)
    bpy.context.area.ui_type = 'TIMELINE'
    bpy.ops.transform.transform(mode='TIME_TRANSLATE', value=(-200, 0, 0, 0), orient_axis='Z', orient_type='VIEW', orient_matrix=((-1, -0, -0), (-0, -1, -0), (-0, -0, -1)), orient_matrix_type='VIEW', mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)
    bpy.context.area.type = 'TEXT_EDITOR'