Guest User

Untitled

a guest
Oct 23rd, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.38 KB | None | 0 0
  1. # !/usr/bin/env python
  2. # coding=utf-8
  3.  
  4. # import config
  5. # import postgresConfig
  6.  
  7. import praw
  8. import prawcore
  9. import psycopg2
  10. import time
  11. import unidecode
  12. import os
  13. import requests
  14. import requests.auth
  15. import logging
  16.  
  17.  
  18. def login():
  19. r = praw.Reddit('juvegoalbot')
  20. return r
  21.  
  22. FOOTER = '''___\n\n
  23. ^^[Wiki](https://www.reddit.com/r/juve_goal_bot/wiki/index)
  24. ^^| ^^[Feedback](/r/juve_goal_bot)
  25. ^^| ^^[Creator](/u/droidonomy)'''
  26.  
  27.  
  28. def parse_body(body):
  29. # Find comments that start with the keyword and start indexing the characters
  30. start_index = body.find('!goalbot ')
  31. # Remove first 8 characters to pull request
  32. body = body[start_index + 8:]
  33. # End indexing at a new line
  34. end_index = body.find('\n')
  35.  
  36. print('user query: {}'.format(body))
  37. # Split the query into different sections at each comma
  38. query = body.split(',')
  39.  
  40. return query
  41.  
  42.  
  43. def parse_body_assist(body):
  44. # Find comments that start with the keyword and start indexing the characters
  45. start_index = body.find('!assist ')
  46. # Remove first 8 characters to pull request
  47. body = body[start_index + 8:]
  48. # End indexing at a new line
  49. end_index = body.find('\n')
  50.  
  51. print('user query: {}'.format(body))
  52. # Split the query into different sections at each comma
  53. query = body.split(',')
  54.  
  55. return query
  56.  
  57.  
  58. def get_sql_items(query):
  59. # Create an empty array for params to be added to
  60. params = []
  61. # Designate variable for first portion of the query
  62. player_name = query[0].strip()
  63.  
  64. # Remove special characters
  65. player_name_string = unidecode.unidecode(player_name)
  66. # Add player_name to params array
  67. params.append(player_name_string)
  68.  
  69. # If query is longer than one section..
  70. if 0 <= 1 < len(query):
  71. # Create a variable for the second portion of the query
  72. second_query = query[1].strip()
  73. # Search to see if the second portion is a competion specific query
  74. if second_query == "ICC" or second_query == "serie a" or second_query == "allstars" or second_query == "ucl" or second_query == "coppa italia":
  75.  
  76. # Add second portion to the params
  77. params.append(second_query)
  78.  
  79. if 0 <= 2 < len(query):
  80.  
  81. third_query = query[2].strip()
  82. params.append(third_query)
  83. sqlquery = '''SELECT opposition, competition, season, url FROM juve_goals WHERE scorer = %s AND competition = %s AND season = %s; '''
  84. return sqlquery, params
  85.  
  86. # Build a query specific to search for player and competion
  87. sqlquery = '''SELECT opposition, competition, season, url FROM juve_goals WHERE scorer = %s AND competition = %s; '''
  88. print("Search via leagues")
  89. return sqlquery, params
  90.  
  91. elif second_query is None:
  92. # TODO handle this better....
  93. print('No second query item')
  94. return("no item")
  95.  
  96. elif second_query == "2018/2019" or second_query == "2017/2018":
  97. params.append(second_query)
  98. sqlquery = '''SELECT opposition, competition, season, url FROM juve_goals WHERE scorer = %s AND season = %s; '''
  99. return sqlquery, params
  100.  
  101. # If the second section does not state a competition
  102. else:
  103. # add second section to params
  104. params.append(second_query)
  105. if 0 <= 2 < len(query):
  106.  
  107. third_query = query[2].strip()
  108. params.append(third_query)
  109. sqlquery = '''SELECT opposition, competition, season, url FROM juve_goals WHERE scorer = %s AND opposition = %s AND season = %s; '''
  110. return sqlquery, params
  111.  
  112. # Query specifically for player and opposition
  113. sqlquery = '''SELECT opposition, competition, season, url FROM juve_goals WHERE scorer = %s AND opposition = %s; '''
  114. print("No league specified")
  115. return sqlquery, params
  116.  
  117.  
  118. def get_assist_items(query):
  119. # Create an empty array for params to be added to
  120. params = []
  121. # Designate variable for first portion of the query
  122. player_name = query[0].strip()
  123. # Add player_name to params array
  124. params.append(player_name)
  125.  
  126. # If query is longer than one section..
  127. if 0 <= 1 < len(query):
  128. # Create a variable for the second portion of the query
  129. second_query = query[1].strip()
  130. # Search to see if the second portion is a competion specific query
  131. if second_query == "icc" or second_query == "serie a" or second_query == "allstars" or second_query == "ucl" or second_query == "coppa italia":
  132.  
  133. # Add second portion to the params
  134. params.append(second_query)
  135.  
  136. if 0 <= 2 < len(query):
  137.  
  138. third_query = query[2].strip()
  139. params.append(third_query)
  140. sqlquery = '''SELECT opposition, competition, season, url FROM juve_goals WHERE assist = %s AND competition = %s AND season = %s; '''
  141. return sqlquery, params
  142.  
  143. # Build a query specific to search for player and competion
  144. sqlquery = '''SELECT opposition, competition, season, url FROM juve_goals WHERE assist = %s AND competition = %s; '''
  145. print("Search via leagues")
  146. return sqlquery, params
  147.  
  148. elif second_query == "2018/2019" or "2017/2018" or second_query == "2016/2017" or second_query == "2015/2016" or second_query == "2014/2015" or second_query == "2013/2014" or second_query == "2012/2013" or second_query == "2011/2012" or second_query == "2010/2011" or second_query == "2009/2010" or second_query == "2008/2009" or second_query == "2007/2008" or second_query == "2006/2007" or second_query == "2005/2006" or second_query == "2004/2005" or second_query == "2003/2004" or second_query == "2002/2003" or second_query == "2001/2002" or second_query == "2000/2001":
  149. params.append(second_query)
  150. sqlquery = '''SELECT opposition, competition, season, url FROM juve_goals WHERE assist = %s AND season = %s; '''
  151. return sqlquery, params
  152.  
  153. # If the second section does not state a competition
  154. else:
  155. # add second section to params
  156. params.append(second_query)
  157. if 0 <= 2 < len(query):
  158.  
  159. third_query = query[2].strip()
  160. params.append(third_query)
  161. sqlquery = '''SELECT opposition, competition, season, url FROM juve_goals WHERE assist = %s AND opposition = %s AND season = %s; '''
  162. return sqlquery, params
  163.  
  164. # Query specifically for player and opposition
  165. sqlquery = '''SELECT opposition, competition, season, url FROM juve_goals WHERE assist = %s AND opposition = %s; '''
  166. print("No league specified")
  167. return sqlquery, params
  168.  
  169.  
  170. def get_urls(sqlquery, params):
  171. is_prod = os.environ.get('IS_HEROKU', None)
  172.  
  173. print("is prod?? ", is_prod)
  174.  
  175. if is_prod:
  176. # Define our connection string
  177. host = os.environ['localhost']
  178. dbname = os.environ['juve_goals_bot']
  179. user = os.environ['postgres']
  180. password = os.environ['xxxxxxxxx']
  181. conn_string = "host='{}' dbname='{}' user='{}' password='{}'".format(host, dbname, user, password)
  182. # print the connection string we will use to connect
  183. print("Connecting to database\n ->%s" % (conn_string))
  184.  
  185. # get a connection, if a connect cannot be made an exception will be raised here
  186. conn = psycopg2.connect(conn_string)
  187.  
  188. # conn.cursor will return a cursor object, you can use this cursor to perform queries
  189. cursor = conn.cursor()
  190. print("Connected!\n")
  191.  
  192. else:
  193. host = 'localhost'
  194. dbname = 'juve_goals_bot'
  195. user = 'postgres'
  196. password = 'xxxxxxxx'
  197. # Define our connection string
  198. # conn_string = "host='{}' dbname='{}' user='{}' password='{}'".format(host,dbname,user,password)
  199. conn_string = "host='localhost' dbname='juve_goals_bot' user='postgres' password ='xxxxxxx'"
  200.  
  201. # print the connection string we will use to connect
  202. print("Connecting to database\n ->%s" % (conn_string))
  203.  
  204. # get a connection, if a connect cannot be made an exception will be raised here
  205. conn = psycopg2.connect(conn_string)
  206.  
  207. # conn.cursor will return a cursor object, you can use this cursor to perform queries
  208. cursor = conn.cursor()
  209. print("Connected!\n")
  210.  
  211. # Variables to connect to DB
  212. conn_string = "host='localhost' dbname='juve_goals_bot' user='postgres' password ='xxxxxxxx'"
  213. # Connect to DB
  214. conn = psycopg2.connect(conn_string)
  215. cursor = conn.cursor()
  216. # Execute query to db for data
  217. cursor.execute(sqlquery, params)
  218. reply = ''
  219.  
  220. if cursor:
  221. # For each record that comes back, loop through and build the reply
  222. for record in cursor:
  223. reply += '[{}: {} ({})](https://gfycat.com/{})'.format(record[0], record[1], record[2], record[3])
  224. reply += '\n\n'
  225.  
  226. reply += FOOTER
  227. return reply
  228.  
  229.  
  230. def run(r):
  231. # Get all comments from designated subreddits
  232. for comment in r.subreddit('juve+juve_goal_bot').stream.comments():
  233. body = comment.body
  234. # listen for any comments that contain the keyword
  235. if "!goalbot" in body:
  236. with open('goalComments.txt', 'r') as outfile:
  237. seen_comments = outfile.read().splitlines()
  238. print(comment.id)
  239. # See if the comment in the subreddit has not already been answered.
  240. if comment.id not in seen_comments:
  241.  
  242. body = comment.body.lower()
  243. query = parse_body(body)
  244. sql = get_sql_items(query)
  245. # If a query the individual tried to use is not in the correct format
  246. # mark it as helped and let the individual know where to get help.
  247. if sql is None:
  248. reply = 'It looks like your request is in a format I do not understand. Feel free to [post a question in the help thread.](https://www.reddit.com/r/juve_goal_bot/comments/9qpxjh/juve_goal_bot_questionsbug_reports)'
  249. comment.reply(reply)
  250. with open('goalComments.txt', 'a+') as outfile:
  251. outfile.write(comment.id + '\n')
  252.  
  253. print("not valid query..")
  254. time.sleep(10)
  255. # If the comment uses the correct format find the results
  256. else:
  257. print("SQL: ", sql)
  258. sqlThing = sql[0]
  259. sqlParams = sql[1]
  260. reply = get_urls(sqlThing, sqlParams)
  261.  
  262. # Create and send the reply
  263. if reply:
  264. comment.reply(reply)
  265. with open('goalComments.txt', 'a+') as outfile:
  266. outfile.write(comment.id + '\n')
  267.  
  268. print("Sleep for 10...")
  269. time.sleep(10)
  270. # If the reply comes back with no results. Let individual know
  271. else:
  272. reply = 'Clip not found. Only 2018/19 clips are currently available. Feel free to [post a question in the help thread.](https://www.reddit.com/r/juve_goal_bot/comments/9qpxjh/juve_goal_bot_questionsbug_reports)'
  273. comment.reply(reply)
  274. with open('goalComments.txt', 'a+') as outfile:
  275. outfile.write(comment.id + '\n')
  276.  
  277. print("Sleep for 10...")
  278. time.sleep(10)
  279. else:
  280. # print out when comment was already addressed
  281. print('This clip has already been requested')
  282.  
  283. # Pull in Gifs of Assists
  284. if "!assist" in body:
  285. print("Juventus assist command")
  286. # store list of existing comments associated with assists
  287. with open('assistComments.txt', 'r') as outfile:
  288. seen_comments = outfile.read().splitlines()
  289. print(comment.id)
  290. # See if the comment in the subreddit has not already been answered.
  291. if comment.id not in seen_comments:
  292.  
  293. body = comment.body.lower()
  294. query = parse_body_assist(body)
  295. sql = get_assist_items(query)
  296. # If a query the individual tried to use is not in the correct format
  297. # mark it as helped and let the individual know where to get help.
  298. if sql is None:
  299. reply = 'It looks like your request is in a format I do not understand. Feel free to [post a question in the help thread.](https://www.reddit.com/r/juve_goal_bot/comments/9qpxjh/juve_goal_bot_questionsbug_reports)'
  300. comment.reply(reply)
  301. with open('assistComments.txt', 'a+') as outfile:
  302. outfile.write(comment.id + '\n')
  303.  
  304. print("not valid query..")
  305. time.sleep(10)
  306. # If the comment uses the correct format find the results
  307. else:
  308. print("SQL: ", sql)
  309. sqlThing = sql[0]
  310. sqlParams = sql[1]
  311. reply = get_urls(sqlThing, sqlParams)
  312.  
  313. # Create and send the reply
  314. if reply:
  315. comment.reply(reply)
  316. with open('assistComments.txt', 'a+') as outfile:
  317. outfile.write(comment.id + '\n')
  318.  
  319. print("Sleep for 10...")
  320. time.sleep(10)
  321. # If the reply comes back with no results. Let individual know
  322. else:
  323. reply = 'Clip not found. Only 2018/19 clips are currently available. Feel free to [post a question in the help thread.](https://www.reddit.com/r/juve_goal_bot/comments/9qpxjh/juve_goal_bot_questionsbug_reports)'
  324. comment.reply(reply)
  325. with open('assistComments.txt', 'a+') as outfile:
  326. outfile.write(comment.id + '\n')
  327.  
  328. print("Sleep for 10...")
  329. time.sleep(10)
  330. else:
  331. # print out when comment was already addressed
  332. print('This clip has already been requested')
  333. # print("Sleep for 10...")
  334. # time.sleep(10)
  335.  
  336.  
  337. def main():
  338. # Authenticate the user
  339. r = login()
  340. while True:
  341. # When authenticated...run the bot
  342. try:
  343. run(r)
  344. # For session time outs
  345. except prawcore.exceptions.ServerError as http_error:
  346. print(http_error)
  347. print('waiting 1 minute')
  348. time.sleep(60)
  349. except prawcore.exceptions.ResponseException as response_error:
  350. print(response_error)
  351. print('waiting 1 minute')
  352. time.sleep(60)
  353. except prawcore.exceptions.RequestException as request_error:
  354. print(request_error)
  355. print('waiting 1 minute')
  356. time.sleep(60)
  357. except Exception as e:
  358. print('error: {}'.format(e))
  359. print('waiting 1 minute')
  360. time.sleep(60)
  361.  
  362.  
  363. if __name__ == '__main__':
  364. main()
Add Comment
Please, Sign In to add comment