Here is my code. It is a bot that finds keywords from a subreddit and posts a reply based on the keyword.
It has 3 different keywords to search for, and a specific answer to each keyword.
But it should randomize which keyword:answer to print out. How do I do this?
Sometimes it will want to say "Hello" to 'hello' comments, other times 'Goodbye' to 'goodbye' comments and so on.
It has a sleeptime of 10 minutes between each scan.
import random
import time
hello_comment = "Hello"
goodbye_comment = "Goodbye"
it_is_true = "It is true"
for submission in subreddit.hot(limit=10):
print(submission.title)
for comment in submission.comments:
if hasattr(comment, "body"):
comment_lower = comment.body.lower()
if " hello " in comment_lower:
print(comment.body)
comment.reply(penge_comment)
elif " goodbye" in comment_lower:
print(comment.body)
comment.reply(koster_comment)
elif " is it true? " in comment_lower:
print(comment.body)
comment.reply(it_is_true)
time.sleep(600)
CodePudding user response:
you can
import random
move your answers in a list
answers =["hi","hello","bye"]
change your answer to
comment.reply(random.choice(answers))
random.choice will pick a random answer for you.
This is what you want if you have multiple keywords:
Create a answers dict {keyword: list[answer,]}
answers = {"keyword1":["a","b"],"keyword2":["c","d"]}
for keyword in answers:
if keyword in comment_lower:
comment.reply(random.choice(answers[keyword]))
break
CodePudding user response:
You can create a list with the options you want to print and choose one element randomly:
import random
l = ["text 1", "text 2", "text 3" ]
print(random.choice(l))