My First Reddit Bot
I have been learning Python since July. This has been a self-learning venture and to this point has been the longest I've gone learning a new skill outside of school. The fact that I have been able to do this gives me hope that I can actually learn anything I want. What I decided to do with my amateur knowledge is to create a bot for Reddit. This bot searches a specific subreddit for certain keywords and responds to that keyword with a message. The bot ran for a few days before I shut it down, it had accomplished its goals and served no purpose other than to show that I can do it.
I will admit, most if not all of the code was not actually written by me. I utilized GitHub and Reddit to answer questions and smooth out problems. However, I was able to read the code and understand what was being done, I also had to convert much of the code from Python 2 to 3.
The conversion of Python 2 code to Python 3 was easy, and automatic. The process, though, is one apparently little known by people. The process is called 2to3 and you can find it here on the Python website: https://docs.python.org/3/library/2to3.html.
Reddit bots take minimal Python ability, not to downplay my own accomplishment, but this is only the first step in becoming a fluent dev.
Here is the code that I used, keep in mind that in order to use it you'll need to convert it with 2to3:
Below is my edited code:
import praw import time import os import names def bot_login(): r = praw.Reddit(username = "**************", password = "*********", client_id = "***************", client_secret = "*****************", user_agent = "Bot v1.0") return r def run_bot(r, comments_replied_to): for comment in r.subreddit('#subredditname').comments(limit=15): if "#keyword" in comment.body and comment.id not in comments_replied_to and comment.author != r.user.me(): print("String with \"sample user comment\" found in comment " + comment.id) comment.reply("############"+ names.get_first_name()+"."+"#########)
print("Replied to comment " + comment.id) comments_replied_to.append(comment.id) with open ("comments_replied_to.txt", "a") as f: f.write(comment.id + "\n") print (comments_replied_to) time.sleep(60) def get_saved_comments(): if not os.path.isfile("comments_replied_to.txt"): comments_replied_to =  else: with open("comments_replied_to.txt", "r") as f: comments_replied_to = f.read() comments_replied_to = comments_replied_to.split("\n") comments_replied_to = [_f for _f in comments_replied_to if _f] return comments_replied_to r = bot_login() comments_replied_to = get_saved_comments() print (comments_replied_to) while True: run_bot(r, comments_replied_to)