Bot
***

class psynet.bot.Bot(*args, **kwargs)

   Bases: "Participant"

   Simulated participant stored in the participant table, used for
   automated tests and simulations.

   Creating a bot waits for the experiment launch to finish, calls
   "initialize_bot()", and advances the bot to the first page. Hooks
   such as "test_check_bot()" receive "Bot" objects. To drive a bot
   through pages over HTTP, use "BotDriver".

   assignment_id

      A String, the assignment id of the participant.

   base_pay

      The amount the participant was paid for finishing the
      experiment.

   bonus

      the amount the participant was paid as a bonus.

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   end_time

      The time at which the participant finished.

   entry_information

      column containing structured data from the recruiter

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   fingerprint_hash

      A String, the fingerprint hash of the participant.

   hit_id

      A String, the id of the hit the participant is working on

   id

      a unique number for every entry. 1, 2, 3 and so on...

   mode

      live, sandbox or debug.

      Type:
         A String, the mode in which Dallinger is running

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   recruiter_id

      A String, the nickname of the recruiter used by this
      participant.

   status

      String representing the current status of the participant, can
      be:

      * "abandoned" - they ran out of time

      * "approved" - their work has been approved and they have been
        paid

      * "bad_data" - the participant finished, but their data was
        malformed

      * "did_not_attend" - the participant finished, but failed the
        attention check

      * "missing_notification" - this indicates that Dallinger has
        inferred that a Mechanical Turk notification corresponding to
        this participant failed to arrive. This is an uncommon, but
        potentially serious issue.

      * "overrecruited" - number of recruited participants exceed
        number required for the experiment, so this participant will
        not be used

      * "recruiter_submission_started" - participant has submitted
        their assignment to their recruiter, but the recruiter is
        still processing it

      * "rejected" - their work has been rejected

      * "replaced" - they have been replaced by another participant

      * "returned" - they returned the hit before finishing

      * "screened_out" - they were screened out (Prolific only)

      * "submitted" - participant's assignment submission processing
        has been completed by their recruiter

      * "working" - participant is working

   time_of_death

      the time at which failing occurred

   timed_out_since_barrier

      whether the latest timed page answered outside waiting logic and
      outside a trial's feedback since the last barrier ended on its
      time limit. The next barrier copies it onto the visit
      ("ParticipantLinkBarrier.ran_out_of_time") and clears it. To
      find answers given when a time limit ran out, read
      "psynet.trial.main.Trial.time_limit_reached" or
      "psynet.timeline.Response.time_limit_reached" instead.

      Type:
         Internal

   type

      a String giving the name of the class. Defaults to
      "participant". This allows subclassing.

   unique_id

      A String, a concatenation of "worker_id" and "assignment_id"

   vars

   worker_id

      A String, the worker id of the participant.

class psynet.bot.BotDriver(id_=None)

   Bases: "ParticipantDriver"

   Driver class for automating bot participants in an experiment.

   The "BotDriver" class is a convenience subclass of
   "ParticipantDriver" specifically focused on creating and
   controlling bot participants.

   If no "id_" is specified, a new "Bot" instance is created
   automatically. Otherwise, behaves like "ParticipantDriver".

   This class is primarily used for automated testing, simulation
   studies, and experiments where human participants interact with
   virtual (bot) participants. Like its parent, it interacts with the
   experiment server via HTTP requests, ensuring that the simulation
   closely matches real participant behavior.

   Parameters:
      **id** (*int**, **optional*) -- The ID of the participant to
      automate (i.e. corresponding to the "id" column in the
      Participant table). If not provided, a new bot participant is
      created.

class psynet.bot.BotResponse(*, raw_answer=NoArgumentProvided, answer=NoArgumentProvided, metadata=NoArgumentProvided, blobs=NoArgumentProvided)

   Bases: "object"

   Defines a bot's response to a given page.

   Parameters:
      * **raw_answer** -- The raw_answer returned from the page.
        Whole-number floats in it, such as "3.0", are submitted as
        "int", as the browser submits them.

      * **answer** -- The version of the answer that will be stored in
        the database, having been passed through .format_answer.

      * **metadata** -- A dictionary of metadata.

      * **blobs** -- A dictionary of blobs returned from the front-
        end.

psynet.bot.advance_past_wait_pages(bots, max_iterations=None, timeout=NoArgumentProvided, stop_at=())

   Repeatedly take wait pages and timeline holds for a group of bots
   until none are waiting.

   Useful in synchronous bot tests, where bots must pass barriers or
   wait pages together. After the first two passes over "bots", it
   polls every half second, as a browser would, so it also works when
   barriers release on a clock or a deadline, as in round-based games.

   Parameters:
      * **bots** (*list** of **BotDriver*) -- Bots to advance.

      * **max_iterations** (*int**, **optional*) -- Deprecated; use
        "timeout". If given, also stop after this many passes.

      * **timeout** (*float**, **optional*) -- Seconds to keep trying
        before giving up. "None" means no limit. Default: 10, or no
        limit if only "max_iterations" is given.

      * **stop_at** (*str** or **sequence** of **str*) -- ID or IDs of
        barriers to leave bots waiting at, for example a responder
        waiting for the proposer's offer while the test plays the
        proposer. Only matches bots on the waiting indicator of a
        barrier, grouper or regrouper with that ID that has no
        "waiting_logic", and only while that barrier hasn't released
        them: bots it has released, for example a turn-taking game's
        waiters once the writer submits, still catch up. Bots on a
        "WaitPage" or on "waiting_logic" pages are always advanced.

   Raises:
      **RuntimeError** -- If some bots are still waiting after
      "timeout" seconds (or     "max_iterations" passes).

