Skip to content

Server Script Functions

NightfallAlicorn edited this page Oct 30, 2015 · 47 revisions

Scripting/Server/Functions

Script Functions

The script functions are properties of the sys object (with one or two exceptions) and they allow you to interface with the C++ code in a safe way.

Some are deprecated and should not be used in new code, those are listed here.

Engine

  • sys.enableStrict() Changes a bunch of things to throw errors instead of warnings and may cause deprecated functions to stop working.

Utility

  • timerID = sys.setTimer(call, time, repeats) Calls the code in call after time milliseconds. If repeats is true then this call repeats itself until unset. Gives a timerID that can be used to unset the timer.
  • sys.unsetTimer(timerID) Cancels a timer function
  • sys.unsetAllTimers() Cancels all timers. Good for dealing with buggy scripts sometimes.
  • sys.sha1(toHash) returns the sha1 hash of the string
  • sys.md4(toHash) returns the md4 hash of the string (not recommended)
  • sys.md5(toHash) returns the md5 hash of the string
  • sys.changeScript(newScript, triggerStartUp) changes the script with the content. Can be used with webCall or getFileContent to do cool stuff. If optional triggerStartUp is true serverStartUp event will be triggered after loading a new script.
  • sys.eval(script) Runs the script given in parameter. Returns the result.
  • sys.stopEvent() if called before an event occurs, if possible, stop the events from happening. If called in an event that starts by "before", stops the event from happenning. For example, if called in beforeChatMessage, the message of the player won't display. If called in beforeLogIn, the player won't be allowed to log in. If called in beforeChallengeIssued, the challenge won't be issued.
  • sys.os() Server OS name
  • sys.system(command) Tell the underlying OS to run the command line. WARNING: Please know what the **** you're doing before you use this. You can break your computer.
  • sys.get_output(command, callback, errback)
  • sys.list_processes()
  • sys.kill_processes()
  • sys.serverVersion() Returns the server's version number (for example 2.1.0)

File I/O

  • sys.exists(filename) Returns if the file exists.
  • sys.read(filename) // also sys.getFileContent Returns the content of the file.
  • sys.write(filename, content) // also sys.writeToFile Clear the content of the file and write that.
  • sys.append(filename, content) // also sys.appendToFile Append content to the content of the file.
  • sys.rm(filename) // also sys.deleteFile Delete the file
  • sys.writeObject(filename, object, cpr) Writes object to filename after serializing and compressing at compression level cpr. cpr can be omitted.
  • sys.readObject(filename) Reads an object from filename
  • sys.getVal(file, key) Returns the variable stored in the file with that key.
  • sys.saveVal(file, key, value) saves a variable to a file so it'll still be there after a server restart.
  • sys.removeVal(key, file) deletes the variable in the file.
  • sys.getValKeys(file) Returns an array of keys stored (without values) of the file.
  • sys.exec(filename) Executes a file as javascript. This has advantages in that it properly handles backtraces, whereas evaluating code read from a file does not.
  • sys.import(filename)
  • sys.zip(file, dir) Puts all the files (not any directories though...) from directory dir into a zipfile named file.
  • sys.extractZip(file, dir) Extracts zip file file. dir is an optional parameter to extract into a specific directory.
  • sys.makeDir(name) Makes a directory with name name
  • sys.removeDir(name) Deletes empty directory name
  • sys.getCurrentDir() Returns the absolute path for the directory the client is saved in
  • sys.filesForDirectory(dir) Return an array of files that are located in dir

Network I/O

  • sys.synchronousWebCall(url) calls the web url given, waits for the reply, and returns the reply.
  • sys.synchronousWebCall(url, args) calls the web url given with the args as POST arguments, waits for the reply, and returns the reply.
  • sys.webCall(url, script) calls the web url given, and when the reply is received runs the script given in parameter. At that moment the variable "resp" will contain the response of the web server.
  • sys.webCall(url, script, args) calls the web url given with the args as POST arguments, and otherwise behaves the same way as the previous function.
  • sys.hostName(player_ip, name) Works like webCall. This functions returns the hostName of the player.

