JoostSijm 4 лет назад
Родитель
Сommit
8d3e79a5a9

+ 4 - 4
Pipfile.lock

@@ -190,7 +190,7 @@
         "rival-regions-wrapper": {
             "editable": true,
             "git": "https://github.com/jjoo914/rival_regions_wrapper",
-            "ref": "26e2a6bc7f2a9bc37bba81cf93b314b3a19ff20d"
+            "ref": "0fe85ed08017efb0947e9b9b505f57f8e8d9ba34"
         },
         "selenium": {
             "hashes": [
@@ -284,11 +284,11 @@
         },
         "more-itertools": {
             "hashes": [
-                "sha256:558bb897a2232f5e4f8e2399089e35aecb746e1f9191b6584a151647e89267be",
-                "sha256:7818f596b1e87be009031c7653d01acc46ed422e6656b394b0f765ce66ed4982"
+                "sha256:68c70cc7167bdf5c7c9d8f6954a7837089c6a36bf565383919bb595efb8a17e5",
+                "sha256:b78134b2063dd214000685165d81c154522c3ee0a1c0d4d113c80361c234c5a2"
             ],
             "markers": "python_version >= '3.5'",
-            "version": "==8.3.0"
+            "version": "==8.4.0"
         },
         "multidict": {
             "hashes": [

+ 5 - 1
src/vboo_info_bot/api.py

@@ -1,10 +1,14 @@
 """API function"""
 
 
-from rival_regions_wrapper.api_wrapper import Article
+from rival_regions_wrapper.api_wrapper import Article, War
 
 from vboo_info_bot import API_WRAPPER
 
 def get_article(article_id):
     """Get article by id"""
     return Article(API_WRAPPER).info(article_id)
+
+def get_war(war_id):
+    """Get war by id"""
+    return War(API_WRAPPER).info(war_id)

+ 61 - 0
src/vboo_info_bot/functions.py

@@ -29,3 +29,64 @@ def telegram_format_article(article):
         article_content,
     )
     return formatted_article
+
+def abbreviate(string, max_lenght):
+    """Abriviate string to only first letters"""
+    if len(string) <= max_lenght:
+        return string
+    abbreviation = ''
+    for word in string.split(' '):
+        abbreviation += word[0:1].upper()
+    return abbreviation
+
+def format_state_region(side):
+    """Format state and region name"""
+    state = '*[{}](https://m.rivalregions.com/#state/details/{})*'.format(
+        abbreviate(side['state_name'], 4),
+        side['state_id'],
+    )
+    region = '[{}](http://m.rivalregions.com/#map/details/{})'.format(
+        side['region_name'],
+        side['region_id'],
+    )
+    return '{} {}'.format(state, region)
+
+def roundk(integer):
+    """Round down number"""
+    thousand = 1
+    while integer >= 999:
+        thousand += 1
+        decimal = str(integer)[-3:-2]
+        integer = int(str(integer)[:-3])
+    return '{}\\.{}{}'.format(integer, decimal, 'k' * thousand)
+
+
+def telegram_format_war(war):
+    """Format war object for article"""
+    if 'region_name' in war['attack']:
+        title = '{} vs {}'.format(
+            format_state_region(war['attack']),
+            format_state_region(war['defend'])
+        )
+    else:
+        title = '{} vs {}'.format(
+            '*{}*'.format(war['type']),
+            format_state_region(war['defend'])
+        )
+    damage = '{} *vs* {} \\= {}'.format(
+        roundk(war['attack']['damage']),
+        roundk(war['defend']['damage']),
+        roundk(war['damage']),
+    )
+
+    link = '[mobile](https://m.rivalregions.com/#war/details/{}) \\| [desktop](http://rivalregions.com/#war/details/{})'.format(
+        war['war_id'],
+        war['war_id'],
+    )
+
+    formatted_war = '{}\n{}\n{}'.format(
+        title,
+        damage,
+        link,
+    )
+    return formatted_war

+ 5 - 0
src/vboo_info_bot/telegram_bot.py

@@ -29,6 +29,11 @@ def text_handler(update, context):
                 article = api.get_article(article_id)
                 formatted_article = functions.telegram_format_article(article)
                 update.message.reply_text(formatted_article, parse_mode=ParseMode.MARKDOWN_V2)
+            elif 'war/details/' in url.fragment:
+                war_id = url.fragment.replace('war/details', '')
+                war = api.get_war(war_id)
+                formatted_war = functions.telegram_format_war(war)
+                update.message.reply_text(formatted_war, parse_mode=ParseMode.MARKDOWN_V2)
 
 
 def run():

+ 20 - 3
tests/conftest.py

@@ -5,12 +5,29 @@ import os
 from rival_regions_wrapper import LocalAuthentication, ApiWrapper
 from dotenv import load_dotenv
 import pytest
+import telegram
 
 
 load_dotenv()
 
-class MissingAuthenticationError(Exception):
-    """Error for missing authentication"""
+class MissingEnvironmentError(Exception):
+    """Error for missing environment variable"""
+
+@pytest.fixture(scope="module")
+def telegram_channel():
+    """Set up telegram channel"""
+    return os.environ.get('TELEGRAM_CHANNEL', None)
+
+@pytest.fixture(scope="module")
+def telegram_bot():
+    """Set up telegram bot before test"""
+    telegram_key = os.environ.get('TELEGRAM_KEY', None)
+    if None in (telegram_key, telegram_channel):
+        raise MissingEnvironmentError(
+            'Load the following variables in your user environment: '
+            'TELEGRAM_KEY'
+        )
+    return telegram.Bot(token=telegram_key)
 
 
 @pytest.fixture(scope="module")
@@ -20,7 +37,7 @@ def api_wrapper():
     rr_password = os.environ.get('RIVAL_REGIONS_PASSWORD', None)
     rr_login_method = os.environ.get('RIVAL_REGIONS_LOGIN_METHOD', None)
     if None in (rr_username, rr_password, rr_login_method):
-        raise MissingAuthenticationError(
+        raise MissingEnvironmentError(
             'Load the following variables in your user environment: '
             'RIVAL_REGIONS_USERNAME, RIVAL_REGIONS_PASSWORD, RIVAL_REGIONS_LOGIN_METHOD'
         )

+ 24 - 1
tests/test_vboo_info_bot_functions.py

@@ -1,6 +1,7 @@
 """Wrapper test"""
 
-from rival_regions_wrapper.api_wrapper import Article
+from rival_regions_wrapper.api_wrapper import Article, War
+from telegram import ParseMode
 import pytest
 
 from vboo_info_bot import functions
@@ -58,3 +59,25 @@ def test_article_info_two(api_wrapper, article_keys):
     assert isinstance(response['content_html'], str), "Content html should be a string"
     assert isinstance(response['language'], str), "Language should be a string"
     assert isinstance(response['rating'], int), "Rating should be an integer"
+
+@pytest.mark.vcr()
+def test_formatting_war_ground(api_wrapper, telegram_bot, telegram_channel):
+    """Test format war"""
+    war_id = 329541
+    response = War(api_wrapper).info(war_id)
+
+    assert isinstance(response, dict), "The response should be a dict"
+    formatted_war = functions.telegram_format_war(response)
+    if telegram_channel:
+        telegram_bot.sendMessage(telegram_channel, formatted_war, parse_mode=ParseMode.MARKDOWN_V2)
+
+@pytest.mark.vcr()
+def test_formatting_war_coup(api_wrapper, telegram_bot, telegram_channel):
+    """Test format war"""
+    war_id = 329518
+    response = War(api_wrapper).info(war_id)
+
+    assert isinstance(response, dict), "The response should be a dict"
+    formatted_war = functions.telegram_format_war(response)
+    if telegram_channel:
+        telegram_bot.sendMessage(telegram_channel, formatted_war, parse_mode=ParseMode.MARKDOWN_V2)