Advertisement
Luke_Username

fill_rt_table.py

Aug 6th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. import psycopg2 # Interface with PostgreSQL
  2. import config   # Login details
  3. import praw     # Interface with Reddit's API
  4. import re       # Regular expressions
  5.  
  6. def bot_login():
  7.     print("Logging in...")
  8.     r = praw.Reddit(username = config.r_username,
  9.                 password = config.r_password,
  10.                 client_id = config.client_id,
  11.                 client_secret = config.client_secret,
  12.                 user_agent = "respectthread responder v0.2")
  13.     print("Logged in")
  14.     return r
  15.  
  16. r = bot_login()
  17.  
  18. insert_query = "INSERT INTO respectthread (title, link) VALUES "
  19. wiki_text = open("wiki_source.txt", "r", encoding="utf-8").read()
  20. pattern = re.compile(r"\[.+]\((https://redd\.it/[a-zA-A0-9]{6})\)") # This regex pattern only matches Reddit shortlinks.
  21.                                                                     # Non-shortlinks can be found with \[.+\]\((?!https://redd\.it/[a-zA-A0-9]{6})(.+)\)
  22. matches = pattern.finditer(wiki_text)
  23. for match in matches:
  24.     shortlink = match.group(1)
  25.     respectthread = r.submission(url=shortlink)
  26.     title = respectthread.title.replace("'", "''")
  27.     insert_query += "('{}', '{}'),".format(title, shortlink)
  28.     print(title)
  29.  
  30. insert_query = insert_query.strip(',') + ';'                        # Replace trailing ',' with ';'
  31.  
  32.  
  33. #connect to the database
  34. con = psycopg2.connect(
  35.             host = config.host,
  36.             database = config.database,
  37.             user = config.d_user,
  38.             password = config.d_password
  39. )
  40. cur = con.cursor()
  41.  
  42. cur.execute(insert_query)
  43. con.commit()
  44. print("Inserted into database")
  45.  
  46. # Close the cursor and connection to prevent leaks
  47. cur.close()
  48. con.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement