Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # I think PMs don't work, so editing settings should be done by replying to the bot in any sub it has access to.
- # Import dependencies
- import praw
- import sqlite3
- import datetime
- import pytz
- import time
- import os
- import logging
- from praw.models import Message
- from praw.models import Comment
- from praw.models import SubredditMessage
- from dotenv import load_dotenv
- load_dotenv()
- #logger = logging.getLogger('prawcore')
- #logger.setLevel(logging.DEBUG)
- botUsername = "ActionByDayBOT"
- try:
- # Reddit initialization
- reddit = praw.Reddit(
- client_id="9yCd3MbHa6kSdkPqagq4TA",
- client_secret=os.getenv("CLIENT_SECRET"),
- user_agent="Action by Day (BOT)",
- username=botUsername,
- password=os.getenv("BOT_PASSWORD")
- )
- except Exception as e:
- print("Login error:")
- print(e)
- # Retry loop
- max_retries = 10
- retries = 0
- while retries < max_retries:
- try:
- # Try the API call
- username = reddit.user.me()
- if(username is None or username == "None"):
- raise Exception("Authentication passed but without a valid user.")
- print("Logged in successfully!")
- break
- except Exception as e:
- # Auth failed, retry
- retries += 1
- print(f"Auth failed, retrying (attempt {retries}/{max_retries})")
- print(e)
- time.sleep(2 * retries)
- # Connect to SQLite database
- conn = sqlite3.connect('bot.db')
- c = conn.cursor()
- # Create table to store subreddit configs
- c.execute('''
- CREATE TABLE IF NOT EXISTS config
- (id INTEGER PRIMARY KEY AUTOINCREMENT,
- subreddit_name TEXT,
- flair TEXT,
- day TEXT,
- timezone TEXT)
- ''')
- # Get config for a subreddit_name
- def get_config(subreddit_name):
- c.execute("SELECT * FROM config WHERE subreddit_name=?", (subreddit_name,))
- return c.fetchone()
- # Update config for a subreddit
- def update_config(subreddit_name, flair, day, timezone):
- c.execute("""UPDATE config
- SET flair=?, day=?, timezone=?
- WHERE subreddit_name=?""",
- (flair, day, timezone, subreddit_name))
- conn.commit()
- # Handle incoming Reddit messages
- def handle_message(message):
- # Split message into command and arguments
- command, *args = message.body.split()
- if command == "!help":
- # Return help text
- reply = get_help_text()
- else:
- subreddit_name = args[0]
- if not subreddit.moderator(reddit.user.me()):
- message.reply("I must be a moderator to configure this subreddit.")
- return
- if not subreddit.moderator(message.author):
- message.reply("You must be a moderator to configure this subreddit.")
- return
- if command == "!addflair":
- # Add flair config
- flair, day = args[1:]
- config = get_config(subreddit_name)
- if not config:
- # Initialize config if none exists
- c.execute("INSERT INTO config (subreddit_name) VALUES (?)", (subreddit_name,))
- update_config(subreddit_name, flair, day, config['timezone'])
- # Confirmation reply
- reply = "Flair added successfully"
- elif command == "!removeflair":
- # Remove flair config
- flair = args[1]
- config = get_config(subreddit_name)
- if not config:
- reply = "Subreddit not configured"
- else:
- # Remove flair text, leave other values
- update_config(subreddit_name, "", config['day'], config['timezone'])
- reply = "Flair removed successfully"
- elif command == "!timezone":
- # Update timezone
- timezone = args[1]
- config = get_config(subreddit_name)
- if not config:
- # Initialize if no config
- c.execute("INSERT INTO config (subreddit_name) VALUES (?)", (subreddit_name,))
- update_config(subreddit_name, config['flair'], config['day'], timezone)
- reply = "Timezone updated successfully"
- else:
- # Unknown command
- reply = "Unknown command. use !help for list of commands."
- # Send reply
- message.reply(reply)
- # Help text
- def get_help_text():
- return """
- Commands:
- !addflair <subreddit> <flair text> <day of week>
- !removeflair <subreddit> <flair text>
- !timezone <subreddit> <timezone>
- """
- # Check submissions in configured subreddits
- def on_main_sub():
- # Get all subreddit configs
- c.execute("SELECT * FROM config")
- configs = c.fetchall()
- # Loop through configs
- for config in configs:
- subreddit_name = config['subreddit_name']
- flair = config['flair']
- day = config['day']
- timezone = config['timezone']
- # Check submissions
- for submission in subreddit.stream.submissions():
- if submission.link_flair_text == flair:
- # Get current weekday
- current_day = get_weekday(timezone)
- if current_day != day:
- # Remove post
- submission.mod.remove()
- # Reply to author
- reply_to_author(submission, config)
- # Reply to author with reason
- def reply_to_author(submission, config):
- flair = config['flair']
- day = config['day']
- reply = f"The {flair} flair can only be used on {day}."
- submission.reply(reply)
- # Get weekday from timezone
- def get_weekday(timezone):
- tz = pytz.timezone(timezone)
- now = datetime.datetime.now(tz)
- return now.strftime("%A")
- # Main loop
- def main():
- while True:
- try:
- # Check submissions
- # on_main_sub()
- try:
- for message in reddit.inbox.unread(limit=None):
- print(type(message))
- if isinstance(message, Message):
- print(message.body)
- except Exception as e:
- print(f"Error reading private messages: {e}")
- except Exception as e:
- # Print any errors
- print(f"Global Error: {e}")
- time.sleep(60)
- main()
- subreddit = reddit.subreddit("all")
- for comment in subreddit.stream.comments(pause_after=-1): # stream will return None when there are no new objects in the stream
- if comment is None:
- for i in reddit.inbox.unread(limit=None):
- if isinstance(i, SubredditMessage): # make sure it's a comment, because it could also be a message
- try:
- i.author
- i.body
- except Exception as e:
- # Print any errors
- print(f"Failed to access potential mod invite message {e}")
- finally:
- if i.author is None:
- if not subreddit.moderator(reddit.user.me()):
- print("Accepted a mod invite")
- i.subreddit.mod.accept_invite()
- i.mark_read()
Advertisement
Add Comment
Please, Sign In to add comment