Exemplo n.º 1
0
    def do_generate(self, event):
        exclude_list = [
            "fn",
        ]
        matches = []

        message = event.data
        for name, l in self.bot.message_listeners.items():
            search_matches = l["regex"].search(message.content)
            if (
                    # The search regex matches and
                    search_matches

                    # It's not from me, or this search includes me, and
                    and (message.will_said_it is False or
                         ("include_me" in l and l["include_me"]))

                    # I'm mentioned, or this is an overheard, or we're in a 1-1
                    and
                (message.is_private_chat or
                 ("direct_mentions_only" not in l
                  or not l["direct_mentions_only"]) or message.is_direct)):
                context = Bunch()
                for k, v in l.items():
                    if k not in exclude_list:
                        context[k] = v
                context.search_matches = search_matches.groupdict()

                o = GeneratedOption(context=context,
                                    backend="regex",
                                    score=100)
                matches.append(o)

        return matches
Exemplo n.º 2
0
 def get_github_branches(self, only_deployable=False):
     repos = []
     for repo in self.get_github_repos():
         if not repo.fork:
             branches = []
             for b in repo.iter_branches():
                 deployable = False
                 deploy_config = None
                 if only_deployable:
                     deploy_config = repo.contents("deploy.yml", ref=b.commit.sha)
                     if deploy_config:
                         deploy_config = yaml.load(deploy_config.content.decode("base64"))
                         deployable = True
                 if not only_deployable or deployable:
                     branches.append(Bunch(
                         url="%s/tree/%s" % (repo.html_url, b.name),
                         repo_name=repo.name,
                         repo_obj=repo,
                         repo_clone_url=repo.ssh_url,
                         name=b.name,
                         branch_obj=b,
                         deployable=deployable,
                         deploy_config=deploy_config,  # Note this will only be set for deployable branches.
                     ))
             if len(branches) > 0:
                 repos.append(Bunch(
                     name=repo.name, 
                     branches=branches, 
                     url=repo.html_url,
                     clone_url=repo.clone_url,
                 ))
     return repos
Exemplo n.º 3
0
    def do_generate(self, event):
        exclude_list = [
            "fn",
        ]
        matches = []

        message = event.data

        # TODO: add token_sort_ratio
        if message.content:
            if not hasattr(self, "match_choices"):
                self.match_choices = []
                self.match_methods = {}
            for name, l in self.bot.message_listeners.items():
                if not l["regex_pattern"] in self.match_methods:
                    self.match_methods[l["regex_pattern"]] = l
                    self.match_choices.append(l["regex_pattern"])

            search_matches = fuzz_process.extract(message.content,
                                                  self.match_choices)

            for match_str, confidence in search_matches:
                logging.debug(" Potential (%s) - %s" % (confidence, match_str))
                l = self.match_methods[match_str]
                if (
                        # The search regex matches and
                        # regex_matches

                        # We're confident enough
                    (confidence >= settings.FUZZY_MINIMUM_MATCH_CONFIDENCE)

                        # It's not from me, or this search includes me, and
                        and (message.will_said_it is False or
                             ("include_me" in l and l["include_me"]))

                        # I'm mentioned, or this is an overheard, or we're in a 1-1
                        and
                    (message.is_private_chat or
                     ("direct_mentions_only" not in l
                      or not l["direct_mentions_only"]) or message.is_direct)):
                    logging.info(" Match (%s) - %s" % (confidence, match_str))
                    fuzzy_regex = self._generate_compiled_regex(l)

                    regex_matches = fuzzy_regex.search(message.content)
                    context = Bunch()
                    for k, v in l.items():
                        if k not in exclude_list:
                            context[k] = v
                    if regex_matches and hasattr(regex_matches, "groupdict"):
                        context.search_matches = regex_matches.groupdict()
                    else:
                        context.search_matches = {}

                    o = GeneratedOption(context=context,
                                        backend="regex",
                                        score=confidence)
                    matches.append(o)

        return matches
Exemplo n.º 4
0
    def __init__(self, *args, **kwargs):
        for f in self.REQUIRED_FIELDS:
            if not f in kwargs:
                raise Exception("Missing %s in Message construction." % f)

        for f in kwargs:
            self.__dict__[f] = kwargs[f]

        if "timestamp" in kwargs:
            self.timestamp = kwargs["timestamp"]
        else:
            self.timestamp = datetime.datetime.now()

        # Clean content.
        self.content = self._clean_message_content(self.content)

        h = hashlib.md5()
        h.update(self.timestamp.strftime("%s").encode("utf-8"))
        h.update(self.content.encode("utf-8"))
        self.hash = h.hexdigest()

        self.metadata = Bunch()
        if not "original_incoming_event_hash" in kwargs:
            if hasattr(self, "original_incoming_event") and hasattr(self.original_incoming_event, "hash"):
                self.original_incoming_event_hash = self.original_incoming_event.hash
            else:
                self.original_incoming_event_hash = self.hash
