Проблема с python и сценарием PRAW reddit - выход без ошибок? - PullRequest
0 голосов
/ 29 ноября 2018

У меня есть текущий бот reddit, который обнаруживает ключевые слова из Reddit (из 2 отдельных списков ключевых слов) и отправляет сообщение в Slack, если обнаружено 1 слово из обоих списков ключевых слов, если обнаружено только 1 ключевое слово из 1 списка ключевых слов ИЛИ другое, он игнорируется.

Я думаю, что код в порядке, и я не получаю никаких ошибок.но после того, как скрипт входит в reddit и отображает имя пользователя в терминале, скрипт просто заканчивается.Я попытался добавить print () в несколько разделов, но я не обнаружил ошибок, которые мог бы найти (я новичок в Python, поэтому не очень понимаю, куда поместить print ().

Будетбыло бы возможно, если бы кто-то мог взглянуть и понять, почему сценарий не продолжается?

Код указан ниже.

import json
import time
import praw
import requests




class SlackError(Exception):
    # This isn't quite how I would handle this, so for now it's
    # just a hint of more to learn.
    pass

    #  http://praw.readthedocs.io/en/latest/getting_started/authentication.html
reddit = praw.Reddit(client_id='yyyyyyyyy',
             client_secret='xxxxxxxxxxxx',
             username='xxxuser',
             password='xxxpassword',
             user_agent='python3:KeyWordNotify:v1 (/u/myuser2)')
print(reddit.user.me())

you = reddit.redditor('myuser')  # this is the account that will receive the messages
  # scan comments in this subreddit

MSG_TEMPLATE = """Keyword *{keyword}* and color *{color}* detected
    https://www.reddit.com{permalink}
    ```{comment_body}```"""


SLACK_WEBHOOK = 'https://hooks.slack.com/services/TB7AH6U2G/xxxxxxxx/xxxxxx'


keywords = ['camera', 'nikon', 'canon']  
color_keywords = ['blue', 'red']
ignore_users = ['baduser1', 'baduser2', 'baduser3']  # case SENSITIVE
subreddit = reddit.subreddit('test')

comment_stream = subreddit.stream.comments()




def send_message(comment, keywords, colors):
    assert keywords and colors, "At this point, we should *only* be calling this function if we have at least one keyword and one color"



    msg = MSG_TEMPLATE.format(
        keyword=keywords[0],
        color=colors[0],
        permalink=comment.permalink,
        comment_body=comment.body
    )




    slack_data = {'text': msg, 'mrkdwn': True,}
    response = requests.post('https://hooks.slack.com/services/TB7AH6U2G/xxxxxx/xxxxxxx',data=json.dumps(slack_data), headers=       {'Content-Type': 'application/json'})



    if response.status_code == 200:
                # Moving this here so you don't miss a comment
                # because of an error. It does mean other errors
                # could potentially cause a repeat message. There
                # are ways to handle that.


        alerted_comments.append(comment.id)

        if len(alerted_comments) > 100:
            alerted_comments = alerted_comments[-100:]

    with open(save_path, 'w') as fp:
                    json.dump(alerted_comments, fp)



def should_be_ignored(comment, alerted):
    return comment.id in alerted or (comment.author and comment.author.name in ignore_users)

def find_keywords(comment, word_list):
    """:returns: List of matching keywords present in the comment, or the empty list"""
    return [word for word in word_list if word.lower() in comment.body.lower()]



    with open(save_path, 'r') as fp:
        alerted_comments = json.load(fp)

    for comment in comment_stream:
        if not should_be_ignored(comment, alerted_comments):
            found_kws = find_keywords(comment, keywords)
            found_colors = find_keywords(comment, color_keywords)

    if found_kws and found_colors:
            # At this point, we're guaranteed to have *both* one or more keywords *and* one or more colors
            send_message(comment, found_kws, found_colors)
            print()

    if __name__ == '__main__':
        while True:
            try:
                main(save_path='alerted_comments.json')
            except Exception as e:
                    print('There was an error: {}'.format(str(e)))
                    time.sleep(60)  # wait for 60 seconds before restarting
                    print()
...