model.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import psycopg
  2. import re
  3. from pprint import pprint
  4. def get_events():
  5. """Simply retrieve events"""
  6. query = """SELECT * FROM
  7. (SELECT hash, timestamp, news, faction, faction_id
  8. FROM events
  9. WHERE (timestamp BETWEEN now() - INTERVAL '24 HOURS' AND now())
  10. AND (news LIKE '% has applied to join the faction.'
  11. OR news LIKE '% left the faction%'
  12. OR news LIKE '% has accepted %'
  13. OR news LIKE '% has declined %'
  14. OR news LIKE '% was kicked out of the faction %')
  15. ORDER BY timestamp DESC) tmp
  16. ORDER BY timestamp;"""
  17. return query
  18. def database_select(cur, query, debug=True):
  19. results = None
  20. try:
  21. cur.execute(query)
  22. results = cur.fetchall()
  23. if debug:
  24. pprint(results)
  25. except (Exception, psycopg.Error) as error:
  26. print(cur.mogrify(query))
  27. print("database_select():")
  28. print("PostgreSQL error from psycopg2:", error)
  29. return results
  30. def database_insert(cur, query, debug=True):
  31. try:
  32. cur.execute(query)
  33. except (Exception, psycopg.Error) as error:
  34. print(cur.mogrify(query))
  35. print("database_insert:")
  36. print("PostgreSQL error from psycopg2:", error)
  37. def create_links(news_string):
  38. regex = re.compile(r'<a href = "?https?://www\.torn\.com/profiles\.php\?XID=(\d+)"?>([^<]+)</a>')
  39. return_string = re.sub(regex, r'[\2 [\1]](<https://www.torn.com/profiles.php?XID=\1>)', news_string)
  40. return return_string
  41. def escape_markdown(news_string):
  42. regex_underscore = re.compile(r'_.+_')
  43. regex_star = re.compile(r'\*.+\*')
  44. regex_tilde = re.compile(r'~.+~')
  45. boolean = re.search(regex_underscore, news_string) or \
  46. re.search(regex_star, news_string) or \
  47. re.search(regex_tilde, news_string)
  48. if boolean:
  49. news_string = news_string.translate(str.maketrans({'_': '\_', '*': '\*', '~': '\~'}))
  50. return news_string
  51. def is_broadcast(cur, this_id):
  52. query = f"""SELECT COUNT(*) FROM human_resource WHERE event = '{this_id}';"""
  53. res = database_select(cur, query)
  54. # pprint(res)
  55. boolean = True if res[0][0] == 1 else False
  56. return boolean
  57. def record_broadcast(cur, event_id):
  58. query = f"""INSERT INTO human_resource(event) VALUES('{event_id}');"""
  59. database_insert(cur, query)