Writing Python Scripts

Python scripts work, generally in a similar way to Groovy or other languages scripts, except one significant difference. You cannot call "return" from the script itself. Hence you cannot simply pass script results by calling "return" statement directly from the script.

To overcome the problem Tigase offers another way to pass script execution results. It checks the value of a special variables on the script completion: "result" and "packet". By assigning value to one of these variables the Python (or any other language) can pass execution results back to the Tigase server.

The simplest possible Python script may look like this one:

result = "Hello world!"

For instructions how to load and execute the script, please refer to ////<<introductoryArticle,////introductory article for scripting in the Tigase server. There were some minor changes in later the Tigase 4.4.0 and later version, so please have a look at the ////<<newElements,////article describing new elements as well.

A bit more advanced script asks the user for providing required parameters for the actual script execution:

from java.lang import *
from tigase.server import *

num1 = Command.getFieldValue(packet, "num1")
num2 = Command.getFieldValue(packet, "num2")

if num1 is None or num2 is None:
  res = Iq.commandResultForm(packet)
  Command.addTextField(res, "Note", "This is a Python script!")
  Command.addFieldValue(res, "num1", "")
  Command.addFieldValue(res, "num2", "")
  packet = res
  result = num1 + num2

Except this rather minor difference, the rest part of scripting in Python for the Tigase administrator commands is the same as for all other languages. As all languages can return execution results via these special variables, it could be argued there is no difference at all.

In next articles, I am going to present the Tigase server API available for scripting framework. My main language is Groovy as it offers the best integration with JVM and Tigase API, however I will try to include Python example code as well.

_I hope this article encourages you to try the scripting support in the Tigase server. If you have any suggestions or questions please do not hesitate to send me your comments. I have also created a new tigase scripts forum on the website. If you have an interesting script to share or want to discuss some aspects of this functionality do not hesitate to add your post.