Messages

  • sys.broadcast(message, channel, sender, html, target)
  • sys.clearChat() Clears server's message window.
  • sys.changeAnnouncement(html) Changes announcement in the config and updates it for all players.
  • sys.getAnnouncement() Gets the announcement in the config.
  • print(variable1, variable2, ...) Displays the content of the variables in the server's mainchat.
  • sys.sendAll(message, channelId) sends a message to the mainchat. If optional channelId is not present, will send a message to all channels.
  • sys.sendHtmlAll(message, channelId) sends a message to the mainchat. It will be displayed in html. If optional channelId is not present, will send a message to all channels.
  • sys.sendHtmlMessage(playerId, message, channelId) sends a message only to the mainchat of that player. It will be displayed in html. If optional channelId is not present, will send a message to the user on all his channels.
  • sys.sendMessage(playerId, message, channelId) sends a message only to the mainchat of that player. If optional channelId is not present, will send a message to the user on all his channels.
  • sys.setAnnouncement(html, playerId) changes announcement. If optional playerId is not specified all players will see updated announcement.

Players

  • sys.os(player) Player's OS name
  • sys.avatar(player_id) returns player's avatar id. Will return null if player is not logged it.
  • sys.auth(player_id) returns the authority level of that player.
  • sys.away(player_id) returns a bool if the player is idle or not. It returns undefined if the player isn't logged on.
  • sys.ban(player_name) bans someone in DB. Use kick() manually if needed.
  • sys.battling(player_id) returns true or false depending on if the player is battling.
  • sys.changeAvatar(playerId, avatarId) will set player's avatar to avatarId.
  • sys.changeAuth(player_id, new_auth) changes the auth of the player to the new auth. Player must be online.
  • sys.changeAway(player_id, bool) changes the idle status of the player. bool being true idles, while false unidles.
  • sys.changeDbAuth(player_name, new_auth) changes the auth of the player in the DB to the new auth. If a player is online effective auth will not change until s/he logs off or changeAuth() called.
  • sys.changeInfo(player_id, new_info) temporary changes player's challenge window info to new_info (HTML).
  • sys.changeName(player_id, new_name) Temporarily changes player's name to new_name. New player is not created. No uniqueness check is performed. Server window will not be updated. Use at your own risk.
  • sys.changeRating(name, tier, new_rating) Changes the rating of a player in that tier.
  • sys.changeTier(player_id, team, tier) Changes a user's tier.
  • sys.clearPass(name) Removes the password associated to that name.
  • sys.hasLegalTeamForTier(player_id, team, tier) returns true or false depending on if the player has a team valid for this tier.
  • sys.hasTier(player_id, tier) returns true if that player has any team placed in tier
  • sys.id(player_name) returns the id of the player with that name.
  • sys.info(player_id) returns someone's trainer info (in HTML)
  • sys.ip(player_id) returns the IP of that player
  • sys.kick(player_id) kicks that player.
  • sys.ladderEnabled(player_id) returns true or false depending on if that player has ladder enabled.
  • sys.ladderRating(player_id, tier) returns the ladder rating of that player. If tier is not specified current one will be used.
  • sys.loggedIn(player_id) returns true or false depending on if the player is logged in or not.
  • sys.name(player_id) returns the name of the player with that id.
  • sys.ranking(player_id) returns the ranking of that player in his tier.
  • sys.ranking(name, tier) returns the ranking of that player for that tier.
  • sys.ratedBattles(player_id) number of rated battles player did.
  • sys.ratedBattles(name, tier) number of rated battles player did in a given tier.
  • sys.tempBan(name, duration) Bans someone for duration. duration is given in minutes.
  • sys.tier(player_id, team) returns the tier of that player.
  • sys.unban(player_name) unbans a name.
  • sys.updatePlayer(player_id) updated changed player data for all player in server (after changing Pokémon with script for example, so the correct team is shown in the challenge window). This is not needed for changeInfo as is does that automatically.

Player Information

  • sys.connections(ip) Number of active connections from this IP.
  • sys.numRegistered(ip) Number of registered accounts on this IP.
  • sys.ability(num) returns ability name by its id.
  • sys.abilityNum(abilityName) returns ability id by its name.
  • sys.aliases(ip) returns an array of users for that IP.
  • sys.banList() returns an array of banned user names.
  • sys.dbAll() Returns a list of all players in the database.
  • sys.dbAuth(name) returns the authority from the member in the database with that name.
  • sys.dbAuths() returns an array of names of people whose auth is superior to 0.
  • sys.dbIp(name) returns the ip from the member in the database with that name.
  • sys.dbLastOn(name) returns the last date of appearance of that person as shown in the Control Panel.
  • sys.dbExpire(name) Returns the amount of days left for the account with the specified name to expire.
  • sys.dbRegistered(name) returns if the name is registered with a password or not.
  • sys.dbExpire(name) Returns the amount of days until a player expires in the database.
  • sys.dbExpiration() Returns the amount of days that the account will stay if it's inactive.
  • sys.dbDelete(name) deletes a player
  • sys.dbTempBanTime(name) how long a player is banned for
  • sys.getColor(id) gets a user's hex code for color.
  • sys.getTierList() returns an array of tiers.
  • sys.maxAuth(ip) returns the maximum authority associated to that IP.
  • sys.numPlayers() returns the number of players online.
  • sys.playerIds() return an array containing the ids of all the players online. You can use this function in your sendall scripts, masskick, etc.
  • sys.totalPlayersByTier(tier) returns the total number of players that are ranked in that tier.

Game Information

  • sys.gen(pokenum) gives the Pokémon's generation.
  • sys.hiddenPowerType(gen, hpdv, attdv, defdv, spddv, sattdv, sdefdv) returns type id for given DVs.
  • sys.item(num) returns the name of the item.
  • sys.itemNum(name) returns the number of the item.
  • sys.move(num) returns the name of the move.
  • sys.moveNum(name) returns the num of the move.
  • sys.nature(num) returns the corresponding nature.
  • sys.natureNum(name) returns the number corresponding to that nature.
  • sys.pokeAbility(poke_id, slot, gen) returns id of an ability that Pokémon can have. slot is either 0, 1, or 2 (which ability to return). gen is optional and last gen is used when omitted. Will return undefined if Pokémon is unknown or slot is out of range.
  • sys.pokeBaseStats(pokeNum) Return an array of baseStats for pokeNum
  • sys.pokemon(num) returns the name of the Pokémon.
  • sys.pokeNum(name) returns the number of the Pokémon.
  • sys.pokeType1(pokeId, gen) returns Pokémon's primary type id. If optional gen is not specified last supported Generation will be used.
  • sys.pokeType2(pokeId, gen) returns Pokémon's secondary type id. If optional gen is not specified last supported Generation will be used. Returns 17 (i.e. type() from it would be "???") if there is none.
  • sys.type(id) returns Pokémon type's display name by id.
  • sys.typeNum(typeName) returns Pokémon type's id by name.
  • sys.weather(weatherId) returns weather name by id.
  • sys.weatherNum(weatherName) returns weather id by name. weatherName can be "hailstorm", "rain", "sandstorm", "sunny", and "normal".

