Python - possible to only send message when keyword is detected in BOTH keyword lists?
I have a python script that detects a keyword from a keyword list keywords = ['camera', 'nikon']
and then sends a message to Slack like the following
Keyword camera detected
'Reddit post url'
'reddit comment that contains the keyword'
If the script detects a keyword from a second keyword list color_keywords = ['red', 'blue']
then it posts the following
Keyword camera detected
'Reddit post url'
'reddit comment that contains the keyword'
Color was detected
My question is, am I somehow able to have the script so it ONLY sends a message if a keyword from EACH keyword list is found?
So if it only finds a keyword from the first list, it will be ignored, if it finds one from the second list, it will also be ignored. but if it finds a keyword from BOTH lists, it will send the message to slack.
Below is my current code
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'})
Any help will be greatly appreciated!
python python-3.x python-requests slack-api praw
add a comment |
I have a python script that detects a keyword from a keyword list keywords = ['camera', 'nikon']
and then sends a message to Slack like the following
Keyword camera detected
'Reddit post url'
'reddit comment that contains the keyword'
If the script detects a keyword from a second keyword list color_keywords = ['red', 'blue']
then it posts the following
Keyword camera detected
'Reddit post url'
'reddit comment that contains the keyword'
Color was detected
My question is, am I somehow able to have the script so it ONLY sends a message if a keyword from EACH keyword list is found?
So if it only finds a keyword from the first list, it will be ignored, if it finds one from the second list, it will also be ignored. but if it finds a keyword from BOTH lists, it will send the message to slack.
Below is my current code
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'})
Any help will be greatly appreciated!
python python-3.x python-requests slack-api praw
add a comment |
I have a python script that detects a keyword from a keyword list keywords = ['camera', 'nikon']
and then sends a message to Slack like the following
Keyword camera detected
'Reddit post url'
'reddit comment that contains the keyword'
If the script detects a keyword from a second keyword list color_keywords = ['red', 'blue']
then it posts the following
Keyword camera detected
'Reddit post url'
'reddit comment that contains the keyword'
Color was detected
My question is, am I somehow able to have the script so it ONLY sends a message if a keyword from EACH keyword list is found?
So if it only finds a keyword from the first list, it will be ignored, if it finds one from the second list, it will also be ignored. but if it finds a keyword from BOTH lists, it will send the message to slack.
Below is my current code
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'})
Any help will be greatly appreciated!
python python-3.x python-requests slack-api praw
I have a python script that detects a keyword from a keyword list keywords = ['camera', 'nikon']
and then sends a message to Slack like the following
Keyword camera detected
'Reddit post url'
'reddit comment that contains the keyword'
If the script detects a keyword from a second keyword list color_keywords = ['red', 'blue']
then it posts the following
Keyword camera detected
'Reddit post url'
'reddit comment that contains the keyword'
Color was detected
My question is, am I somehow able to have the script so it ONLY sends a message if a keyword from EACH keyword list is found?
So if it only finds a keyword from the first list, it will be ignored, if it finds one from the second list, it will also be ignored. but if it finds a keyword from BOTH lists, it will send the message to slack.
Below is my current code
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'})
Any help will be greatly appreciated!
python python-3.x python-requests slack-api praw
python python-3.x python-requests slack-api praw
edited Nov 24 '18 at 6:15
s3cur3
858722
858722
asked Nov 24 '18 at 1:40
VestipialVestipial
86
86
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Sure! The code below is excerpted for brevity:
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()]
for comment in comment_stream:
if not should_be_ignored(comment):
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)
The key insight here is: you create your lists of matches first, and then afterward examine them to decide if you want to send a message. In this case, only if both lists are not empty will you progress to sending the message.
(Implementation of should_be_ignored()
and send_message()
are, of course, left as an exercise to the reader. :) )
EDIT: Complete implementation of the original code:
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_TEMPLATE = """Keyword *{keyword}* and color *{color}* detected
https://www.reddit.com{permalink}
```{comment_body}```"""
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/xxxxxxx/0KOjl9251TZExxxxxxxx',
data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
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()]
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 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)
Note that all I've done (aside from the new requirement that we have both a color and a keyword before sending a message) is to pull out some of your business logic into the should_be_ignored()
and send_message()
functions, hopefully clarifying the intent of the main body of code. This should be a drop-in replacement for the sample you started with.
Thank you so much for answering!. I have been trying to format it into my code, but am having trouble of where to put it and what to take out of my current code? Would it be possible if you could show me how I would format it? Sorry, I am new to python and just trying to get my head around it haha
– Vestipial
Nov 24 '18 at 6:08
@Vestipial, edited to include the complete sample you provided. :) And, erm... sorry I can't help myself with the refactorings...
– s3cur3
Nov 24 '18 at 19:58
haha wow, thank you so much!, yep, I am just too new at python to have figured that out haha. So I have put the code in and tried to sort everything myself, but now I am getting the following errorTraceback (most recent call last): File "fudbot-client.py", line 37, in <module> keyword=keywords[0], NameError: name 'keywords' is not defined
I tried for a while messing around with the code, but it didn't help haha. I have pasted the entire script, maybe I have just missed a line somewhere? pastebin.com/hj4JSyhR Once again, thank you for your detailed help!
– Vestipial
Nov 25 '18 at 0:31
Looks like the indentation on yoursend_message()
is broken. Lines 30 through 43 in your PasteBin link should all be indented as part of thesend_message()
definition. And you'll probably want to move your response-handling code (lines 75 through 93) intosend_message()
as well.
– s3cur3
Nov 25 '18 at 19:55
Thank you, I got them all sorted out, Now I have a strange one. I get no errors, the script runs, shows the reddit username (so I guess it logged in) but then the script just ends. but with no errors or anything. it just jumps back to the command prompt which is strange? pastebin.com/m8tu2LRn
– Vestipial
Nov 26 '18 at 13:20
|
show 3 more comments
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53454472%2fpython-possible-to-only-send-message-when-keyword-is-detected-in-both-keyword%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Sure! The code below is excerpted for brevity:
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()]
for comment in comment_stream:
if not should_be_ignored(comment):
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)
The key insight here is: you create your lists of matches first, and then afterward examine them to decide if you want to send a message. In this case, only if both lists are not empty will you progress to sending the message.
(Implementation of should_be_ignored()
and send_message()
are, of course, left as an exercise to the reader. :) )
EDIT: Complete implementation of the original code:
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_TEMPLATE = """Keyword *{keyword}* and color *{color}* detected
https://www.reddit.com{permalink}
```{comment_body}```"""
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/xxxxxxx/0KOjl9251TZExxxxxxxx',
data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
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()]
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 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)
Note that all I've done (aside from the new requirement that we have both a color and a keyword before sending a message) is to pull out some of your business logic into the should_be_ignored()
and send_message()
functions, hopefully clarifying the intent of the main body of code. This should be a drop-in replacement for the sample you started with.
Thank you so much for answering!. I have been trying to format it into my code, but am having trouble of where to put it and what to take out of my current code? Would it be possible if you could show me how I would format it? Sorry, I am new to python and just trying to get my head around it haha
– Vestipial
Nov 24 '18 at 6:08
@Vestipial, edited to include the complete sample you provided. :) And, erm... sorry I can't help myself with the refactorings...
– s3cur3
Nov 24 '18 at 19:58
haha wow, thank you so much!, yep, I am just too new at python to have figured that out haha. So I have put the code in and tried to sort everything myself, but now I am getting the following errorTraceback (most recent call last): File "fudbot-client.py", line 37, in <module> keyword=keywords[0], NameError: name 'keywords' is not defined
I tried for a while messing around with the code, but it didn't help haha. I have pasted the entire script, maybe I have just missed a line somewhere? pastebin.com/hj4JSyhR Once again, thank you for your detailed help!
– Vestipial
Nov 25 '18 at 0:31
Looks like the indentation on yoursend_message()
is broken. Lines 30 through 43 in your PasteBin link should all be indented as part of thesend_message()
definition. And you'll probably want to move your response-handling code (lines 75 through 93) intosend_message()
as well.
– s3cur3
Nov 25 '18 at 19:55
Thank you, I got them all sorted out, Now I have a strange one. I get no errors, the script runs, shows the reddit username (so I guess it logged in) but then the script just ends. but with no errors or anything. it just jumps back to the command prompt which is strange? pastebin.com/m8tu2LRn
– Vestipial
Nov 26 '18 at 13:20
|
show 3 more comments
Sure! The code below is excerpted for brevity:
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()]
for comment in comment_stream:
if not should_be_ignored(comment):
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)
The key insight here is: you create your lists of matches first, and then afterward examine them to decide if you want to send a message. In this case, only if both lists are not empty will you progress to sending the message.
(Implementation of should_be_ignored()
and send_message()
are, of course, left as an exercise to the reader. :) )
EDIT: Complete implementation of the original code:
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_TEMPLATE = """Keyword *{keyword}* and color *{color}* detected
https://www.reddit.com{permalink}
```{comment_body}```"""
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/xxxxxxx/0KOjl9251TZExxxxxxxx',
data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
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()]
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 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)
Note that all I've done (aside from the new requirement that we have both a color and a keyword before sending a message) is to pull out some of your business logic into the should_be_ignored()
and send_message()
functions, hopefully clarifying the intent of the main body of code. This should be a drop-in replacement for the sample you started with.
Thank you so much for answering!. I have been trying to format it into my code, but am having trouble of where to put it and what to take out of my current code? Would it be possible if you could show me how I would format it? Sorry, I am new to python and just trying to get my head around it haha
– Vestipial
Nov 24 '18 at 6:08
@Vestipial, edited to include the complete sample you provided. :) And, erm... sorry I can't help myself with the refactorings...
– s3cur3
Nov 24 '18 at 19:58
haha wow, thank you so much!, yep, I am just too new at python to have figured that out haha. So I have put the code in and tried to sort everything myself, but now I am getting the following errorTraceback (most recent call last): File "fudbot-client.py", line 37, in <module> keyword=keywords[0], NameError: name 'keywords' is not defined
I tried for a while messing around with the code, but it didn't help haha. I have pasted the entire script, maybe I have just missed a line somewhere? pastebin.com/hj4JSyhR Once again, thank you for your detailed help!
– Vestipial
Nov 25 '18 at 0:31
Looks like the indentation on yoursend_message()
is broken. Lines 30 through 43 in your PasteBin link should all be indented as part of thesend_message()
definition. And you'll probably want to move your response-handling code (lines 75 through 93) intosend_message()
as well.
– s3cur3
Nov 25 '18 at 19:55
Thank you, I got them all sorted out, Now I have a strange one. I get no errors, the script runs, shows the reddit username (so I guess it logged in) but then the script just ends. but with no errors or anything. it just jumps back to the command prompt which is strange? pastebin.com/m8tu2LRn
– Vestipial
Nov 26 '18 at 13:20
|
show 3 more comments
Sure! The code below is excerpted for brevity:
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()]
for comment in comment_stream:
if not should_be_ignored(comment):
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)
The key insight here is: you create your lists of matches first, and then afterward examine them to decide if you want to send a message. In this case, only if both lists are not empty will you progress to sending the message.
(Implementation of should_be_ignored()
and send_message()
are, of course, left as an exercise to the reader. :) )
EDIT: Complete implementation of the original code:
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_TEMPLATE = """Keyword *{keyword}* and color *{color}* detected
https://www.reddit.com{permalink}
```{comment_body}```"""
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/xxxxxxx/0KOjl9251TZExxxxxxxx',
data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
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()]
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 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)
Note that all I've done (aside from the new requirement that we have both a color and a keyword before sending a message) is to pull out some of your business logic into the should_be_ignored()
and send_message()
functions, hopefully clarifying the intent of the main body of code. This should be a drop-in replacement for the sample you started with.
Sure! The code below is excerpted for brevity:
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()]
for comment in comment_stream:
if not should_be_ignored(comment):
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)
The key insight here is: you create your lists of matches first, and then afterward examine them to decide if you want to send a message. In this case, only if both lists are not empty will you progress to sending the message.
(Implementation of should_be_ignored()
and send_message()
are, of course, left as an exercise to the reader. :) )
EDIT: Complete implementation of the original code:
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_TEMPLATE = """Keyword *{keyword}* and color *{color}* detected
https://www.reddit.com{permalink}
```{comment_body}```"""
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/xxxxxxx/0KOjl9251TZExxxxxxxx',
data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
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()]
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 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)
Note that all I've done (aside from the new requirement that we have both a color and a keyword before sending a message) is to pull out some of your business logic into the should_be_ignored()
and send_message()
functions, hopefully clarifying the intent of the main body of code. This should be a drop-in replacement for the sample you started with.
edited Nov 24 '18 at 19:57
answered Nov 24 '18 at 2:03
s3cur3s3cur3
858722
858722
Thank you so much for answering!. I have been trying to format it into my code, but am having trouble of where to put it and what to take out of my current code? Would it be possible if you could show me how I would format it? Sorry, I am new to python and just trying to get my head around it haha
– Vestipial
Nov 24 '18 at 6:08
@Vestipial, edited to include the complete sample you provided. :) And, erm... sorry I can't help myself with the refactorings...
– s3cur3
Nov 24 '18 at 19:58
haha wow, thank you so much!, yep, I am just too new at python to have figured that out haha. So I have put the code in and tried to sort everything myself, but now I am getting the following errorTraceback (most recent call last): File "fudbot-client.py", line 37, in <module> keyword=keywords[0], NameError: name 'keywords' is not defined
I tried for a while messing around with the code, but it didn't help haha. I have pasted the entire script, maybe I have just missed a line somewhere? pastebin.com/hj4JSyhR Once again, thank you for your detailed help!
– Vestipial
Nov 25 '18 at 0:31
Looks like the indentation on yoursend_message()
is broken. Lines 30 through 43 in your PasteBin link should all be indented as part of thesend_message()
definition. And you'll probably want to move your response-handling code (lines 75 through 93) intosend_message()
as well.
– s3cur3
Nov 25 '18 at 19:55
Thank you, I got them all sorted out, Now I have a strange one. I get no errors, the script runs, shows the reddit username (so I guess it logged in) but then the script just ends. but with no errors or anything. it just jumps back to the command prompt which is strange? pastebin.com/m8tu2LRn
– Vestipial
Nov 26 '18 at 13:20
|
show 3 more comments
Thank you so much for answering!. I have been trying to format it into my code, but am having trouble of where to put it and what to take out of my current code? Would it be possible if you could show me how I would format it? Sorry, I am new to python and just trying to get my head around it haha
– Vestipial
Nov 24 '18 at 6:08
@Vestipial, edited to include the complete sample you provided. :) And, erm... sorry I can't help myself with the refactorings...
– s3cur3
Nov 24 '18 at 19:58
haha wow, thank you so much!, yep, I am just too new at python to have figured that out haha. So I have put the code in and tried to sort everything myself, but now I am getting the following errorTraceback (most recent call last): File "fudbot-client.py", line 37, in <module> keyword=keywords[0], NameError: name 'keywords' is not defined
I tried for a while messing around with the code, but it didn't help haha. I have pasted the entire script, maybe I have just missed a line somewhere? pastebin.com/hj4JSyhR Once again, thank you for your detailed help!
– Vestipial
Nov 25 '18 at 0:31
Looks like the indentation on yoursend_message()
is broken. Lines 30 through 43 in your PasteBin link should all be indented as part of thesend_message()
definition. And you'll probably want to move your response-handling code (lines 75 through 93) intosend_message()
as well.
– s3cur3
Nov 25 '18 at 19:55
Thank you, I got them all sorted out, Now I have a strange one. I get no errors, the script runs, shows the reddit username (so I guess it logged in) but then the script just ends. but with no errors or anything. it just jumps back to the command prompt which is strange? pastebin.com/m8tu2LRn
– Vestipial
Nov 26 '18 at 13:20
Thank you so much for answering!. I have been trying to format it into my code, but am having trouble of where to put it and what to take out of my current code? Would it be possible if you could show me how I would format it? Sorry, I am new to python and just trying to get my head around it haha
– Vestipial
Nov 24 '18 at 6:08
Thank you so much for answering!. I have been trying to format it into my code, but am having trouble of where to put it and what to take out of my current code? Would it be possible if you could show me how I would format it? Sorry, I am new to python and just trying to get my head around it haha
– Vestipial
Nov 24 '18 at 6:08
@Vestipial, edited to include the complete sample you provided. :) And, erm... sorry I can't help myself with the refactorings...
– s3cur3
Nov 24 '18 at 19:58
@Vestipial, edited to include the complete sample you provided. :) And, erm... sorry I can't help myself with the refactorings...
– s3cur3
Nov 24 '18 at 19:58
haha wow, thank you so much!, yep, I am just too new at python to have figured that out haha. So I have put the code in and tried to sort everything myself, but now I am getting the following error
Traceback (most recent call last): File "fudbot-client.py", line 37, in <module> keyword=keywords[0], NameError: name 'keywords' is not defined
I tried for a while messing around with the code, but it didn't help haha. I have pasted the entire script, maybe I have just missed a line somewhere? pastebin.com/hj4JSyhR Once again, thank you for your detailed help!– Vestipial
Nov 25 '18 at 0:31
haha wow, thank you so much!, yep, I am just too new at python to have figured that out haha. So I have put the code in and tried to sort everything myself, but now I am getting the following error
Traceback (most recent call last): File "fudbot-client.py", line 37, in <module> keyword=keywords[0], NameError: name 'keywords' is not defined
I tried for a while messing around with the code, but it didn't help haha. I have pasted the entire script, maybe I have just missed a line somewhere? pastebin.com/hj4JSyhR Once again, thank you for your detailed help!– Vestipial
Nov 25 '18 at 0:31
Looks like the indentation on your
send_message()
is broken. Lines 30 through 43 in your PasteBin link should all be indented as part of the send_message()
definition. And you'll probably want to move your response-handling code (lines 75 through 93) into send_message()
as well.– s3cur3
Nov 25 '18 at 19:55
Looks like the indentation on your
send_message()
is broken. Lines 30 through 43 in your PasteBin link should all be indented as part of the send_message()
definition. And you'll probably want to move your response-handling code (lines 75 through 93) into send_message()
as well.– s3cur3
Nov 25 '18 at 19:55
Thank you, I got them all sorted out, Now I have a strange one. I get no errors, the script runs, shows the reddit username (so I guess it logged in) but then the script just ends. but with no errors or anything. it just jumps back to the command prompt which is strange? pastebin.com/m8tu2LRn
– Vestipial
Nov 26 '18 at 13:20
Thank you, I got them all sorted out, Now I have a strange one. I get no errors, the script runs, shows the reddit username (so I guess it logged in) but then the script just ends. but with no errors or anything. it just jumps back to the command prompt which is strange? pastebin.com/m8tu2LRn
– Vestipial
Nov 26 '18 at 13:20
|
show 3 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53454472%2fpython-possible-to-only-send-message-when-keyword-is-detected-in-both-keyword%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown