api.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """PACC API functions"""
  2. import re
  3. import requests
  4. from bs4 import BeautifulSoup
  5. from dateutil import parser
  6. from app import BASE_URL, HEADERS, LOGGER
  7. class PlayerNotFoundException(Exception):
  8. """RR exception"""
  9. def __init__(self, *args, **kwargs):
  10. Exception.__init__(self, *args, **kwargs)
  11. LOGGER.warning('PlayerNotFoundException')
  12. def get_rr_player(player_id):
  13. """Get Rival Region player"""
  14. response = requests.get(
  15. '{}slide/profile/{}'.format(BASE_URL, player_id),
  16. headers=HEADERS
  17. )
  18. soup = BeautifulSoup(response.text, 'html.parser')
  19. player = {
  20. 'id': player_id,
  21. 'name': None,
  22. 'region': None,
  23. 'residency': None,
  24. 'registation_date': None,
  25. }
  26. table = soup.find('table')
  27. if table is None:
  28. raise PlayerNotFoundException('Player {} not found'.format(player_id))
  29. name = soup.find('h1')
  30. if name:
  31. player['name'] = re.sub(r'.*:\s', '', name.text)
  32. for row in table.find_all('tr'):
  33. label = row.find('td').text.strip()
  34. if label == 'Region:':
  35. span = row.find('span', {'class': 'dot'})
  36. if span:
  37. player['region'] = span.text
  38. if label == 'Residency:':
  39. span = row.find('span', {'class': 'dot'})
  40. if span:
  41. player['residency'] = span.text
  42. if label == 'Registration date:':
  43. element = row.find('td', {'class': 'imp'})
  44. if element:
  45. player['registation_date'] = parser.parse(element.text)
  46. return player
  47. def get_players_by_name(player_name):
  48. """Get player list by name"""
  49. response = requests.get(
  50. '{}listed/region/0/{}/0'.format(BASE_URL, player_name),
  51. headers=HEADERS,
  52. )
  53. soup = BeautifulSoup(response.text, 'html.parser')
  54. players = []
  55. player_items = soup.find_all('tr', {'class': 'list_link'})
  56. for player_item in player_items:
  57. players.append({
  58. 'id': int(player_item.get('user')),
  59. 'name': player_item.find('td', {'class': 'list_name'}).text.strip(),
  60. 'level': int(player_item.find('td', {'class': 'list_level'}).text),
  61. })
  62. return players
  63. def send_personal_message(user_id, message):
  64. """Send personal message to player"""
  65. requests.post(
  66. '{}send_personal_message/{}'.format(BASE_URL, user_id),
  67. headers=HEADERS,
  68. data={
  69. 'message': message
  70. }
  71. )