Team

  • sys.changePokeAbility(player_id, team, slot, ability_num) Changes ability of a Pokémon in selected slot.
  • sys.changePokeGender(player_id, team, slot, gender) Changes gender of a Pokémon in selected slot. gender must be either 0 (neutral), 1 (male), or 2 (female).
  • sys.changePokeHappiness(player_id, team, slot, new_value) new_value must be in [0..255] range.
  • sys.changePokeItem(player_id, team, pokeSlot, itemnum) Changes the item of the Pokémon in that slot.
  • sys.changePokeLevel(player_id, team, pokeSlot, pokeLevel) Changes the level of the Pokémon in that slot.
  • sys.changePokeMove(player_id, team, pokeSlot, moveSlot, movenum) Changes the move of that Pokémon in that moveslot (move slots range from 0 to 3).
  • sys.changePokeName(player_id, team, slot, name) Changes name of a Pokémon in selected slot.
  • sys.changePokeNature(player_id, team, slot, nature) Changes the nature of a Pokémon in selected slot.
  • sys.changePokeNum(player_id, team, pokeSlot, pokeNum) Changes the Pokémon in that slot (eg 150 = Mewtwo), slots range from 0 to 5.
  • sys.changePokeShine(player_id, team, slot, new_value) new_value is either true or false.
  • sys.changePokeHp(playerId, team, slot, hp) Changes hp stat of pokemon in slot, on team of playerId to hp
  • sys.changePokeStatus(playerId, team, slot, status) Changes status of pokemon in slot, on team of playerId to status
  • sys.changePokePP(playerId, team, slow, moveslot, pp) Changes PP of move in moveslot of pokemon in slot, on team of playerId to pp
  • sys.compatibleAsDreamWorldEvent(player_id, team, slot) Checks if the Pokémon is a valid male DW Pokémon (no breeding moves).
  • sys.hasDreamWorldAbility(player_id, team, index) Returns true if a Pokémon in the team is using a DW ability. Returns false otherwise.
  • sys.hasTeamItem(player_id, team, itemnum) Returns true or false depending if one Pokémon in the team has that item.
  • sys.hasTeamMove(player_id, team, movenum) Returns true if the team has a Pokémon with that move or false otherwise.
  • sys.hasTeamPoke(player_id, team, pokenum) Returns true or false depending if that player has that Pokémon in his team.
  • sys.hasTeamPokeMove(player_id, team, pokeslot, movenum) Returns true or false depending if that Pokémon has the move or not.
  • sys.indexOfTeamPoke(player_id, team, pokenum) Returns the slot of the Pokémon in the team or undefined if the Pokémon is not found.
  • sys.indexOfTeamPokeMove(player_id, team, pokeslot, movenum) Returns the slot of the move in the moveset of that Pokémon in the team or undefined if the move is not found.
  • sys.changeTeamPokeDV(player_id, team, slot, stat, newValue) stat's DV for the selected Pokémon will be set to newValue.
  • sys.changeTeamPokeEV(player_id, team, slot, stat, newValue) stat's EV for the selected Pokémon will be set to newValue.
  • sys.teamPoke(player_id, team, slot) Returns Pokémon in the team of that player at that slot (slots start from 0).
  • sys.teamPokeAbility(player_id, team, slot) Returns Pokémon's ability id in a specified team slot.
  • sys.teamPokeDV(player_id, slot, team, stat) Returns DV (IV) of Pokémon in a specified slot for specified stat.
  • sys.teamPokeGender(player_id, team, slot) Returns gender of a Pokémon in a specified slot.
  • sys.teamPokeEV(player_id, team, slot, stat) Returns EV of Pokémon in a specified slot for specified stat.
  • sys.teamPokeItem(player_id, team, pokeslot) Returns the item of that Pokémon (slots start from 0).
  • sys.teamPokeLevel(player_id, team, pokeslot) Returns the level of the Pokémon in that slot.
  • sys.teamPokeMove(player_id, team, pokeslot, moveslot) Returns the move of the Pokémon of the team of that player (slots start from 0).
  • sys.teamPokeNature(player_id, team, pokeslot) Returns the nature of the Pokémon in that slot.
  • sys.teamPokeNick(player_id, team, pokeslot) Returns Pokémon's nickname.
  • sys.teamPokeStat(playerId, team, slot, stat) Return value of stat of pokemon in slot on team of playerId
  • sys.teamPokeHP(playerId, team, slot) Return HP of pokemon in slot on team of playerId
  • sys.teamPokeStatus(playerId, team, slot) Return status of pokemon in slot on team of playerId
  • sys.teamPokePP(playerId, team, slot, moveslot) Return PP of move in moveslot of pokemon in slot on team of playerId
  • sys.swapPokemons(playerId, team, slot1, slot2) Swaps the pokemon in slot1 for the pokemon in slot2 on team of playerId

