SPADS plugin development (Python): Difference between revisions

From Spring
Jump to navigationJump to search
Bibim (talk | contribs)
Bibim (talk | contribs)
Replaced content with "This page is now hosted on GitHub: [https://github.com/Yaribz/SPADS/wiki/SPADS-plugin-development-(Python) SPADS plugin development (Python)]"
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
= Introduction =
This page is now hosted on GitHub: [https://github.com/Yaribz/SPADS/wiki/SPADS-plugin-development-(Python) SPADS plugin development (Python)]
 
SPADS is an autohost system coded in Perl, it supports both Perl and Python plugins. This tutorial deals with Python plugin development only (for Perl plugin development another tutorial is available [https://springrts.com/wiki/SPADS_plugin_development here]).
 
SPADS plugins are object-oriented modules. It is strongly recommended to already know Python basics before starting Python plugin development (a Python tutorial is available [https://docs.python.org/3/tutorial/ here]).
 
<br>
= Technical prerequisites =
 
Python (the Python interpreter and its libraries) must be installed on the system (versions 2.6+ or 3.2+ recommended). The type of installation (32-bit / 64-bit) must be consistent with the Perl version and the Spring engine used for SPADS.
 
Additionally, in order to allow communication between Perl code (SPADS core) and Python code (SPADS plugins), SPADS uses a Perl module named <code>Inline::Python</code> which must also be installed on the system. It is recommended to install the latest version for SPADS, refer to [https://springrts.com/wiki/SPADS_Inline::Python_installation_guide this guide] for installation.
 
<br>
 
= Simple plugin tutorial (HelloWorld) =
 
In this section we are going to write our first SPADS plugin. So let's start simple with a good old "Hello world". The plugin will answer "Hello World" to anyone saying "Hello" in a private message to SPADS.
 
== Choosing our template ==
 
Some plugin templates are available to help you bootstrap your plugin development. The commented versions of these templates are available [http://planetspads.free.fr/spads/plugins/templates/commented/ here], while the raw versions (without comment) are available [http://planetspads.free.fr/spads/plugins/templates/raw/ here] (the <code>.pm</code> files must be ignored for this tutorial, these are the Perl versions of the templates).
 
Our first plugin will be very basic, so we will use the simplest template: <code>mysimpleplugin.py</code>. Let's download [http://planetspads.free.fr/spads/plugins/templates/commented/mysimpleplugin.py the commented version of this template] and open it with our favorite editor. As you can see, the code is heavily commented (actually every single line of code is explained), so I won't go into further details here. Now that you've read and understood the commented template, let's actually start plugin development.
 
== Adapting the template ==
 
First we must name our plugin. Let's call it <code>HelloWorld</code>. We have to rename the downloaded template from <code>mysimpleplugin.py</code> to <code>helloworld.py</code>, and edit it to replace <code>MySimplePlugin</code> by <code>HelloWorld</code> in the source code.
 
== Checking SPADS plugin system ==
 
Before going into actually writing new code, let's just check that the plugin works in SPADS (if not done yet, you have to configure the [http://planetspads.free.fr/spads/doc/spadsDoc_All.html#global:pluginsDir SPADS plugins directory] in your <code>spads.conf</code> configuration file and reload SPADS configuration).
 
We have to move our new plugin (<code>helloworld.py</code>) in the SPADS plugins directory so that SPADS can find it. Then, as a privileged SPADS user, we can type following command (in a private message to SPADS for example): <code>!plugin HelloWorld load</code>. SPADS should answer <code>Loaded plugin HelloWorld.</code>, which indicates the plugin has been loaded successfully.
 
If all is ok, we can let this SPADS instance running like this, we will get back to it later.
 
== Writing plugin code ==
 
Writing plugin code mainly consists in implementing plugin callbacks and calling plugin API functions, as specified in [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html SPADS plugin API documentation].
 
So we want our plugin to react to some private messages sent to SPADS. To do so we have to implement a plugin callback function which is called by SPADS core each time a lobby private message is received: this is the [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#onPrivateMsg-self-userName-message onPrivateMsg] event-based callback.
 
We also want our plugin to send a private message, to do so we can call the plugin API function [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#sayPrivate-user-message sayPrivate].
 
Now that we have identified the API functions that we need, we can actually implement our plugin. Here is a commented implementation example of the <code>onPrivateMsg</code> callback, which will answer <code>Hello World</code> to anyone saying <code>Hello</code> in a private message to SPADS:
<syntaxhighlight lang="python">
    # This is the callback called each time SPADS receives a private message
    #  self is the plugin object (first parameter of all plugin callbacks)
    #  userName is the name of the user sending the private message
    #  message is the message sent by the user
    def onPrivateMsg(self,userName,message):
   
        # Here we "fix" strings received from Perl in case
        # the Inline::Python module transmits them as byte strings
        (userName,message)=spads.fix_string(userName,message)
 
        # We check the message sent by the user is "Hello"
        if message == 'Hello':
           
            # We send our wonderful Hello World message
            spads.sayPrivate(userName,'Hello World')
       
        # We return 0 because we don't want to filter out private messages
        # for other SPADS processing
        return 0</syntaxhighlight>
 
All we have to do now is adding this callback declaration in our <code>helloworld.py</code> file located in SPADS plugins directory. We obtain [http://planetspads.free.fr/spads/plugins/tutorials/helloworld.py this fully functional HelloWorld plugin].
 
== Testing our plugin ==
 
Let's test this plugin in SPADS. First, since we modified the plugin source code, we have to tell SPADS to reload the plugin as follows: <code>!plugin HelloWorld reload</code>. SPADS should answer <code>Reloaded plugin HelloWorld.</code>, which indicates the plugin has been reloaded successfully.
 
Finally, just say <code>Hello</code> to SPADS in a private message. Congratulations for your first SPADS plugin! ;)
 
<br>
= Configurable plugin tutorial (ForbiddenWords) =
 
In this section we are going to write our first configurable SPADS plugin (a configurable plugin has its own configuration file, named after the plugin name but with <code>.conf</code> extension). This plugin will monitor all messages said by players in the battle lobby, and will kick players who use swear words.
 
== Specifying our configuration parameters ==
 
The first step of writing a configurable plugin is to choose how we will configure it. In our example, we will use 2 configuration parameters: <code>words</code> will contain the list of forbidden words, and <code>immuneLevel</code> will contain the minimum autohost access level to be immune regarding these forbidden words checks.
 
We choose to make <code>words</code> a global setting (unmodifiable, not impacted by preset change), and <code>immuneLevel</code> a preset setting (modifiable, can be impacted by preset change). The <code>words</code> global setting will have no restriction (can be empty, can contain any character...), whereas the <code>immuneLevel</code> preset setting will only be allowed to be an integer or integer range.
 
== Preparing the template ==
 
Once we have a clear view of our configuration settings, we can start adapting the template for our needs. Since we are making a configurable plugin, this time we will download [http://planetspads.free.fr/spads/plugins/templates/commented/myconfigurableplugin.py the configurable plugin template] and its associated [http://planetspads.free.fr/spads/plugins/templates/commented/MyConfigurablePlugin.conf configuration file example].
 
First, let's take a look at the configuration file example. This is a just a basic configuration file containing one global setting example and one preset setting example. Let's modify this file to match the configuration we chose as follows (don't forget to rename the file from <code>MyConfigurablePlugin.conf</code> to <code>ForbiddenWords.conf</code> also):
{|style="margin-top: 10px; margin-left: 40px; background-color: #38474E; border: 1px solid black; border-color: #20292E" |
|
# This is our global setting (can't be changed without reloading the configuration)
words:ass;asshole;bastard;bitch;cunt;fuck;motherfucker;shit;whore
 
# We must define our preset setting in the default preset at least
[default]
 
# This is our preset setting, which can be changed with "!plugin ... set ..."
# or by loading a preset.
# "100" is the default value, and any integer between 0 and 140 is allowed
immuneLevel:100|0-140
|}
Then we must prepare the plugin template itself, by renaming it from <code>myconfigurableplugin.py</code> to <code>forbiddenwords.py</code> and editing it to replace <code>MyConfigurablePlugin</code> by <code>ForbiddenWords</code> in the source code. We must also adapt the template so that it uses the configuration settings we chose. This is done by modifying the <code>globalPluginParams</code> and <code>presetPluginParam</code> declarations as follows:
<syntaxhighlight lang="python">
# We define one global setting "words" and one preset setting "immuneLevel".
# "words" has no type associated (no restriction on allowed values)
# "immuneLevel" must be an integer or an integer range
# (check %paramTypes hash in SpadsConf.pm for a complete list of allowed
# setting types)
globalPluginParams = { 'words': [] }
presetPluginParams = { 'immuneLevel': ['integer','integerRange'] }
</syntaxhighlight>
 
== Writing plugin code ==
 
We want our plugin to react to messages said in the battle lobby. There is no dedicated callback for this event in [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html SPADS plugin API documentation], so we have to set up our own handler on the [http://springrts.com/dl/LobbyProtocol/ProtocolDescription.html#SAIDBATTLE:server SAIDBATTLE lobby command]. To do so we have to call the plugin API function [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#addLobbyCommandHandler-handlers-priority-caller addLobbyCommandHandler]. We will call this function at the end of our plugin constructor as follows, so that it will be set up directly when the plugin is loaded:
<syntaxhighlight lang="python">
        [...]
   
        # We set up a lobby command handler on SAIDBATTLE
        spads.addLobbyCommandHandler({'SAIDBATTLE': hLobbySaidBattle})
</syntaxhighlight>
However, if SPADS is disconnected from the lobby due to network problems for example, all lobby handlers are automatically removed. So we must re-add them each time we connect to lobby server. This can be done using the [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#onLobbyConnected-self-lobbyInterface onLobbyConnected] event-based callback as follows:
<syntaxhighlight lang="python">
    # This callback is called each time we (re)connect to the lobby server
    def onLobbyConnected(self,lobbyInterface):
       
        # When we are disconnected from the lobby server, all lobby command
        # handlers are automatically removed, so we (re)set up our command
        # handler here.
        spads.addLobbyCommandHandler({'SAIDBATTLE': hLobbySaidBattle})
</syntaxhighlight>
Also, it is a good practice to remove any handler we have added when the plugin is unloaded. To do so we must implement the [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#onUnload-self-context onUnload] event-based callback as follows:
<syntaxhighlight lang="python">
    # This callback is called when the plugin is unloaded
    def onUnload(self,reason):
       
        # We remove our lobby command handler when the plugin is unloaded
        spads.removeLobbyCommandHandler(['SAIDBATTLE'])
</syntaxhighlight>
Finally, we have to implement our <code>SAIDBATTLE</code> handler <code>hLobbySaidBattle</code>. In this handler we need to perform following operations:
* skip processing if the user is the autohost itself: we need to access SPADS configuration to compare the user name with the [http://planetspads.free.fr/spads/doc/spadsDoc_All.html#global:lobbyLogin lobbyLogin] setting value. So we will need the plugin API function [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#getSpadsConf getSpadsConf].
* perform processing according to our configuration (<code>words</code> and <code>immuneLevel</code> settings): we need to access our plugin configuration, so we will need the plugin API function [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#getPluginConf-pluginName-caller getPluginConf].
* retrieve the autohost access level of the user: we will use the plugin API function [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#getUserAccessLevel-user getUserAccessLevel]
* send a message to the battle lobby when we kick someone: we will use the plugin API function [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#sayBattle-message sayBattle].
* send a [http://springrts.com/dl/LobbyProtocol/ProtocolDescription.html#KICKFROMBATTLE:client KICKFROMBATTLE] lobby command to kick a user: we will use the plugin API function [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#queueLobbyCommand-lobbyCommand queueLobbyCommand].
 
Here is a commented implementation example of this <code>hLobbySaidBattle</code> handler, which will kick any non-privileged user saying a forbidden word in the battle lobby:
<syntaxhighlight lang="python">
# This is the handler we set up on SAIDBATTLE lobby command.
# It is called each time a player says something in the battle lobby.
#  command is the lobby command name (SAIDBATTLE)
#  user is the name of the user who said something in the battle lobby
#  message is the message said in the battle lobby
def hLobbySaidBattle(command,user,message):
   
    # First we "fix" strings received from Perl in case
    # the Inline::Python module transmits them as byte strings
    (user,message)=spads.fix_string(user,message)
   
    # Here we check it's not a message from SPADS (so we don't kick ourself)
    spadsConf = spads.getSpadsConf()
    if user == spadsConf['lobbyLogin']:
        return
   
    # Then we check the user isn't a privileged user
    # (autohost access level >= immuneLevel)
    pluginConf = spads.getPluginConf()
    if int(spads.getUserAccessLevel(user)) >= int(pluginConf['immuneLevel']):
        return
   
    # We put the forbidden words in a list
    forbiddenWords = pluginConf['words'].split(';')
           
    # We test each forbidden word
    for forbiddenWord in forbiddenWords:
       
        # If the message contains the forbidden word (case insensitive)
        if re.search(r'\b' + re.escape(forbiddenWord) + r'\b',message,re.IGNORECASE):
           
            # Then we kick the user from the battle lobby
            spads.sayBattle("Kicking %s from battle (watch your language!)" % user)
            spads.queueLobbyCommand(["KICKFROMBATTLE",user])
                   
            # We quit the foreach loop (no need to test other forbidden word)
            break
</syntaxhighlight>
 
As we are using regular expressions in our plugin code, we must not forget to import the <code>re</code> Python module at the start of our plugin:
<syntaxhighlight lang="python">
# Import the regular expression module to check for forbidden words
import re
</syntaxhighlight>
Once we put all that together, we obtain [http://planetspads.free.fr/spads/plugins/tutorials/forbiddenwords.py this fully functional ForbiddenWords] plugin and [http://planetspads.free.fr/spads/plugins/tutorials/ForbiddenWords.conf its associated configuration file].
 
== Testing our plugin ==
 
To test our plugin, we have to put the plugin module in [http://planetspads.free.fr/spads/doc/spadsDoc_All.html#global:pluginsDir SPADS plugins directory], and the associated configuration file in [http://planetspads.free.fr/spads/doc/spadsDoc_All.html#global:etcDir SPADS etc directory].
 
Then we load the plugin as follows: <code>!plugin ForbiddenWords load</code>. And finally, as an unprivileged user we can try to say some forbidden words in the battle lobby and we should get kicked by the plugin.
 
<br>
 
<span style="color:#ff0000">'''/!\ WORK IN PROGRESS /!\'''</span>
 
= New-command plugin tutorial (TimePlugin) =
 
In this section we are going to write a plugin which implements a new command for SPADS. Such plugins are configurable plugins like the one we wrote just before, with 2 additional files to configure the new commands. This plugin will give current time when someone types <code>!time</code>.
 
== Preparing the template ==
 
This time we need to download 4 files to prepare our plugin: [http://planetspads.free.fr/spads/plugins/templates/commented/mynewcommandplugin.py the new-command plugin template], [http://planetspads.free.fr/spads/plugins/templates/commented/MyNewCommandPlugin.conf the associated configuration file example], [http://planetspads.free.fr/spads/plugins/templates/commented/MyNewCommandPluginHelp.dat the help file example] and [http://planetspads.free.fr/spads/plugins/templates/commented/MyNewCommandPluginCmd.conf the commands rights configuration file example].
 
As usual, we rename these files to match our plugin name: <code>MyNewCommandPlugin</code> --> <code>TimePlugin</code>. Then we edit the plugin template <code>timeplugin.py</code> and replace <code>MyNewCommandPlugin</code> by <code>TimePlugin</code> in the source code, and we do the same for the plugin configuration template <code>TimePlugin.conf</code>, so that the <code>commandsFile</code> and <code>helpFile</code> settings are consistent with the files we just renamed.
 
Then we can edit our command rights requirements configuration file: <code>TimePluginCmd.conf</code>. This file uses the same syntax as the standard SPADS <code>commands.conf</code> file. The template provides a default command <code>myCommand</code> with no requirement. We will just rename this command to <code>time</code>:
{|style="margin-top: 10px; margin-left: 40px; background-color: #38474E; border: 1px solid black; border-color: #20292E" |
|
# Anyone can call our command from anywhere
[time]
::|0:
|}
Now we need to write the help information for our new command. This is done in the file <code>TimePluginHelp.dat</code>. This file uses the same syntax as the standard SPADS <code>help.dat</code> file, and the template provides a help example for a command <code>myCommand</code> as a syntax reminder. After each command declaration, the first line is the command syntax description, and the other lines are optional usage examples. Let's replace this help example with our own help information for our basic <code>!time</code> command:
{|style="margin-top: 10px; margin-left: 40px; background-color: #38474E; border: 1px solid black; border-color: #20292E" |
|
[time]
<nowiki>!</nowiki>time - This command just prints current time
|}
 
== Writing plugin code ==
 
The new-command plugin template that we used to initialize our plugin already defines a new command named <code>myCommand</code>, so all we have to do is to edit our plugin file ( <code>timeplugin.py</code> ) and replace this command by our own <code>time</code> command:
 
First, let's modify the code which sets up the new SPADS command handler using the plugin API function [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#addSpadsCommandHandler-handlers-replace-0 addSpadsCommandHandler]. This call is located in the plugin constructor. We edit it so that it becomes:
<syntaxhighlight lang="python">
        [...]
        # We declare our new command and the associated handler
        spads.addSpadsCommandHandler({'time': hSpadsTime})
        [...]
</syntaxhighlight>
We must modify the same way the code which removes this SPADS handler using the plugin API function [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#removeSpadsCommandHandler-commands removeSpadsCommandHandler] in the [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#onUnload-self-context onUnload] event-based callback:
<syntaxhighlight lang="python">
        [...]
        # We remove our new command handler
        spads.removeSpadsCommandHandler(['time'])
        [...]
</syntaxhighlight>
Finally, we must replace the handler example <code>hMyCommand</code> by our own handler <code>hSpadsTime</code>. In order to answer to the user issuing the command, we can use the plugin API function [http://planetspads.free.fr/spads/doc/spadsPluginApiDoc.html#answer-message answer], which will send an answer message to the user in the same way he sent the command (private message, battle lobby...).
 
Here is an implementation example for this basic command:
<syntaxhighlight lang="python">
# This is the handler for our new command
def hSpadsTime(source,user,params,checkOnly):
   
    # time is a basic command, we have nothing to check in case of callvote
    return 1 if($checkOnly);
   
    my @time = localtime();
    @time = map(sprintf("%02d",$_),@time);
   
    answer("Current local time: $time[2]:$time[1]:$time[0]");
  }
</syntaxhighlight>
 
Once we put all that together, we obtain [http://planetspads.free.fr/spads/plugins/tutorials/timeplugin.py this fully functional TimePlugin] plugin, and its associated [http://planetspads.free.fr/spads/plugins/tutorials/TimePlugin.conf configuration file], [http://planetspads.free.fr/spads/plugins/tutorials/TimePluginCmd.conf command rights configuration file] and [http://planetspads.free.fr/spads/plugins/tutorials/TimePluginHelp.dat command help file].
 
== Testing our plugin ==
 
To test our plugin, we have to put the plugin module and the plugin help file in [http://planetspads.free.fr/spads/doc/spadsDoc_All.html#global:pluginsDir SPADS plugins directory], and the 2 configuration files in [http://planetspads.free.fr/spads/doc/spadsDoc_All.html#global:etcDir SPADS etc directory].
 
Then we load the plugin as follows: <code>!plugin TimePlugin load</code>. And finally, we can try to say !time in a private message to SPADS or in the battle lobby, and SPADS should answer giving current local time. Our <code>!time</code> command help should also appear in <code>!help</code> and <code>!help time</code> outputs.
 
[[Category:SPADS]]

Latest revision as of 11:08, 15 July 2024

This page is now hosted on GitHub: SPADS plugin development (Python)