Skip to content

Commit

Permalink
Merge pull request #85 from HamletSargsyan/dev
Browse files Browse the repository at this point in the history
Release v10.3.0
  • Loading branch information
HamletSargsyan authored Dec 23, 2024
2 parents 58b769e + 361e835 commit ad718ba
Show file tree
Hide file tree
Showing 10 changed files with 93 additions and 27 deletions.
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [10.3.0] - 2024-12-24

### Добавлено

- Новые ачивки

### Исправлено

- Отправка уведомлений для действий
- Баг при покупке предмета из рынка ([#84](https://github.com/HamletSargsyan/livebot/issues/84))

## [10.2.0] - 2024-11-03

### Добавлено
Expand Down
6 changes: 3 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
changelog-parser @ git+https://github.com/HamletSargsyan/changelog-parser@main
pyTelegramBotAPI==4.23.0
pyTelegramBotAPI==4.25.0
pymongo==4.10.1
transliterate==1.10.2
redis==5.2.0
redis==5.2.1
toml==0.10.2
argparse==1.4.0
semver==3.0.2
httpx==0.27.2
httpx==0.28.1
cachetools==5.5.0
dacite==1.8.1
python-dateutil==2.9.0.post0
Expand Down
27 changes: 27 additions & 0 deletions src/base/achievements.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,31 @@
"буст": 2,
},
),
Achievement(
name="кладоискатель",
emoji="🎁",
desc="открой 20 сундуков",
need=20,
reward={
"бокс": 4,
},
),
Achievement(
name="новичок",
emoji="👋",
desc="посети игру каждый день на протяжении первой недели",
need=7,
reward={
"бабло": 5_000,
},
),
Achievement(
name="олд",
emoji="👨‍🦳",
desc="оставайся активным игроком в течение целого года",
need=365,
reward={
"бабло": 20_000,
},
),
]
18 changes: 16 additions & 2 deletions src/base/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def street(call: CallbackQuery, user: UserModel):
increment_achievement_progress(user, "бродяга")

try:
user_notification = database.notifications.get(**{"owner": user._id})
user_notification = database.notifications.get(owner=user._id)
user_notification.walk = False
database.notifications.update(**user_notification.to_dict())
except NoResult:
Expand Down Expand Up @@ -219,7 +219,7 @@ def work(call: CallbackQuery, user: UserModel):
increment_achievement_progress(user, "работяга")

try:
user_notification = database.notifications.get(**{"owner": user._id})
user_notification = database.notifications.get(owner=user._id)
user_notification.work = False
database.notifications.update(**user_notification.to_dict())
except NoResult:
Expand Down Expand Up @@ -257,6 +257,13 @@ def sleep(call: CallbackQuery, user: UserModel):
user.xp += random.uniform(1.5, 2.0)
user.action = None

try:
user_notification = database.notifications.get(owner=user._id)
user_notification.sleep = False
database.notifications.update(**user_notification.to_dict())
except NoResult:
pass

database.users.update(**user.to_dict())
increment_achievement_progress(user, "сонный")

Expand Down Expand Up @@ -303,6 +310,13 @@ def game(call: CallbackQuery, user: UserModel):
user.mood *= 2
user.action = None

try:
user_notification = database.notifications.get(owner=user._id)
user_notification.game = False
database.notifications.update(**user_notification.to_dict())
except NoResult:
pass

database.users.update(**user.to_dict())
increment_achievement_progress(user, "игроман")

Expand Down
14 changes: 6 additions & 8 deletions src/base/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,12 @@ def check_user_stats(user: UserModel, chat_id: Union[str, int, None] = None):


def generate_quest(user: UserModel):
try:
old_quest = database.quests.get(**{"owner": user._id})
database.quests.delete(**old_quest.to_dict())
except NoResult:
pass

allowed_items = []

for item in ITEMS:
Expand All @@ -175,14 +181,6 @@ def generate_quest(user: UserModel):
task_coin = item.task_coin
reward = random.randint(min(task_coin), max(task_coin)) * quantity # pyright: ignore

try:
old_quest = database.quests.get(**{"owner": user._id})
except NoResult:
old_quest = None

if old_quest:
database.quests.delete(**old_quest.to_dict())

quest = QuestModel(
name=item.name,
quantity=quantity,
Expand Down
9 changes: 6 additions & 3 deletions src/handlers/callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
get_item,
get_user_tag,
increment_achievement_progress,
safe,
utcnow,
)

