asterobot:timers has a single export, sleep(). Scripts have no setTimeout() or setInterval(), so pauses, delays and repeated tasks are all built with it.
import { sleep } from "asterobot:timers";
sleep()
sleep(milliseconds) returns Promise<void>.
| Parameter | Type | Description |
|---|---|---|
milliseconds |
number | How long to wait. 0 and fractions such as 2.5 are accepted. |
The promise resolves once the time has passed and the script gets to it: when other events are waiting to be handled, it resolves after them. While a script awaits sleep(), its message handlers keep running.
The promise rejects with:
| Error | Cause |
|---|---|
timeout/milliseconds must be a finite positive Number |
milliseconds is negative, NaN or Infinity, or isn't a number at all. A BigInt such as 1000n and a string such as "1000" are refused too. |
timeout/milliseconds is too large |
milliseconds is too big to be a duration, more than about 292 years |
behavior resource limit exceeded: maximum timers reached |
128 calls to sleep() are already pending. See Limits. |
When the script stops while a sleep() is pending, its promise rejects with the reason the script stopped, such as behavior runtime closed after Stop.
Repeating a task
Start the loop without awaiting it, so the entry function can finish. A start only counts as successful once that function has returned, which matters for launch.reason.
import { session, botInfo, botWarn } from "asterobot:bot";
import { send } from "asterobot:protocol";
import { sleep } from "asterobot:timers";
async function everyMinute() {
while (true) {
await sleep(60000);
botInfo("Still running");
}
}
export default async function behavior(launch) {
// Not awaited, and caught: a rejection nobody catches stops the script.
everyMinute().catch((error) => botWarn("Timer loop stopped:", String(error)));
// A new game connection starts with this message. MITM bots never launch
// with "initial": the Dofus client has already identified their session.
if (launch.reason === "initial") {
await send("IdentificationRequest", {
ticketKey: session.gameToken,
languageCode: session.language,
});
}
}
When you click Stop, the pending sleep() rejects, so the console shows Timer loop stopped: behavior runtime closed as the script ends.
Don't poll in a tight loop to wait for a message: await wait(selector, { timeout }) from asterobot:protocol resolves as soon as the message arrives. And never keep the script busy without an await: code that runs for more than 250 ms in one go stops the script. Async and timing explains why.
Aucun avis à afficher.