> For the complete documentation index, see [llms.txt](https://waypoint-scripts.gitbook.io/waypoint-scripts/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://waypoint-scripts.gitbook.io/waypoint-scripts/scripts/waypoint-ai-ems/code-snippets.md).

# Code Snippets

## QBCore: qb-ambulancejob custom checkin event

If you are using `qb-ambulancejob`, their event`qb-ambulancejob:checkin` does a distance check [in their check-in event](https://github.com/qbcore-framework/qb-ambulancejob/blob/2aa9a9ac482788cc2fc358ca7d9251eda3bdbc7b/client/main.lua#L832C9-L832C29) that will prevent the player from checking in when dropped off outside by the AI EMS because they are too far from the checkin location.

The simplest way to fix this is to add a new checkin event that we will call from wp-ai-ems.&#x20;

Here is an example of what a new event could look like that works with qb-ambulancejob.

```lua
-- This will check the player into the hospital that they spawn near
-- The hospitalIndex provided by wp-ai-ems must match the index for the hospital locations defined in this script
RegisterNetEvent('qb-ambulancejob:aiems-checkin', function(hospitalIndex)
    QBCore.Functions.Progressbar("hospital_checkin", Lang:t('progress.checking_in'), 2000, false, true, {
        disableMovement = true,
        disableCarMovement = true,
        disableMouse = false,
        disableCombat = true,
    }, {}, {}, {}, function() -- Done
        -- Gets a bed that is not occupied at this hospital to place the player in
        local bedId = getClosestAvailableBed(hospitalIndex)

        if bedId then
            TriggerServerEvent("hospital:server:SendToBed", bedId, true, hospitalIndex)
            hospitalLocation = hospitalIndex
            -- HospitalOutfit() -- Optional if you have this defined
        else
            QBCore.Functions.Notify(Lang:t('error.beds_taken'), "error")
        end
    end)
end)
```

## PS-MDT: Dispatch AI EMS on downed person alerts from the MDT

{% hint style="info" %}
The following snippets are for ps-mdt v1, but can easily be adapted to work with ps-mdt v2.
{% endhint %}

<figure><img src="/files/EF7VihPSsxLlV68bx6ZL" alt=""><figcaption></figcaption></figure>

1. At the bottom of `client/main.lua` add:

```lua
-- Custom Waypoint Events
RegisterNUICallback("dispatchLocalEMS", function(data, cb)
    local targetSourceId = data.playerSource
    TriggerServerEvent('ps-mdt:server:dispatchLocalEMS', targetSourceId)
    cb(true)
end)
```

2. At the bottom of `server/main.lua` add:

```lua
-- Custom Waypoint Events

-- Handles dispatching AI EMS to a target downed player
RegisterNetEvent("ps-mdt:server:dispatchLocalEMS", function(targetSourceId)
    local src = source
    local targetPlayer = QBCore.Functions.GetPlayer(targetSourceId)
    local isTargetPlayerDead = targetPlayer.PlayerData.metadata["isdead"] or targetPlayer.PlayerData.metadata["inlaststand"]

    if isTargetPlayerDead then
        local isInstantDispatch = true
        TriggerEvent('wp-ai-ems:server:DispatchAIEMS', targetSourceId, isInstantDispatch)
        TriggerClientEvent('QBCore:Notify', src, 'Local EMS dispatched')
    else
        TriggerClientEvent('QBCore:Notify', src, 'Patient no longer needs EMS', 'error')
    end
end)
```

3. In `ui/app.js` we need to make several changes to add the "Dispatch Local EMS" context menu item

   1. Look for  `$(".contextmenu").on("click", ".attached-units", function () {...}` and under that code block add:

      ```javascript
      // Waypoint custom code for dispathcing AI EMS
      $(".contextmenu").on("click", ".dispatch-local-ems", function () {
        const playerSource = $(this).data("playersource");
        $.post(
          `https://${GetParentResourceName()}/dispatchLocalEMS`,
          JSON.stringify({
            playerSource: playerSource,
          })
        );
      });
      ```

   2. Look for `const canRespond = $(this).data("canrespond");` and add these lines beneath:

      ```javascript
      const playersource = $(this).data("playersource");
      const dispatchcodename = $(this).data("dispatchcodename");
      ```

   3. Look for `if (canRespond == true) {...} elseif (canRespond == false) { ... }` , after the if/else we want to add another conditional to make it only render this new item if its for civdown dispatchcodename

      ```javascript
      if (dispatchcodename == "civdown") {
          args = [
            ...args,
            {
              className: "dispatch-local-ems",
              icon: "fa-solid fa-ambulance",
              text: "Dispatch Local EMS",
              info: callId,
              playersource,
              status: "",
            },
            {
              className: "notify-ems-enroute",
              icon: "fa-solid fa-medkit",
              text: "Notify EMS enroute",
              info: callId,
              playersource,
              status: "",
            },
          ];
        }
      ```

   4. We now need to add data attributes onto the items so we can pluck off the `playersource` and `dispatchcodenames`. Look for `DispatchItem =` there should be 4 results. Add the following attributes onto each of them:

      ```javascript
      data-playersource=${value.source} data-dispatchcodename=${value.dispatchcodename}
      ```

   5. Look for `<li class="contextmenu-item ${value.className}" data-info="${value.info}" data-status="${value.status}` and update to include the new attribute, you should now have: `<li class="contextmenu-item ${value.className}" data-info="${value.info}" data-status="${value.status}" data-playersource="${value.playersource}">`