Expand Down Expand Up @@ -489,6 +490,7 @@ def chest_callback(call: CallbackQuery):
user_item = get_or_add_user_item(user, item.name)
user_item.quantity += quantity
database.items.update(**user_item.to_dict())
increment_achievement_progress(user, "сундук-собиратель")
bot.delete_message(call.message.chat.id, call.message.id)
if call.message.reply_to_message:
bot.reply_to(call.message.reply_to_message, mess)
Expand Down Expand Up @@ -654,21 +656,22 @@ def market_callback(call: CallbackQuery):
database.items.update(**user_item.to_dict())
database.users.update(**user.to_dict())
database.users.update(**item_owner.to_dict())
database.market_items.delete(**market_item.to_dict())

increment_achievement_progress(user, "богач", market_item.price)
increment_achievement_progress(item_owner, "продавец")

usage = f" ({int(market_item.usage)}%)" if market_item.usage else ""

mess = f"{get_user_tag(user)} купил {market_item.quantity} {get_item_emoji(market_item.name)}{usage}"
bot.send_message(call.message.chat.id, mess)
safe(bot.send_message, call.message.chat.id, mess)

bot.send_message(
safe(
bot.send_message,
item_owner.id,
f"{get_user_tag(user)} купил у тебя {market_item.quantity} {get_item_emoji(market_item.name)}{usage}",
)

database.market_items.delete(**market_item.to_dict())

mess = "<b>Рынок</b>\n\n"
market_items = database.market_items.get_all()
Expand Down
5 changes: 4 additions & 1 deletion src/handlers/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
get_item,
Loading,
increment_achievement_progress,
safe,
send_channel_subscribe_message,
utcnow,
)
Expand Down Expand Up @@ -112,13 +113,15 @@ def start(message: Message):
database.users.update(**ref_user.to_dict())
increment_achievement_progress(ref_user, "друзья навеки")

bot.send_message(
safe(
bot.send_message,
ref_user.id,
(
f"{user.name} присоединился к игре благодаря твой реферальной ссылке\n"
f"Ты получил {coin} бабла {get_item_emoji('бабло')}"
),
)

return

if message.chat.type != "private":
Expand Down
23 changes: 15 additions & 8 deletions src/helpers/utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from contextlib import suppress
from functools import wraps
import json
import random
import statistics
from typing import (
Any,
Callable,
NoReturn,
Optional,
Expand Down Expand Up @@ -34,15 +36,16 @@
from base.items import ITEMS
from helpers.enums import ItemRarity


T = TypeVar("T")
P = ParamSpec("P")

_deprecated_funcs = set()


def deprecated(
remove_version: Version,
*,
remove_in: Version,
deprecated_in: Version,
message: Optional[str] = None,
warn_once: bool = True,
):
Expand All @@ -52,7 +55,7 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
if warn_once and func.__name__ in _deprecated_funcs:
return func(*args, **kwargs)
_deprecated_funcs.add(func.__name__)
msg = f"функция `{func.__name__}` помечена как устаревшая и будет удалена в версии {remove_version}, (текущая версия: {VERSION})"
msg = f"начиная с версии {deprecated_in} функция `{func.__name__}` помечена как устаревшая и будет удалена в версии {remove_in}, (текущая версия: {VERSION})"

if message:
msg += f" | {message}"
Expand Down Expand Up @@ -273,10 +276,9 @@ def check_version() -> str: # type: ignore


@deprecated(
Version(
12,
),
"Use `message.from_user` instead",
remove_in=Version(major=12),
deprecated_in=Version(major=10),
message="Use `message.from_user` instead",
)
def from_user(message: Message) -> User:
return message.from_user # type: ignore
Expand Down Expand Up @@ -420,7 +422,7 @@ def __init__(

self.title = title
self._mess = f"<b>{self.title}</b>"
self.exit_funcs: set[Callable] = set()
self.exit_funcs: set[Callable[[], None | Any]] = set()

def __enter__(self) -> Self:
self.message = antiflood(bot.reply_to, self.user_message, self._mess)
Expand All @@ -436,3 +438,8 @@ def write(self, new_text: str):
self.message = antiflood(
bot.edit_message_text, text, self.message.chat.id, self.message.id
)


def safe(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> Optional[T]:
with suppress(BaseException):
return func(*args, **kwargs)
5 changes: 4 additions & 1 deletion src/middlewares/actives.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from telebot.types import Message, CallbackQuery

from database.funcs import database
from helpers.utils import utcnow
from helpers.utils import increment_achievement_progress, utcnow


class ActiveMiddleware(BaseMiddleware):
Expand All @@ -19,3 +19,6 @@ def post_process(self, message: Union[Message, CallbackQuery], data, exception):
user = database.users.get(id=user_id)
user.last_active_time = utcnow()
database.users.update(**user.to_dict())

if (utcnow() - user.registered_at).days >= 7:
increment_achievement_progress(user, "новичок")
2 changes: 1 addition & 1 deletion version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
10.2.0
10.3.0

0 comments on commit ad718ba

Please sign in to comment.