【发布时间】:2018-11-24 01:40:22
【问题描述】:
我有一个 python 脚本,它从关键字列表keywords = ['camera', 'nikon'] 中检测一个关键字,然后向 Slack 发送一条消息,如下所示
检测到关键字相机
'Reddit 帖子网址'
'包含关键字的reddit评论'
如果脚本从第二个关键字列表color_keywords = ['red', 'blue'] 中检测到一个关键字,那么它会发布以下内容
检测到关键字相机
'Reddit 帖子网址'
'包含关键字的reddit评论'
检测到颜色
我的问题是,我是否能够以某种方式拥有脚本,以便仅在找到每个关键字列表中的关键字时才发送消息? 所以如果它只从第一个列表中找到一个关键字,它将被忽略,如果它从第二个列表中找到一个,它也将被忽略。但如果它从 BOTH 列表中找到一个关键字,它会将消息发送到 slack。
下面是我当前的代码
MSG_TEMPLATE = """Keyword *{keyword}* detected
https://www.reddit.com{permalink}
```{comment_body}```"""
keywords = ['camera', 'nikon', 'canon']
color_keywords = ['blue', 'red']
with open(save_path, 'r') as fp:
alerted_comments = json.load(fp)
for comment in comment_stream:
if comment.id in alerted_comments:
continue
if comment.author: # if comment author hasn't deleted
if comment.author.name in ignore_users:
continue
if any(kw.lower() in comment.body.lower() for kw in keywords):
found_kws = [kw for kw in keywords if kw.lower() in comment.body.lower()]
msg = MSG_TEMPLATE.format(
keyword=found_kws[0],
permalink=comment.permalink,
comment_body=comment.body
)
if any(kw.lower() in comment.body.lower() for kw in color_keywords):
msg += "\n<!here> *A color was detected*"
slack_data = {'text': msg, 'mrkdwn': True,}
response = requests.post('https://hooks.slack.com/services/TB7AH6U2G/xxxxxxx/0KOjl9251TZExxxxxxxx',
data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
任何帮助将不胜感激!
【问题讨论】:
标签: python python-3.x python-requests slack-api praw