def process(self):
        ok = self.answers[0]['boolean']
        if ok:
            group_name = self.group_name
            if not self.user_is_in_group(group_name, self.username):
                try:
                    self.add_to_group(group_name, self.username)
                    subject = 'User was added to %s' % group_name
                    s = '%s was added to the group %s because they self-certified.' % (
                        self.username, group_name)
                except DiscourseClientError, exc:
                    subject = 'User could not be added to %s' % group_name
                    s = '%s could not be added to the group %s. Maybe they are already a member?' % (
                        self.username, group_name)

                s += '<br>'
                url = 'https://forum.506investorgroup.com/g/%s' % group_name
                s += 'To change this, visit the %s group settings at ' % group_name
                s += url
                s += '.'
                for recipient in recipients:
                    send_simple_email(recipient, subject, s)
                    print 'sent email'
            else:
                print 'username is already in group'
def user_event_handler():

    # This handler handles user events, so mods can check for full name on user_created
    # and hopefully on user_updated.

    # Ideally I could put arbitrary reviewables on the queue, but that's not possible.
    # Creating a reviewable of type "User" applies only to new users- mods can approve
    # the user or not- so that's not appropriate for this. The best I can do is when a
    # user changes his name or username, I can flag the New Members topic at
    # https://forum.506investorgroup.com/t/policy-actual-full-name-must-be-used-on-the-forum/7298,
    # and in the message include the user's new name and username.

    # The check for new users could be done in either of two ways:
    # 1. This webhook, with type = user_created.
    # 2. The built-in option must_approve_users.
    # I'm trying the second option because it's no work, and blocks the new user until
    # they are approved. However I may still need a webhook here in case the user changes
    # their name or username.

    # Wait until we've approved a few new users via the built-in method before implementing this?

    event_type = request.headers['X-Discourse-Event-Type']
    event = request.headers['X-Discourse-Event']
    print 'event: ', event
    print 'event_type', event_type

    # Any checks for category are best done in the webhook settings
    if event_type == 'user' and event in ('user_created', 'user_updated'):

        user = request.json['user']

        print 'user created: '
        print user

        # just guessing
        name = user['name']
        username = user['username']

        url = "https://forum.506investorgroup.com/u/%s/summary" % username

        msg = 'User created or updated. username: %s, name: %s. Review here: %s.  ' % (
            username, name, url)

        print 'msg: ', msg

        send_simple_email('*****@*****.**', event, msg)

        client = create_client(1)

        # Must flag some post, so flag the full-name policy post (data-post-id from inspection)
        post_id = 50958

        # Note the flag method is currently added to client.py, not a subclass client506.py.
        client.flag(post_id, msg)

        return '', 200
    else:
        return '', 400
