DAmn Viper/Packet Parser

From Botdom Wiki
Jump to: navigation, search

Packet Parsers are an important component in dAmn clients, as they greatly simplify the process of handling incoming data from dAmn's server. dAmn Viper's packet parser is a class which parses a given packet inside its __init__ method. The object, once instantiated, is used to represent the packet as a data type.

Source

The source code for the packet parser is released under GNU GPL v3, and is free for anyone to use. You can see the code below. <python> class Packet:

   """ Use this class to parse dAmn packets.
       Data is stored in the attributes cmd, param,
       args, body and raw.
   """
   def __init__(self, data=None, sep='='):
       self.cmd, self.param, self.args, self.body, self.raw = None, None, {}, None, data
       if not bool(data): return
       if data.find('\n\n') != -1:
           self.body = data[data.find('\n\n')+2:]
           data = data[:data.find('\n\n')]
       breaks = data.split('\n')
       if not bool(breaks): return
       if len(breaks) >= 1 and not sep in breaks[0]:
           head = breaks.pop(0).split(' ')
           self.cmd = head[0] or None
           self.param = None if len(head) < 2 else head[1]
       for line in breaks:
           if line.find(sep) == -1: continue
           self.args[line[:line.find(sep)]] = line[line.find(sep)+len(sep):]
       # And that's the end of that chapter.

</python>

Usage

Using this packet parser is quite simple. Appropriate usage is demonstrated below. <python>

  1. Let's parse a simple recv_msg packet.

pkt = Packet('recv chat:Botdom\n\nmsg main\nfrom=photofroggy\n\nHello, world!') print(pkt.cmd) # "recv" print(pkt.param) # "chat:Botdom" print(pkt.body) # "msg main\nfrom=photofroggy\n\nHello, world!"

  1. Note that this parser does not parse sub-packets. You have to do this manually, as shown below.

subpkt = Packet(pkt.body) print(subpkt.cmd) # "msg" print(subpkt.param) # "main" print(subpkt.args['from']) # "photofroggy" print(subpkt.body) # "Hello, world!" </python>