Skip to content

Preserve data between sessions

nemunaire edited this page Sep 8, 2014 · 3 revisions

In many case, you have to save data. Of course, you can use all Python methods, but nemubot integrates a powerfull class which will help you to do this part easily.

Load and save datas

Automatically, data are loaded with the module, and saved when the module is closed.

In your code, you can force backup by calling the function save.

Access and save data

In your module, you can access module data through the DATAS global variable.

This variable is a tree and it works like a DOM object. We will see later how make an index to increase access speed.

We will continue to use the Hello World module build in the previous part. Try the following code:

nemubotversion = 3.4

from xmlparser import ModuleState

@hook("msg_default")
def parselisten(msg):
  for usr in DATAS.getChilds():
    if usr["name"] == msg.sender:
      #The user is already in the list, don't speak to it
      return None

  #Create a new user and save it into DATAS
  user = ModuleState("user")
  user["name"] = msg.sender #Set the name attribute
  DATAS.addChild(user) #Save the new user into DATAS

  #Send the message to this new user
  return Response(msg.sender, "Hello world!")

Note the import statement. You can test: load the module, speak, then restart the program or reset the prompt and load the module again, speak. You shouldn't receive message from nemubot.

Simplify this code?

You can see in the previous code example, we do a for loop whereas before, we just done a single if; to retrieve this behavior, we will need to create an index.

Generally, it is defined during the module loading (when you add or delete an item from the node, the index is automatically updated).

nemubotversion = 3.4

from xmlparser import ModuleState

def load():
  #Create an index on name attribute, only on tag named user
  DATAS.setIndex("name", "user")

def parselisten(msg):
  if msg.sender not in DATAS.index:
    #Create a new user and save it into DATAS
    user = ModuleState("user")
    user["name"] = msg.sender
    DATAS.addChild(user)

    #Force the save, in case of bug :p
    save()

    #Send the message to this new user
    return Response(msg.sender, "Hello world!")
  else:
    return None

It is possible to build one single index per node.

You can redefined it later by calling the same method setIndex with the new parameters.