def topic_event_handler():

    # See https://meta.discourse.org/t/setting-up-webhooks/49045
    # See also https://forum.506investorgroup.com/admin/api/web_hooks

    # This handler handles new topics and flags the new topic for moderator review.
    # Mods will verify it has the right tags, is in the right category, etc.

    event_type = request.headers['X-Discourse-Event-Type']
    event = request.headers['X-Discourse-Event']
    print 'event: ', event

    # Any checks for category are best done in the webhook settings
    if event_type == 'topic' and event == 'topic_created':

        topic = request.json['topic']

        # Checks to make sure it's a normal public topic, not a PM or system message
        created_by = topic['created_by']['username']
        archetype = topic['archetype']
        user_id = topic['user_id']

        # Just the first check should be sufficient. User ID > 0 excludes system and discobot.
        if str(archetype) == 'regular' and user_id > 0:
            tags = topic.get('tags', [])
            topic_id = topic['id']
            title = topic['title']
            slug = topic['slug']
            # Could edit the webhook to deliver only Deals category
            # category_id = topic['category_id']
            url = "https://forum.506investorgroup.com/t/%s/%d" % (slug,
                                                                  topic_id)

            msg = '**[How to Review a New Topic](https://forum.506investorgroup.com/t/moderators-reviewing-each-new-topic/18317)**  ' \
                  '@%s created a new topic: \"%s\".  ' \
                  'Review here: %s.  ' % \
                  (created_by, title, url)

            send_simple_email('*****@*****.**', event, msg)

            client = create_client(1)
            post = client.post(topic_id, 1)
            post_id = post['post_stream']['posts'][0]['id']

            # Note the flag method is currently added to client.py, not a subclass client506.py.
            client.flag(post_id, msg)

        return '', 200
    else:
        return '', 400
    def run(self):
        # Data is the json as dict
        data = self.data
        if data:
            
            # email before patching or otherwise messing with the data
            if data['email'] == '*****@*****.**':
                try:
                    send_simple_email('*****@*****.**', 'json to debug', json.dumps(data))
                except Exception:
                    pass
            
            
            topics = data['activity']
            # print 'Digest.run got %s, %s, %d topics' % (data['username'], data['email'], len(topics))
            if topics:
                # Pre-processing for convenience
                self.patch(topics)
                self.order_categories(topics)

                num_visible_topics = len(topics)
                num_visible_posts = sum([len(t['posts']) for t in topics])

                post_contents = []
                for cat in self.ordered_main_categories:

                    # The duplicate topics are because of this line. When cat = Deals,
                    # and a topic's topic_categories is Premium Deals, then cat is in
                    # topic_categories. Need to check for equality, not containment.
                    # That's more complicated than it should be, because I've modified
                    # topic_categories in-place. I need to retain the original list,
                    # perhaps in a new key original_topic_categories, and change this
                    # line to test for equality of cat and original_topic_categories[0].
                    # Note cat is the *main* category.

                    # I can test using new json every day now, so no hurry.

                    # topics_in_cat = [t for t in topics if cat in t['topic_categories']]
                    # This fixes it in one case at least.
                    topics_in_cat = [t for t in topics if cat == t['original_topic_categories'][0]]


                    topics_in_cat.sort(cmp=cmp_topic_categories)
                    for topic in topics_in_cat:
                        post_content = self.topic_to_html(topic)
                        post_contents.append(post_content)

                username = data['username']
                summary = '<h3>%s, you have %d New Posts in %d Topics</h3>' % (username, num_visible_posts, num_visible_topics)
                subject = self.subject()
                posts_contents = ''.join(post_contents)
                topics_contents = self.make_topics_table(topics)

                special_contents = self.get_special_post()
                favorite_contents = self.get_favorite_posts()

                # dummy arg for now:
                manage_emails_url = ''

                email_address = data['email']


                recipients = ['*****@*****.**',
                              '*****@*****.**',
                              '*****@*****.**',
                              '*****@*****.**',
                              '*****@*****.**'
                              ]

                send_digest_email(email_address, topics_contents, posts_contents, summary, subject, manage_emails_url, special_contents, favorite_contents, username)

                logger.info('emailed %s %s' % (username, email_address))
def post_event_handler():

    # This handler handles new posts. If the post appears to contain wiring instructions,
    # flag the new topic for moderator review. Mods will add a staff notice warning about
    # wiring scams, if appropriate. This check does not need to be perfect- it can never
    # be perfect and it's easy enough for mods to ignore any false alarms.

    event_type = request.headers['X-Discourse-Event-Type']
    event = request.headers['X-Discourse-Event']
    print 'event: ', event
    print 'event_type', event_type

    # Any checks for category are best done in the webhook settings
    if event_type == 'post' and event == 'post_created':

        post = request.json['post']

        print 'post: '
        print post

        # Checks to make sure it's a normal public topic, not a PM or system message
        archetype = post.get('topic_archetype')
        user_id = post['user_id']

        print 'archetype: ', archetype

        if archetype != 'private_message' and user_id > 0:
            raw = post['raw']

            #raw = str(raw)  # trying to handle unicode issue
            #print 'raw: ', raw

            if contains_wiring_info(raw):

                print 'contains something about wires'

                slug = post['topic_slug']
                topic_id = post['topic_id']
                post_number = post['post_number']
                url = "https://forum.506investorgroup.com/t/%s/%d/%d" % (
                    slug, topic_id, post_number)

                msg = 'New post may contain wiring instructions. Add staff notice if needed. Review here: %s.  ' % url

                print 'msg: ', msg

                send_simple_email('*****@*****.**', event, msg)

                client = create_client(1)
                # post = client.post(topic_id, 1)
                # post_id = post['post_stream']['posts'][0]['id']
                post_id = post['id']

                print 'post_id', post_id

                # all working except not getting the right post_id.

                # Note the flag method is currently added to client.py, not a subclass client506.py.
                client.flag(post_id, msg)

        return '', 200
    else:
        return '', 400