psynet.bot.bots_by_sync_group(bots, group_type)

   Return the bots grouped by their current group of "group_type".

   Groupers and regroupers can group bots in any order, so a test can
   use this to find who plays with whom. Bots not in a group of that
   type are left out.

   Parameters:
      * **bots** (*list** of **BotDriver*) -- Bots to sort into
        groups.

      * **group_type** (*str*) -- The group type, as in
        "participant.in_sync_group(group_type)".

   Returns:
      One list per group, ordered by group ID, each ordered by bot ID.

   Return type:
      list of list of BotDriver

   -[ Examples ]-

      for first, second in bots_by_sync_group(bots, "pair"):
          first.take_page(response="circle")
          second.take_page(response="square")

psynet.bot.make_late_now(bots, barrier_id, timeout=10.0)

   Make the members who haven't reached a "GroupBarrier" late now,
   then advance the bots past it.

   A bot test would otherwise wait out the barrier's "late_after" in
   real time to test a player who goes quiet. For each group of a bot
   waiting at the barrier, this moves the group's clocks back: the
   time it last passed a barrier, and its members' times of joining
   and page deadlines. They move back by "late_after", or further if a
   quiet member's timed page and the grace for its answer would
   otherwise keep them from being late. The barrier's next check, when
   the waiting bots poll it, then removes every member who isn't
   waiting there, with its "late_action". Bots not waiting there, such
   as the quiet ones, aren't advanced: a quiet bot sees that its group
   went on without it, and the test takes its page next.

   Parameters:
      * **bots** (*list** of **BotDriver*) -- Bots to advance; include
        the ones waiting at the barrier. Quiet bots may be included
        and stay on their page.

      * **barrier_id** (*str*) -- The barrier's ID.

      * **timeout** (*float**, **optional*) -- Passed to
        "advance_past_wait_pages()".

   Raises:
      **ValueError** -- If none of the bots is waiting at the barrier,
      or it has no     "late_after".

   -[ Examples ]-

      bots[0].take_page(response=4)
      bots[1].take_page(response=8)
      make_late_now(bots, "round_finished")  # bots[2] goes quiet.

psynet.bot.regroup_now(bots, regrouper, timeout=10.0)

   Split the bots' pools at a "Regrouper" now, then advance them past
   it.

   A bot test would otherwise wait out the regrouper's "deadline" or
   its next "every" tick, for example to test a round that starts
   without a member who is still reading their results. This moves two
   clocks back by one "deadline" (or "every" period): the bots'
   arrival times at the regrouper and the creation times of the groups
   their pools' earlier splits formed. The next check then splits the
   pools as the deadline or tick would. Group memberships and roles
   are untouched, so a player still in last round's group keeps their
   role. "max_wait_time" doesn't move: it counts from the bots' real
   arrivals. A player waiting alone for cohort members who are still
   playing isn't released: that needs a second deadline (or tick), so
   a single call leaves them waiting.

   Parameters:
      * **bots** (*list** of **BotDriver*) -- Bots waiting at the
        regrouper, and any others to advance with them. Only these
        bots' arrivals move back, so with "every" pass every bot
        waiting in the pool.

      * **regrouper** (*Regrouper*) -- The regrouper from the
        timeline.

      * **timeout** (*float**, **optional*) -- Passed to
        "advance_past_wait_pages()".

   Raises:
      **ValueError** -- If the regrouper has neither "deadline" nor
      "every", or none of     the bots is waiting at it.

   -[ Examples ]-

      for bot in bots[:3]:
          bot.take_page()  # The fourth player is still reading.
      regroup_now(bots[:3], pairing)

psynet.bot.run_bots_to_completion(bots, timeout=60.0)

   Take pages for bots in turn until all of them have finished the
   experiment.

   Use this instead of calling "run_to_completion" on each bot when
   the bots still wait for each other, for example players a
   "Regrouper" keeps pairing: one bot run to completion on its own
   would wait at the next barrier for partners who never move. Each
   pass takes one page for every bot that is still working, answering
   with the page's bot response; a bot waiting at a barrier polls it,
   as a browser would.

   Parameters:
      * **bots** (*list** of **BotDriver*) -- Bots to run.

      * **timeout** (*float**, **optional*) -- Seconds to keep going
        before giving up (default 60). "None" means no limit.

   Raises:
      **RuntimeError** -- If some bots are still working after
      "timeout" seconds.