Server management and configuration

These functions affect the server globally.

  • sys.resetLadder(tier) reset all players rankings in the selected tier and update them on the server.
  • sys.synchronizeTierWithSQL(tier) reloads all the ratings of the tier from the SQL database and updates all the ratings of the people of the tier on the server.
  • sys.exportMemberDatabase() saves all the members database to a file called members.txt, which would be imported on next restart if the SQL database were empty of players.
  • sys.exportTierDatabase() saves all the tiers database (ratings) to files called tier_NameOfTier.txt, which would be imported on next restart if the SQL database were empty for those tiers
  • sys.makeServerPublic(flag) makes server public if flag parameter is true. Private if false.
  • sys.memoryDump() prints a state of the memory, was used to evaluate the memory consumption.
  • sys.modifyBaseStat(poke_id, stat, value) will change Pokémon's base stat to specified value (0-255).
  • sys.modifyMovePower(moveNum, power, generation) will change move's power to given 'power' value (0-255). 1 will cause zero damage but still counts as attacking move (unlike 0). If optional 'generation' is not specified last supported Generation will be used.
  • sys.modifyMoveAccuracy(moveNum, accuracy, generation) will change move's accuracy to given 'accuracy' value. If optional 'generation' is not specified last supported Generation will be used.
  • sys.modifyMovePP(moveNum, pp, generation) will change move's PP to given 'pp' value. If optional 'generation' is not specified last supported Generation will be used.
  • sys.modifyMovePriority(moveNum, priority, generation) will change move's priority to given 'priority' value (from -128 to 127). If optional 'generation' is not specified last supported Generation will be used.
  • sys.modifyPokeAbility(poke_id, ability_slot, ability_id, gen) will change given Pokémon's ability globally. ability_slot is either 0, 1, or 2. gen is optional and equals to last supported gen by default. Team Builder info will not be changed however.
  • sys.modifyTypeChart(attacker_type_id, defender_type_id, modifier) will modify type chart for server. modifier must be one of the following strings"none", "ineffective", "normal", "effective".
  • sys.reloadTiers() Reloads tier data from the tiers.xml file
  • sys.shutDown() shuts down the server (after calling the serverShutDown() event).
  • sys.updateRatings() updates all ratings (has something to do with rating decay).
  • sys.isServerPrivate() If the server is private
  • sys.dosChannel() Returns the channel in which overactive messages are sent
  • sys.changeDosChannel (newchanname) Changes the channel in which overactive messages are sent
  • sys.reloadDosSettings() Reloads Anti-DOS settings from the config file
  • sys.loadServerPlugin(path) Loads the plugin and returns true on success.
  • sys.unloadServerPlugin(name) Unloads the plugin (by plugin name) and returns true on success
  • sys.listPlugins() List the server plugins loaded (by plugin names)
  • sys.removePlugin(int index) Removes the plugin (by index in the list of plugins, not by name)

SQL

  • sys.sql(command [, params]) Executes a sql command and returns the result. params is optional and used to add parameters to the command, that you want the sql engine to escape appropriately. If params is an array, all the '?' in command are replaced in order with the values of the array. If params is an object, all the :xxxXxxx in command are replaced by value with the key xxxXxxx. For example: sys.sql('INSERT INTO mytable(name, attribute) VALUES(:name, :attribute)', {'name': 'crystal', 'attribute':'cutie'}) or sys.sql('INSERT INTO mytable(name, attribute) VALUES(?, ?)', ['crystal', 'cutie']) are equivalent.

