-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.py
126 lines (109 loc) · 5.39 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import os
import ast
import requests # Import requests to use for the Discord webhook
import time
from dotenv import load_dotenv
import praw
from sqlitedict import SqliteDict
# Load environment variables from .env file
# Will not overwrite existing environment variables
load_dotenv()
db = SqliteDict("data/reddit.sqlite", autocommit=True)
# Reddit API credentials
client_id = os.environ["CLIENT_ID"]
client_secret = os.environ["CLIENT_SECRET"]
user_agent = 'Reddit Sticky Bot'
username = os.environ["USERNAME"]
password = os.environ["PASSWORD"]
# Whitelisted users
whitelisted_users = ast.literal_eval(os.environ["WHITELIST"])
whitelisted_users_lower = [name.lower() for name in whitelisted_users]
# Discord Webhook URL
try:
discord_webhook_url = os.environ["DISCORD_WEBHOOK_URL"]
print(f"Using webhook: {discord_webhook_url}")
except:
discord_webhook_url = None
print(f"No webhook URL set.")
# Initialize PRAW with your credentials
reddit = praw.Reddit(client_id=client_id,
client_secret=client_secret,
user_agent=user_agent,
username=username,
password=password)
reddit.validate_on_submit = True
bot_user = reddit.user.me()
# Subreddit to monitor
subreddit_name = os.environ["SUBREDDIT"]
subreddit = reddit.subreddit(subreddit_name)
stream = subreddit.stream.comments(skip_existing=True)
print(f"Bot {bot_user} connected and listening in r/{subreddit_name}")
print(f"Whitelisted users: {whitelisted_users_lower}")
# The text for the sticky comment
sticky_comment_text = """
This post contains replies from employees of Keen Games, you can see them here:
"""
def send_to_discord(message):
"""
Sends a message to the Discord webhook.
"""
if not discord_webhook_url:
return
data = {"content": message}
response = requests.post(discord_webhook_url, json=data)
try:
response.raise_for_status()
except Exception as error:
print(f"[{time.asctime()}] ERROR: {error}\n")
def sticky_comment_on_whitelisted_user_post():
for comment in stream:
# Check if new comment is from a whitelisted username
if comment.author and (comment.author.name.lower() in whitelisted_users_lower):
print(f"Found a post by whitelisted user: {comment.author.name}")
submission = comment.submission
existing_sticky = None
# Check if post already has developer comments bot sticky
if submission.id in db.keys():
existing_sticky = reddit.comment(db[submission.id])
print(f"Found bot post id: {existing_sticky.id}")
if existing_sticky:
sticky_body = existing_sticky.body
# Append comment to template
comment_body:str = comment.body
comment_body_split = comment_body.split()
# Shorten comment to first 5 words if longer
if (len(comment_body_split) > 5):
comment_body = " ".join(comment_body_split[:5]) + " ..."
sticky_comment_text_with_comment = f"{sticky_body}\n\n/u/{comment.author.name} posted a comment: [{comment_body}]({comment.permalink}?context=1)"
# Edit sticky comment with new post
existing_sticky.edit(sticky_comment_text_with_comment)
print(f"Edited a comment on post: {submission.title}")
# Send notification to Discord
send_to_discord(f"A stickied reply has been updated in r/{subreddit_name} by {comment.author.name}. [Link to comment](<https://www.reddit.com{comment.permalink}?context=1>)")
# Else, create new comment and sticky
else:
# Append comment to template
comment_body:str = comment.body
comment_body_split = comment_body.split()
# Shorten comment to first 5 words if longer
if (len(comment_body_split) > 5):
comment_body = " ".join(comment_body_split[:5]) + " ..."
sticky_comment_text_with_comment = f"{sticky_comment_text}\n\n/u/{comment.author.name} posted a comment: [{comment_body}]({comment.permalink}?context=1)"
# Post the comment
bot_sticky_comment = submission.reply(sticky_comment_text_with_comment)
db[submission.id] = bot_sticky_comment.id
# Sticky and distinguish the comment
bot_sticky_comment.mod.distinguish(how='yes', sticky=True)
print(f"Stickied a comment on post: {submission.title}\nPost id: {submission.id}\nComment id: {bot_sticky_comment.id}")
# Send notification to Discord
send_to_discord(f"A stickied reply has been posted in r/{subreddit_name} by {comment.author.name}. [Link to comment](<https://www.reddit.com{comment.permalink}?context=1>)")
while True:
try:
# Run the bot
stream = subreddit.stream.comments(skip_existing=True)
sticky_comment_on_whitelisted_user_post()
print(f"[{time.asctime()}] Retrying connection in 60 seconds...\n")
except Exception as error:
print(f"[{time.asctime()}] ERROR: {error}\n")
print(f"[{time.asctime()}] Retrying connection in 60 seconds...\n")
time.sleep(60)