4. In `ui/style.css` add these lines:

   ```css
   dispatch-local-ems:hover {
       background-color: rgb(156, 156, 156);
   }

   .notify-ems-enroute:hover {
       background-color: rgb(156, 156, 156);
   }

   .respond-call:hover {
       background-color: rgb(156, 156, 156);
   }
   ```

## Wasabi Ambulance Integration

If you use wasabi\_ambulance and want to dispatch AI EMS as part of the distress signal, follow these snippets.&#x20;

1. In `cl_customize.lua` find the `SendDistressSignal` function and add this `TriggerServerEvent('hospital:server:RequestEMS')`.

   <pre class="language-lua" data-overflow="wrap"><code class="lang-lua">SendDistressSignal = function() -- Edit distress signal to implement custom dispatch
   	TriggerEvent('wasabi_bridge:notify', Strings.distress_sent_title, Strings.distress_sent_desc, 'success')
   	TriggerServerEvent('hospital:server:RequestEMS')
   	local ped = cache.ped
   	...

   </code></pre>
2. In `sv_customize.lua` add the following new event.

   ```lua
   -- If there are no active EMS online, dispatch AI EMS
   RegisterNetEvent('hospital:server:RequestEMS', function()
       local src = source
       local players = GetPlayers()
       local isActiveEMS = false
       for _, playerIdString in ipairs(players) do
           local playerId = tonumber(playerIdString)
           local player = wsb.getPlayer(playerId)
           if player and wsb.hasGroup(playerId, Config.ambulanceJobs) then
               if wsb.framework == 'qb' and player.PlayerData and player.PlayerData.job.onduty then
                   isActiveEMS = true
                   break
               else
                   isActiveEMS = true
                   break
               end
           end
       end

       if not isActiveEMS then
           -- Change this to true if you want to instantly dispatch EMS
           local isInstantDispatch = false
           TriggerClientEvent('wp-ai-ems:client:DispatchAIEMS', src, isInstantDispatch)
       end
   end)
   ```
3. Ensure that you have updated `Config.HospitalLocations` and `Config.DefaultHospital` to match the keys defined in `wasabi-ambulance config.lua - Config.Locations` .&#x20;

   > As of writing this (5/8/24), the key values should be updated to strings, where the string matches the hospital names you've configured.

   1. Example:

   ```lua
   Config.DefaultHospital = "Pillbox"
   Config.HospitalLocations = {
       ["hospital"] = {
           ["Pillbox"] = {
               ["name"] = "Pillbox",
               ...
   ```
4. Update `Config.HospitalCheckinEvent` to

   ```lua
   Config.HospitalCheckinEvent = "wasabi_ambulance:hospitalCheckIn"
   ```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://waypoint-scripts.gitbook.io/waypoint-scripts/scripts/waypoint-ai-ems/code-snippets.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
