Exemplo n.º 1
0
    def __init__(self,
                 ip="127.0.0.1",
                 modules_paths=list(),
                 data_store=datastore.Abstract(),
                 debug=False):
        """Initialize the bot context

        Keyword arguments:
        ip -- The external IP of the bot (default: 127.0.0.1)
        modules_paths -- Paths to all directories where looking for modules
        data_store -- An instance of the nemubot datastore for bot's modules
        debug -- enable debug
        """

        super().__init__(name="Nemubot main")

        logger.info("Initiate nemubot v%s (running on Python %s.%s.%s)",
                    __version__, sys.version_info.major,
                    sys.version_info.minor, sys.version_info.micro)

        self.debug = debug
        self.stop = True

        # External IP for accessing this bot
        import ipaddress
        self.ip = ipaddress.ip_address(ip)

        # Context paths
        self.modules_paths = modules_paths
        self.datastore = data_store
        self.datastore.open()

        # Keep global context: servers and modules
        self._poll = select.poll()
        self.servers = dict()
        self.modules = dict()
        self.modules_configuration = dict()

        # Events
        self.events = list()
        self.event_timer = None

        # Own hooks
        from nemubot.treatment import MessageTreater
        self.treater = MessageTreater()

        import re

        def in_ping(msg):
            return msg.respond("pong")

        self.treater.hm.add_hook(
            nemubot.hooks.Message(
                in_ping,
                match=lambda msg: re.match(
                    "^ *(m[' ]?entends?[ -]+tu|h?ear me|do you copy|ping)", msg
                    .message, re.I)), "in", "DirectAsk")

        def in_echo(msg):
            from nemubot.message import Text
            return Text(msg.frm + ": " + " ".join(msg.args),
                        to=msg.to_response)

        self.treater.hm.add_hook(nemubot.hooks.Command(in_echo, "echo"), "in",
                                 "Command")

        def _help_msg(msg):
            """Parse and response to help messages"""
            from nemubot.module.more import Response
            res = Response(channel=msg.to_response)
            if len(msg.args) >= 1:
                if "nemubot.module." + msg.args[
                        0] in self.modules and self.modules[
                            "nemubot.module." + msg.args[0]]() is not None:
                    mname = "nemubot.module." + msg.args[0]
                    if hasattr(self.modules[mname](), "help_full"):
                        hlp = self.modules[mname]().help_full()
                        if isinstance(hlp, Response):
                            return hlp
                        else:
                            res.append_message(hlp)
                    else:
                        res.append_message(
                            [
                                str(h) for s, h in self.modules[mname]
                                ().__nemubot_context__.hooks
                            ],
                            title="Available commands for module " +
                            msg.args[0])
                elif msg.args[0][0] == "!":
                    from nemubot.message.command import Command
                    for h in self.treater._in_hooks(Command(msg.args[0][1:])):
                        if h.help_usage:
                            lp = [
                                "\x03\x02%s%s\x03\x02: %s" %
                                (msg.args[0],
                                 (" " + k if k is not None else ""),
                                 h.help_usage[k]) for k in h.help_usage
                            ]
                            jp = h.keywords.help()
                            return res.append_message(lp + ([
                                ". Moreover, you can provides some optional parameters: "
                            ] + jp if len(jp) else []),
                                                      title=
                                                      "Usage for command %s" %
                                                      msg.args[0])
                        elif h.help:
                            return res.append_message("Command %s: %s" %
                                                      (msg.args[0], h.help))
                        else:
                            return res.append_message(
                                "Sorry, there is currently no help for the command %s. Feel free to make a pull request at https://github.com/nemunaire/nemubot/compare"
                                % msg.args[0])
                    res.append_message("Sorry, there is no command %s" %
                                       msg.args[0])
                else:
                    res.append_message("Sorry, there is no module named %s" %
                                       msg.args[0])
            else:
                res.append_message(
                    "Pour me demander quelque chose, commencez "
                    "votre message par mon nom ; je réagis "
                    "également à certaine commandes commençant par"
                    " !.  Pour plus d'informations, envoyez le "
                    "message \"!more\".")
                res.append_message(
                    "Mon code source est libre, publié sous "
                    "licence AGPL (http://www.gnu.org/licenses/). "
                    "Vous pouvez le consulter, le dupliquer, "
                    "envoyer des rapports de bogues ou bien "
                    "contribuer au projet sur GitHub : "
                    "https://github.com/nemunaire/nemubot/")
                res.append_message(
                    title="Pour plus de détails sur un module, "
                    "envoyez \"!help nomdumodule\". Voici la liste"
                    " de tous les modules disponibles localement",
                    message=[
                        "\x03\x02%s\x03\x02 (%s)" %
                        (im, self.modules[im]().__doc__) for im in self.modules
                        if self.modules[im]() is not None and self.modules[im]
                        ().__doc__
                    ])
            return res

        self.treater.hm.add_hook(nemubot.hooks.Command(_help_msg, "help"),
                                 "in", "Command")

        from queue import Queue
        # Messages to be treated
        self.cnsr_queue = Queue()
        self.cnsr_thrd = list()
        self.cnsr_thrd_size = -1