فهرست منبع

Working on account retrieving

JoostSijm 5 سال پیش
والد
کامیت
6b85b21d13
7فایلهای تغییر یافته به همراه137 افزوده شده و 63 حذف شده
  1. 1 1
      app/__init__.py
  2. 7 55
      app/__main__.py
  3. 46 0
      app/api.py
  4. 50 0
      app/commands.py
  5. 12 5
      app/conversations/add_account.py
  6. 12 2
      app/database.py
  7. 9 0
      app/functions.py

+ 1 - 1
app/__init__.py

@@ -50,7 +50,7 @@ SCHEDULER = BackgroundScheduler(
 SCHEDULER.start()
 SCHEDULER.start()
 
 
 TELEGRAM_KEY = os.environ['TELEGRAM_KEY']
 TELEGRAM_KEY = os.environ['TELEGRAM_KEY']
-BOT = telegram.Bot(token=TELEGRAM_KEY)
+# BOT = telegram.Bot(token=TELEGRAM_KEY)
 UPDATER = Updater(TELEGRAM_KEY, use_context=True)
 UPDATER = Updater(TELEGRAM_KEY, use_context=True)
 
 
 # api
 # api

+ 7 - 55
app/__main__.py

@@ -1,69 +1,21 @@
 """Telegram bot"""
 """Telegram bot"""
 
 
-import re
+from telegram.ext import CommandHandler
 
 
-from telegram import ParseMode
-from telegram.ext import MessageHandler, CommandHandler, Filters, ConversationHandler, RegexHandler
-
-from app import LOGGER, BOT, UPDATER
-
-from app import database
+from app import LOGGER, UPDATER, commands
 from app.conversations.add_account import ADD_ACCOUNT_CONV
 from app.conversations.add_account import ADD_ACCOUNT_CONV
 
 
 
 
-def cmd_start(update, context):
-    """Start command"""
-    update.message.reply_text(
-        'Hello {},\ntype /help for a list of commands'.format(update.message.from_user.first_name))
-
-def cmd_help(update, context):
-    """Help command"""
-    message_list = [
-        '**Command list**',
-        '/accounts - list of accounts',
-        '/add\\_account - add account to list',
-    ]
-    message = '\n'.join(message_list)
-    print(message)
-    update.message.reply_text(message, parse_mode=ParseMode.MARKDOWN)
-
-def cmd_accounts(update, context):
-    """Return account list"""
-    accounts = database.get_rr_accounts(update.message.from_user.id)
-    message_list = ['Accounts verified to this Telgeram account:']
-    for account in accounts:
-        # name = re.sub(r'\[.*\]\s', '', account.name)
-        desktop_link = '[desktop](https://rivalregions.com/#slide/profile/{})'.format(account.id)
-        mobile_link = '[mobile](https://m.rivalregions.com/#slide/profile/{})'.format(account.id)
-        message_list.append(
-            '• {} {} - {}'.format(
-                escape_text(account.name),
-                desktop_link,
-                mobile_link,
-            )
-        )
-    message = '\n'.join(message_list)
-    update.message.reply_text(message, parse_mode=ParseMode.MARKDOWN)
-
-def escape_text(text):
-    """Escape text"""
-    return text \
-        .replace("_", "\\_") \
-        .replace("*", "\\*") \
-        .replace("[", "\\[") \
-        .replace("`", "\\`")
-
 def main():
 def main():
     """Main function"""
     """Main function"""
     dispatcher = UPDATER.dispatcher
     dispatcher = UPDATER.dispatcher
 
 
-    # general commands
-    dispatcher.add_handler(CommandHandler('start', cmd_start))
-    dispatcher.add_handler(CommandHandler('help', cmd_help))
-
-    # account commaonds
-    dispatcher.add_handler(CommandHandler('accounts', cmd_accounts))
+    # commands
+    dispatcher.add_handler(CommandHandler('start', commands.cmd_start))
+    dispatcher.add_handler(CommandHandler('help', commands.cmd_help))
+    dispatcher.add_handler(CommandHandler('accounts', commands.cmd_accounts))
 
 
+    # conversations
     dispatcher.add_handler(ADD_ACCOUNT_CONV)
     dispatcher.add_handler(ADD_ACCOUNT_CONV)
 
 
     UPDATER.start_polling()
     UPDATER.start_polling()

+ 46 - 0
app/api.py

@@ -0,0 +1,46 @@
+"""PACC API functions"""
+
+import re
+
+import requests
+from bs4 import BeautifulSoup
+from dateutil import parser
+
+from app import BASE_URL, HEADERS
+
+
+def get_rr_account(account_id):
+    """Get Rival Region account"""
+    response = requests.get(
+        '{}slide/profile/{}'.format(BASE_URL, account_id),
+        headers=HEADERS
+    )
+    soup = BeautifulSoup(response.text, 'html.parser')
+    account = {
+        'name': None,
+        'region': None,
+        'residency': None,
+        'registation_date': None,
+    }
+    table = soup.find('table')
+    name = soup.find('h1')
+    if name:
+        account['name'] = re.sub(r'.*:\s', '', name.text)
+        print(account['name'])
+    for row in table.find_all('tr'):
+        label = row.find('td').text.strip() 
+        if label == 'Region:':
+            span = row.find('span', {'class': 'dot'})
+            if span:
+                account['region'] = span.text
+        if label == 'Residency:':
+            span = row.find('span', {'class': 'dot'})
+            if span:
+                account['residency'] = span.text
+        if label == 'Registration date:':
+            element = row.find('td', {'class': 'imp'})
+            if element:
+                account['registation_date'] = parser.parse(element.text)
+    # print(region)
+
+    return account

+ 50 - 0
app/commands.py

@@ -0,0 +1,50 @@
+"""Telegram commands"""
+
+from telegram import ParseMode
+
+
+from app import database, functions
+from app.models import TelegramAccount
+
+
+def cmd_start(update, context):
+    """Start command"""
+    update.message.reply_text(
+        'Hello {},\ntype /help for a list of commands'.format(update.message.from_user.first_name))
+    telegram_account = database.get_telegram_account(update.message.from_user.id)
+    if not telegram_account:
+        database.add_telegram_account(update)
+
+
+def cmd_help(update, context):
+    """Help command"""
+    message_list = [
+        '**Command list**',
+        '/accounts - list of accounts',
+        '/add\\_account - add account to list',
+    ]
+    message = '\n'.join(message_list)
+    update.message.reply_text(message, parse_mode=ParseMode.MARKDOWN)
+
+def cmd_accounts(update, context):
+    """Return account list"""
+    message_list = ['Accounts verified to this Telgeram account:']
+    telegram_account = database.get_telegram_account(update.message.from_user.id)
+    if telegram_account:
+        accounts = database.get_rr_accounts(telegram_account)
+    else:
+        accounts = []
+    if not accounts:
+        message_list.append('• none')
+    for account in accounts:
+        desktop_link = '[desktop](https://rivalregions.com/#slide/profile/{})'.format(account.id)
+        mobile_link = '[mobile](https://m.rivalregions.com/#slide/profile/{})'.format(account.id)
+        message_list.append(
+            '• {} {} - {}'.format(
+                functions.escape_text(account.name),
+                desktop_link,
+                mobile_link,
+            )
+        )
+    message = '\n'.join(message_list)
+    update.message.reply_text(message, parse_mode=ParseMode.MARKDOWN)

+ 12 - 5
app/conversations/add_account.py

@@ -3,6 +3,7 @@
 from telegram import ParseMode
 from telegram import ParseMode
 from telegram.ext import MessageHandler, CommandHandler, Filters, ConversationHandler, RegexHandler
 from telegram.ext import MessageHandler, CommandHandler, Filters, ConversationHandler, RegexHandler
 
 
+from app import api, functions
 
 
 ACCOUNT_ID, CONFIRM, VERIFICATION = range(3)
 ACCOUNT_ID, CONFIRM, VERIFICATION = range(3)
 
 
@@ -23,14 +24,20 @@ def conv_error_ask_account_id(update, context):
 
 
 def conv_account_id_confirm(update, context):
 def conv_account_id_confirm(update, context):
     """Sending announcement"""
     """Sending announcement"""
+    update.message.reply_text(
+        'Retreiving account from Rival Regions, this might take a couple seconds.'
+    )
     account_id = update.message.text
     account_id = update.message.text
+    # account = api.get_rr_account(2000326045)
+    account = api.get_rr_account(account_id)
 
 
     message_list = [
     message_list = [
-        '**Account details**',
-        'ID: {}'.format(account_id),
-        'Name: {}'.format(account_id),
-        'Region: {}'.format(account_id),
-        'Residency: {}'.format(account_id),
+        '*Account details*',
+        '*ID*: {}'.format(account_id),
+        '*Name*: {}'.format(functions.escape_text(account['name'])),
+        '*Region*: {}'.format(account['region']),
+        '*Residency*: {}'.format(account['residency']),
+        '*Registration date*: {}'.format(account['registation_date']),
         '\nPlease confirm this is your account by typing \'confirm\'',
         '\nPlease confirm this is your account by typing \'confirm\'',
     ]
     ]
 
 

+ 12 - 2
app/database.py

@@ -4,6 +4,17 @@ from app import SESSION
 from app.models import Player, TelegramAccount, TelegramHandle, PlayerTelegram, TelegramVerification
 from app.models import Player, TelegramAccount, TelegramHandle, PlayerTelegram, TelegramVerification
 
 
 
 
+def add_telegram_account(update):
+    """Add new Telegram account"""
+    session = SESSION()
+    telegram_account = TelegramAccount()
+    telegram_account.id = update.message.from_user.id
+    telegram_account.name = update.message.from_user.name
+    session.add(telegram_account)
+    session.commit()
+    session.close()
+    return telegram_account
+
 def get_telegram_account(telegram_id):
 def get_telegram_account(telegram_id):
     """Get Telegram account"""
     """Get Telegram account"""
     session = SESSION()
     session = SESSION()
@@ -15,10 +26,9 @@ def _get_telegram_account(session, telegram_id):
     """Return telegram_account"""
     """Return telegram_account"""
     return session.query(TelegramAccount).get(telegram_id)
     return session.query(TelegramAccount).get(telegram_id)
 
 
-def get_rr_accounts(telegram_id):
+def get_rr_accounts(telegram_account):
     """Get Rival Region accounts associated with Telegram account"""
     """Get Rival Region accounts associated with Telegram account"""
     session = SESSION()
     session = SESSION()
-    telegram_account = _get_telegram_account(session, telegram_id)
     rr_accounts = session.query(Player) \
     rr_accounts = session.query(Player) \
         .join(Player.player_telegram) \
         .join(Player.player_telegram) \
         .filter(PlayerTelegram.telegram_id == telegram_account.id) \
         .filter(PlayerTelegram.telegram_id == telegram_account.id) \

+ 9 - 0
app/functions.py

@@ -0,0 +1,9 @@
+"""General function"""
+
+def escape_text(text):
+    """Escape text"""
+    return text \
+        .replace("_", "\\_") \
+        .replace("*", "\\*") \
+        .replace("[", "\\[") \
+        .replace("`", "\\`")