python和PRAW reddit脚本出现问题-退出时没有错误?

时间:2018-11-29 12:53:14

标签: python python-3.x python-2.7 reddit praw

我有一个当前的reddit机器人,它从Reddit(从2个单独的关键字列表)中检测关键字,并且如果从BOTH关键字列表中检测到1个单词,或者仅从1个关键字列表中检测到1个关键字,或者检测到另一个关键字,则向Slack发送消息,它将被忽略。

我认为代码很好,并且没有出现任何错误。但是在脚本登录到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()

0 个答案:

没有答案