Exemplo n.º 5
0
    def bootstrap(self):
        # Bootstrap must provide a way to to have:
        # a) self.normalize_incoming_event fired, or incoming events put into self.incoming_queue
        # b) any necessary threads running for a)
        # c) self.me (Person) defined, with Will's info
        # d) self.people (dict of People) defined, with everyone in an organization/backend
        # e) self.channels (dict of Channels) defined, with all available channels/rooms.
        #    Note that Channel asks for members, a list of People.
        # f) A way for self.handle, self.me, self.people, and self.channels to be kept accurate,
        #    with a maximum lag of 60 seconds.
        self.people = {}
        self.channels = {}
        self.me = Person(
            id="will",
            handle="will",
            mention_handle="@will",
            source=Bunch(),
            name="William T. Botterton",
        )

        # Do this to get the first "you" prompt.
        self.pubsub.publish('message.incoming.stdin',
                            (Message(content="",
                                     type="message.incoming",
                                     is_direct=True,
                                     is_private_chat=True,
                                     is_group_chat=False,
                                     backend=self.internal_name,
                                     sender=self.partner,
                                     will_is_mentioned=False,
                                     will_said_it=False,
                                     backend_supports_acl=False,
                                     original_incoming_event={})))
Exemplo n.º 6
0
    def _send_to_backend(self, msg):
        stripped_msg = Bunch()
        # TODO: Find a faster way to do this - this is crazy.
        for k, v in msg.__dict__.items():
            try:
                pickle.dumps(v)
                stripped_msg[k] = v
            except:
                pass
        for k in msg.xml.keys():
            try:
                # print(k)
                # print(msg.xml.get(k))
                pickle.dumps(msg.xml.get(k))
                stripped_msg[k] = msg.xml.get(k)
            except:
                # print("failed to parse %s" % k)
                pass

        stripped_msg.xmpp_jid = msg.getMucroom()
        stripped_msg.body = msg["body"]
        self.xmpp_bridge_queue.put(stripped_msg)
Exemplo n.º 7
0
class ShellBackend(StdInOutIOBackend):
    friendly_name = "Interactive Shell"
    internal_name = "will.backends.io_adapters.shell"
    partner = Person(
        id="you",
        handle="shelluser",
        mention_handle="@shelluser",
        source=Bunch(),
        name="Friend",
    )

    def send_direct_message(self, message_body, **kwargs):
        print("Will: %s" % html_to_text(message_body))

    def send_room_message(self,
                          room_id,
                          message_body,
                          html=False,
                          color="green",
                          notify=False,
                          **kwargs):
        print("Will: %s" % html_to_text(message_body))

    def set_room_topic(self, topic):
        print("Will: Let's talk about %s" % (topic, ))

    def normalize_incoming_event(self, event):
        if event["type"] == "message.incoming.stdin":
            m = Message(content=event.data.content.strip(),
                        type=event.type,
                        is_direct=True,
                        is_private_chat=True,
                        is_group_chat=False,
                        backend=self.internal_name,
                        sender=self.partner,
                        will_is_mentioned=False,
                        will_said_it=False,
                        backend_supports_acl=False,
                        original_incoming_event=event)
            return m
        else:
            # An event type the shell has no idea how to handle.
            return None

    def handle_outgoing_event(self, event):
        # Print any replies.
        if event.type in ["say", "reply"]:
            self.send_direct_message(event.content)
        if event.type in [
                "topic_change",
        ]:
            self.set_room_topic(event.content)

        elif event.type == "message.no_response":
            if event.data and hasattr(
                    event.data, "original_incoming_event") and len(
                        event.data.original_incoming_event.data.content) > 0:
                self.send_direct_message(random.choice(UNSURE_REPLIES))

        # Regardless of whether or not we had something to say,
        # give the user a new prompt.
        sys.stdout.write("You:  ")
        sys.stdout.flush()

    def bootstrap(self):
        # Bootstrap must provide a way to to have:
        # a) self.normalize_incoming_event fired, or incoming events put into self.incoming_queue
        # b) any necessary threads running for a)
        # c) self.me (Person) defined, with Will's info
        # d) self.people (dict of People) defined, with everyone in an organization/backend
        # e) self.channels (dict of Channels) defined, with all available channels/rooms.
        #    Note that Channel asks for members, a list of People.
        # f) A way for self.handle, self.me, self.people, and self.channels to be kept accurate,
        #    with a maximum lag of 60 seconds.
        self.people = {}
        self.channels = {}
        self.me = Person(
            id="will",
            handle="will",
            mention_handle="@will",
            source=Bunch(),
            name="William T. Botterton",
        )

        # Do this to get the first "you" prompt.
        self.pubsub.publish('message.incoming.stdin',
                            (Message(content="",
                                     type="message.incoming",
                                     is_direct=True,
                                     is_private_chat=True,
                                     is_group_chat=False,
                                     backend=self.internal_name,
                                     sender=self.partner,
                                     will_is_mentioned=False,
                                     will_said_it=False,
                                     backend_supports_acl=False,
                                     original_incoming_event={})))