Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Advert #27

Merged
merged 5 commits into from
Jun 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Добавлено
- Добавлена новая библиотека: `argparse`
- Добавлена команда `/daily_gift` ([#20](https://github.com/HamletSargsyan/livebot/issues/20))
- Добавлена интеграция с сервисом GramAds ([#23](https://github.com/HamletSargsyan/livebot/issues/23))

### Изменено
- Рефакторинг главного файла (`main.py`)
Expand Down
1 change: 1 addition & 0 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
REDIS_URL = os.getenv("REDIS_URL", "")
DB_NAME = os.getenv("DB_NAME", "livebot")
OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API", "")
GRAMADS_TOKEN = os.getenv("GRAMADS_TOKEN", "")

if not TOKEN:
raise ValueError
Expand Down
2 changes: 2 additions & 0 deletions src/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,8 @@ class UserModel(BaseModel):
new_quest_coin_quantity = Field(int, default=2)
max_items_count_in_market = Field(int, default=4)
luck = Field(int, default=1)
last_advert_time = Field(datetime, nullable=True)
adverts_count = Field(int, default=0)

def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
Expand Down
64 changes: 64 additions & 0 deletions src/helpers/advert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from typing import Union
import requests
from datetime import datetime, timedelta

from telebot.types import Message

from config import GRAMADS_TOKEN, logger
from database.models import UserModel
from database.funcs import database


def show_advert(user: UserModel):
"""
Undefined = 0,
Success = 1,
RevokedTokenError = 2,
UserForbiddenError = 3,
ToManyRequestsError = 4,
OtherBotApiError = 5,
OtherError = 6,

AdLimited = 7,
NoAds = 8,
BotIsNotEnabled=9,
Banned=10,
InReview=11
"""
headers = {
"Authorization": f"Bearer {GRAMADS_TOKEN}",
"Content-Type": "application/json",
}
json = {"SendToChatId": user.id}

logger.debug(f"Send advert to user `{user.id}`")
response = requests.post(
"https://api.gramads.net/ad/SendPost", headers=headers, json=json
)

logger.debug(response.text)

if response.status_code == 200 and response.json()["SendPostResult"] == 1:
user.last_advert_time = datetime.utcnow()
user.adverts_count += 1
database.users.update(**user.to_dict())
else:
try:
logger.error(response.json())
except Exception:
logger.error(response.text)


def send_advert(message: Message, user: Union[UserModel, None] = None):
if message.chat.type != "private":
return

if not user:
user = database.users.get(id=message.from_user.id)

if not user.last_advert_time:
show_advert(user)
return

if user.last_advert_time > datetime.utcnow() + timedelta(minutes=5):
show_advert(user)
5 changes: 3 additions & 2 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from threads.check import check
from config import bot, event_open, logger
from threads.notification import notification
from middlewares.register import RegisterMiddleware
from middlewares import middlewares


def configure_bot_commands():
Expand Down Expand Up @@ -40,7 +40,8 @@ def configure_bot_commands():


def init_middlewares():
bot.setup_middleware(RegisterMiddleware())
for middleware in middlewares:
bot.setup_middleware(middleware())


def start_threads():
Expand Down
10 changes: 10 additions & 0 deletions src/middlewares/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from typing import Type
from telebot.handler_backends import BaseMiddleware

from .register import RegisterMiddleware
from .advert import AdvertMiddleware


middlewares: list[Type[BaseMiddleware]] = [RegisterMiddleware, AdvertMiddleware]

__all__ = ["middlewares"]
22 changes: 22 additions & 0 deletions src/middlewares/advert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import requests
from telebot import BaseMiddleware, CancelUpdate
from telebot.types import Message

from helpers.advert import send_advert
from database.funcs import database


class AdvertMiddleware(BaseMiddleware):
def __init__(self) -> None:
self.update_types = ["message"]

def pre_process(self, message: Message, data):
if message.from_user.is_bot:
return CancelUpdate()

def post_process(self, message, data, exception):
user = database.users.get(id=message.from_user.id)
try:
send_advert(message, user)
except requests.exceptions.JSONDecodeError as e:
raise Exception(f"Cant send advert to `{user.id}`") from e
13 changes: 6 additions & 7 deletions src/threads/notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,12 @@ def notification():
try:
user_notification = database.notifications.get(owner=user._id)
except NoResult:
user_notification = NotificationModel(
owner=user._id
)
id = database.notifications.add(**user_notification.to_dict()).inserted_id
user_notification = NotificationModel(owner=user._id)
id = database.notifications.add(
**user_notification.to_dict()
).inserted_id
user_notification._id = id



user = database.users.get(_id=user._id)
try:
current_time = datetime.utcnow()
Expand All @@ -45,7 +44,7 @@ def notification():
{"Дом": {"callback_data": f"open home {user.id}"}}
)
antiflood(bot.send_message, user.id, mess, reply_markup=markup)

except ApiTelegramException:
continue

Expand Down