class psynet.participant.ParticipantDriver(id_)

   Driver class for automating participant actions in an experiment.

   The "ParticipantDriver" class contrasts with the "Participant"
   class. "Participant" instances correspond to rows in the
   Participant table in the database. These "Participant" instances
   are used in the primary experiment logic. The "ParticipantDriver"
   class is meanwhile used to simulate how a human actually interacts
   with the user interface. This simulation is primarily useful for
   automated testing, but it is also used for simulation studies as
   well as for studies where human participants interact with virtual
   participants.

   From an implementation perspective, the primary reason why we have
   this driver class in addition to the "Participant" class is to
   avoid having long-lived database object proxies. Such long-lived
   proxies can cause hard-to-debug issues such as database deadlocks.
   Where possible, the class uses HTTP requests to interact with the
   experiment server rather than directly interacting with the
   database; this helps us to ensure that the simulation is as close
   as possible to the real thing.

   In most cases, we anticipate users will want to use the convenience
   subclass "BotDriver", which is a subclass of "ParticipantDriver"
   that is specifically focused on creating and controlling bot
   participants. However, the "ParticipantDriver" class can be used in
   the rare case where we want to occasionally control individual
   actions of a human participant.

   Parameters:
      **id** (*int**, **optional*) -- The ID of the participant to
      automate (i.e. corresponding to the "id" column in the
      Participant table). If not provided, a new bot participant is
      created.

   stop_event

      If set while the driver is taking pages, the next page raises
      "DriverStopped". Load tests use this to end bots that run in
      threads.

      Type:
         threading.Event or None

   allow_failure()

      Tell the default "test_check_bot()" that this bot may fail.

      Use it for bots that the test makes fail on purpose, such as the
      partner of a bot that drops out.

   property current_notice: str | None

      The notice that the participant's progress bar shows now, if
      any.

      For example "Your partner is no longer in your group. Please
      continue." after their group dissolved, or a partner-ready
      notice.

   property current_page_label

      Label of the current page, or "None" once the participant has
      left.

   property current_page_text

      Text of the current page, or "None" once the participant has
      left.

   property current_page_time_estimate

      Time estimate of the current page, or "None" once the
      participant has left.

   drop_out()

      Leave the experiment as if returning the study on the
      recruitment platform.

      The participant is failed with the "premature_exit" tag, and
      their group reacts as it would to a real dropout. The default
      "test_check_bot()" accepts bots that dropped out. To simulate a
      participant who closes the tab without telling the platform,
      stop taking pages for that bot instead, and let the barriers'
      timeouts deal with them.

      Barriers where their group waits are checked before this
      returns, so members waiting there for them have been released.
      On a server, the periodic barrier check releases them a few
      seconds later.

   fail(reason=None, *, redirect_to_end=True)

      Fail the participant, as after a failed check.

      Barriers where their group waits are checked before this
      returns, so members waiting there for them have been released.

   property failed: bool

      Whether the participant has failed, read from the database.

   property http_session

      Return this participant's own "requests.Session", as a browser
      tab would keep.

      Reusing connections keeps bots cheap under load; opening a new
      HTTPS connection for every request can make the bots, not the
      server, the bottleneck of a performance test.

   property is_waiting

      Whether the current page is a waiting page, such as one at a
      barrier.

      Like the other "current_page_*" properties, this reads the
      status as of the last "take_page()" or "refresh_status()".

   refresh_status()

      Reload the cached page and response files from the experiment
      server.

   run_out_of_time()

      Let the time limit of the bot's current page run out without
      answering.

      Waits until the page's "time_limit" has passed, then submits as
      the browser does at that moment, so the page saves its
      "time_limit_answer" and "time_limit_reached" is "True". The bot
      is still on time for a barrier's "late_after".

      Returns:
         "True" if the participant should continue, "False" if
         finished.

      Return type:
         bool

   run_to_completion(render_pages=True, time_factor=0.0)

      Take pages until the participant has finished the experiment.

   run_until(condition, render_pages=True, time_factor=0.0)

      Take pages until a condition is met.

   send_chat_message(content)

      Post "content" to the "ChatRoom" on the bot's current page.

      The message goes through the same handler as one typed on the
      page, so the bot first joins the room.

   take_experiment(render_pages=True, time_factor=0.0)

      Run the participant through the entire experiment.

   take_page(render_pages=True, time_factor=0.0, response=NoArgumentProvided)

      Advance the participant by one page. Returns False if finished.

      Parameters:
         * **render_pages** (*bool**, **optional*) -- Whether to
           render pages during automation (default is True).

         * **time_factor** (*float**, **optional*) -- Factor to
           multiply the simulated page time by (default is 0.0).

         * **response** (*optional*) -- If provided, submitted as the
           page's final answer instead of the page's bot response,
           without passing through "format_answer".

      Returns:
         True if the participant should continue, False if finished.

      Return type:
         bool

   with_participant(function)

      Return "function(participant)", called with the bot's database
      row.

      Useful for questions that take a participant, for example:

         reason = bot.with_participant(
             lambda p: p.sync_group_removal_reason("pair")
         )
         pair_id = bot.with_participant(lambda p: p.active_sync_groups["pair"].id)

      Return plain values rather than database objects, which expire
      when the call ends.
