Skip to content

Commit

Permalink
правки
Browse files Browse the repository at this point in the history
  • Loading branch information
HamletSargsyan committed Jul 22, 2024
1 parent bfbe7f6 commit bc6b19b
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 2 deletions.
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]
### Устарело
- Интеграция с сервисом GramAds ([#23](https://github.com/HamletSargsyan/livebot/issues/23)) будет удалена
- Все что связанно с интеграций с сервисом GramAds

### Добавлено
- Кеширование некоторых функций, для увеличения скорости работы с ботом

## [3.6.2] - 2024-07-10

Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ argparse==1.4.0
aiohttp==3.9.5
semver==3.0.2
git+https://github.com/HamletSargsyan/changelog-parser.git#egg=changelog-parser
cachetools==5.4.0
typing_extensions==4.12.2
2 changes: 2 additions & 0 deletions src/base/weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

from helpers.datatypes import WeatherData
from config import OPENWEATHER_API_KEY, weather_region
from helpers.utils import cached


@cached
def get_weather() -> WeatherData:
url = "http://api.openweathermap.org/data/2.5/weather?"

Expand Down
3 changes: 3 additions & 0 deletions src/helpers/advert.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
from typing import Union

from typing_extensions import deprecated
from telebot.types import Message

from config import GRAMADS_TOKEN, logger
Expand All @@ -10,6 +11,7 @@
import aiohttp


@deprecated("Deprecated", category=DeprecationWarning)
async def show_advert(user_id: int):
"""
Undefined = 0,
Expand Down Expand Up @@ -70,6 +72,7 @@ async def show_advert(user_id: int):
# logger.error(response.text)


@deprecated("Deprecated", category=DeprecationWarning)
def send_advert(message: Message, user: Union[UserModel, None] = None):
if message.chat.type != "private":
return
Expand Down
27 changes: 26 additions & 1 deletion src/helpers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
from datetime import datetime, timedelta
import random
import statistics
from typing import NoReturn, Union
from typing import Callable, NoReturn, Union

from cachetools import TTLCache
import requests
from semver import Version
from telebot.types import Message, ReplyParameters, InlineKeyboardButton
Expand Down Expand Up @@ -59,13 +60,32 @@ def log(log_text: str, log_level: str, record: logging.LogRecord) -> None:
logger.log(record.levelno, text)


_cache = TTLCache(100, 18_000) # ttl 5 h (18000 s)


def cached(func: Callable):
def wrapper(*args, **kwargs):
key = (args, frozenset(kwargs.items()))

if key in _cache:
return _cache[key]

result = func(*args, **kwargs)
_cache[key] = result
return result

return wrapper


@cached
def remove_not_allowed_symbols(text: str) -> str:
not_allowed_symbols = ["#", "<", ">", "{", "}", '"', "'", "$", "(", ")", "@"]
cleaned_text = "".join(char for char in text if char not in not_allowed_symbols)

return cleaned_text


@cached
def get_time_difference_string(d: timedelta) -> str:
days = d.days
years, days_in_year = divmod(days, 365)
Expand All @@ -92,6 +112,7 @@ def get_user_tag(user: UserModel):
return f"<a href='tg://user?id={user.id}'>{user.name}</a>"


@cached
def get_item(name: str) -> Union[Item, NoReturn]:
for item in items_list:
item.name = item.name.lower()
Expand All @@ -104,13 +125,15 @@ def get_item(name: str) -> Union[Item, NoReturn]:
raise ItemNotFoundError(f"Item {name} not found")


@cached
def get_item_emoji(item_name: str) -> Union[str, None]:
try:
return get_item(item_name).emoji or ""
except AttributeError:
return ""


@cached
def get_item_count_for_rarity(rarity: ItemRarity) -> int:
if rarity == ItemRarity.COMMON:
quantity = random.randint(5, 20)
Expand Down Expand Up @@ -166,6 +189,7 @@ def get_pager_controllers(name: str, pos: int, user_id: Union[int, str]):
]


@cached
def get_middle_item_price(name: str) -> int:
from database.funcs import database

Expand All @@ -184,6 +208,7 @@ def get_middle_item_price(name: str) -> int:
return int(price)


@cached
def calc_xp_for_level(level: int) -> int:
return 5 * level + 50 * level + 100

Expand Down
2 changes: 2 additions & 0 deletions src/middlewares/advert.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing_extensions import deprecated
import requests
from telebot import BaseMiddleware, CancelUpdate
from telebot.types import Message
Expand All @@ -6,6 +7,7 @@
from database.funcs import database


@deprecated("Deprecated", category=DeprecationWarning)
class AdvertMiddleware(BaseMiddleware):
def __init__(self) -> None:
self.update_types = ["message"]
Expand Down

0 comments on commit bc6b19b

Please sign in to comment.