Skip to content
This repository was archived by the owner on Oct 25, 2022. It is now read-only.

Using Players

Haz Æ 41 edited this page Nov 21, 2020 · 2 revisions

With a Server object, you can use server.players to get the Players object

Retrieving a player

To get a connected player you can use

  • names (Map<string, Player>) to retrieve by name
  • uuids (Map<string, Player>) to retrieve by uuid
  • or get(PlayerInfo) to retrieve either by name or uuid
const player = server.players.names.get("Steve")
const player = server.players.uuids.get("f9f4f96d-cc0d-426d-a869-2c429e453bff")
const pinfo: PlayerInfo = {
  name: "Steve",
  uuid: "f9f4f96d-cc0d-426d-a869-2c429e453bff"
}

const player = server.players.get(pinfo)

Events

You can use join and quit events

For example

export class MyPlugin {
  constructor(
    readonly server: Server
  ) {
    server.players.on(["join"],
      this.onjoin.bind(this))

    server.players.on(["quit"], 
      this.onquit.bind(this))
  }
}
  • "join" emits a JoinEvent, which looks like this
interface JoinEvent {
  event: "player.join"
  player: Player
  location: Location
  message: string
} 
  • "quit" emits a QuitEvent, which looks like this
interface QuitEvent {
  event: "player.quit"
  player: Player
  location: Location
  message: string
} 

So you can use those events like this

class MyPlugin {
  // ...

  private async onjoin({ player }: JoinEvent){
    console.log(player.name, "joined the game")
  }

  private async onquit({ player }: QuitEvent){
    console.log(player.name, "left the game")
  }
}

Don't forget to cleanup the listeners when the server disconnects

export class MyPlugin {
  constructor(
    readonly server: Server
  ) {
    const offjoin = server.players.on(["join"],
      this.onjoin.bind(this))

    const offquit = server.players.on(["quit"], 
      this.onquit.bind(this))

    server.once(["close"], offjoin, offquit)
  }
}
Clone this wiki locally