Helpers

  • sys.rand(min, max) returns a random number between min inclusive and max exclusive (like rand(0, 4) will return 0, 1, 2 or 3).
  • sys.time() returns the number of seconds elapsed since 1 Jan 1970.
  • Qt.lighter(color, factor)
  • Qt.darker(color, factor)
  • Qt.lightness(color)
  • Qt.tint(color)

Channels

It is advised to allow the user to have at least one channel open at all times. Naturally, the server won't allow a user to leave a channel if it's the last channel open, but it's possible with scripts. If a user has no channel open, he has a blank screen replacing main chat, players list, and battles list, and it's not very nice.

  • sys.channel(channelId) returns the name of that channel.
  • sys.channelId(channelName) return channel's id by name.
  • sys.channelIds() returns an array of channel ids.
  • sys.channelsOfPlayer(playerId) an array of channel ids a player is on.
  • sys.createChannel(channelName) creates an channel with that name. The channel won't be destroyed until one player logs on that channel and off when he's the only player online. Returns the id of the create channel.
  • sys.existChannel(channelName) returns true if a channel with that name exists.
  • sys.isInChannel(playerId, channelId) Will return true when that player is in that channel, false otherwise.
  • sys.isInSameChannel(player1, player2) Will return true when player1 and player2 are in the same channel, false otherwise.
  • sys.kick(playerId, channelId) Kicks a player out of the given channel. This will NOT remove the tab in the players client; it will let the tab open with the message "You are not in the channel anymore" displayed.
  • sys.playersOfChannel(channelId) an array of players for a channel.
  • sys.putInChannel(playerId, channelId) forces a player to join a channel. Will bypass the 7 channels limit. It should be noted that sys.putInChannel() will call the ChannelJoin events and will therefore not bypass restrictions defined in those events (for example blocking normal users from joining a staff channel even if you use this function).

Battle setup

Use these functions ONLY in battleSetup event and only with battle_id it'll pass to you. Otherwise things will break.

  • sys.inflictStatus(battle_id, to_first_player, slot, status_id) will apply status condition to first player if to_first_player is true. To second one otherwise. Available statusesparalyze (1), sleep (2), poison (5), freeze (3), burn (4), fine (0) and KO (31).
  • sys.prepareWeather(battle_id, weather_id) makes it so a specified weather is already in place when battle starts. This weather will not end by itself but still can be changed with weather changing moves.

Battles

  • sys.forceBattle(player_id_1, player_id_2, clauses, mode, is_rated) will force battle between 2 players. clauses is an integer between 1 and 511 (look at the server events page under the section "Battles" for more information). mode is 0 for Singles, 1 for Doubles and 2 for Triples. ìs_rated is either true or false whether the battle is rated (for ladder) or not.
  • sys.battlingIds() Returns an array of active battle IDs
  • sys.prepareItems(battleId, playerslot, items) Gives items to players before a battle starts (Be careful with this as players on < 2.0.07 clients will crash when given items). battleId is the battle you want to give the items to, playerslot is which player you want to give them to and items is a list of items you want to give (e.g. {"124":3} gives 3 sacred ash) Item ids are available in db/items/items.txt or using the sys.itemNum function.
  • sys.setTeamToBattleTeam(playerId, team, battleId) Sets the team of playerId of the team they had at the end of battleId. Only works when used in beforeBattleEnded. For example if at the end of the battle he had 5 pokemon koed, then at the next battle he'll only have one pokemon not koed

Technical

  • sys.clearDosData() Removes all overactive past data stored in the server
  • currentMod() Current pokemon mod loaded
  • currentModPath() Path to folder of the current pokemon mod loaded
  • dataRepo() Path to folder where all the server files are stored (typically './', but may be different when installed from a debian package)