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

Feature/python3.12 #71

Merged
merged 3 commits into from
Nov 17, 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
4 changes: 2 additions & 2 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging

from aiogram.client.default import DefaultBotProperties
import config
from aiogram import Bot, Dispatcher
from aiogram.enums import ParseMode
Expand All @@ -10,7 +10,7 @@
from config import TOKEN, WEBHOOK_URL, ADMIN_ID_LIST
from db import create_db_and_tables

bot = Bot(TOKEN, parse_mode=ParseMode.HTML)
bot = Bot(TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
dp = Dispatcher(storage=MemoryStorage())


Expand Down
12 changes: 5 additions & 7 deletions db.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Union

from sqlalchemy import event, Engine, text, create_engine
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from sqlalchemy.orm import sessionmaker, Session
Expand Down Expand Up @@ -46,7 +44,7 @@


@asynccontextmanager
async def get_db_session() -> Union[AsyncSession, Session]:
async def get_db_session() -> AsyncSession | Session:
session = None
try:
if config.DB_ENCRYPTION:
Expand All @@ -64,7 +62,7 @@ async def get_db_session() -> Union[AsyncSession, Session]:
session.close()


async def session_execute(stmt, session: Union[AsyncSession, Session]):
async def session_execute(stmt, session: AsyncSession | Session):
if isinstance(session, AsyncSession):
query_result = await session.execute(stmt)
return query_result
Expand All @@ -73,14 +71,14 @@ async def session_execute(stmt, session: Union[AsyncSession, Session]):
return query_result


async def session_refresh(session: Union[AsyncSession, Session], instance: object) -> None:
async def session_refresh(session: AsyncSession | Session, instance: object) -> None:
if isinstance(session, AsyncSession):
await session.refresh(instance)
else:
session.refresh(instance)


async def session_commit(session: Union[AsyncSession, Session]) -> None:
async def session_commit(session: AsyncSession | Session) -> None:
if isinstance(session, AsyncSession):
await session.commit()
else:
Expand All @@ -94,7 +92,7 @@ def set_sqlite_pragma(dbapi_connection, connection_record):
cursor.close()


async def check_all_tables_exist(session: Union[AsyncSession, Session]):
async def check_all_tables_exist(session: AsyncSession | Session):
for table in Base.metadata.tables.values():
sql_query = f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table.name}';"
if isinstance(session, AsyncSession):
Expand Down
27 changes: 15 additions & 12 deletions handlers/admin/admin.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import asyncio
import inspect
import logging
from typing import Union

from aiogram import types, Router, F
from aiogram.exceptions import TelegramForbiddenError
from aiogram.filters import StateFilter
Expand Down Expand Up @@ -32,7 +30,7 @@
class AdminCallback(CallbackData, prefix="admin"):
level: int
action: str
args_to_action: Union[str, int]
args_to_action: str | int
page: int


Expand Down Expand Up @@ -66,7 +64,7 @@ async def admin_command_handler(message: types.message):
await admin(message)


async def admin(message: Union[Message, CallbackQuery]):
async def admin(message: Message | CallbackQuery):
admin_menu_builder = InlineKeyboardBuilder()
admin_menu_builder.button(text=Localizator.get_text(BotEntity.ADMIN, "announcements"),
callback_data=create_admin_callback(level=1))
Expand Down Expand Up @@ -410,7 +408,8 @@ async def make_refund_markup(page):
text=Localizator.get_text(BotEntity.ADMIN, "refund_by_username").format(
telegram_username=buy.telegram_username,
total_price=buy.total_price,
subcategory=buy.subcategory),
subcategory=buy.subcategory,
currency_sym=Localizator.get_currency_symbol()),
callback_data=create_admin_callback(level=16,
action="make_refund",
args_to_action=buy.buy_id))
Expand All @@ -419,7 +418,8 @@ async def make_refund_markup(page):
text=Localizator.get_text(BotEntity.ADMIN, "refund_by_tgid").format(
telegram_id=buy.telegram_id,
total_price=buy.total_price,
subcategory=buy.subcategory),
subcategory=buy.subcategory,
currency_sym=Localizator.get_currency_symbol()),
callback_data=create_admin_callback(level=16,
action="make_refund",
args_to_action=buy.buy_id))
Expand Down Expand Up @@ -457,15 +457,17 @@ async def refund_confirmation(callback: CallbackQuery):
telegram_username=refund_data.telegram_username,
quantity=refund_data.quantity,
subcategory=refund_data.subcategory,
total_price=refund_data.total_price),
total_price=refund_data.total_price,
currency_sym=Localizator.get_currency_symbol()),
reply_markup=confirmation_builder.as_markup())
else:
await callback.message.edit_text(
text=Localizator.get_text(BotEntity.ADMIN, "refund_confirmation_by_tgid").format(
telegram_id=refund_data.telegram_id,
quantity=refund_data.quantity,
subcategory=refund_data.subcategory,
total_price=refund_data.total_price), reply_markup=confirmation_builder.as_markup())
total_price=refund_data.total_price,
currency_sym=Localizator.get_currency_symbol()), reply_markup=confirmation_builder.as_markup())


async def pick_statistics_entity(callback: CallbackQuery):
Expand Down Expand Up @@ -526,8 +528,9 @@ async def get_statistics(callback: CallbackQuery):
statistics_keyboard_builder.row(
*[AdminConstants.back_to_main_button, await AdminConstants.get_back_button(unpacked_callback)])
await callback.message.edit_text(
text=Localizator.get_text(BotEntity.ADMIN, "new_users_msg").format(users_count=users_count,
timedelta=unpacked_callback.args_to_action),
text=Localizator.get_text(BotEntity.ADMIN, "new_users_msg").format(
users_count=users_count,
timedelta=unpacked_callback.args_to_action),
reply_markup=statistics_keyboard_builder.as_markup())
elif unpacked_callback.action == "buys":
back_button = await AdminConstants.get_back_button(unpacked_callback)
Expand Down Expand Up @@ -606,8 +609,8 @@ async def make_refund(callback: CallbackQuery):
total_price=refund_data.total_price,
telegram_username=refund_data.telegram_username,
quantity=refund_data.quantity,
subcategory=refund_data.subcategory),
currency_sym=Localizator.get_currency_symbol())
subcategory=refund_data.subcategory,
currency_sym=Localizator.get_currency_symbol()))
else:
await callback.message.edit_text(
text=Localizator.get_text(BotEntity.ADMIN, "successfully_refunded_with_tgid").format(
Expand Down
32 changes: 16 additions & 16 deletions handlers/user/all_categories.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Union

from aiogram import types, Router, F
from aiogram.filters.callback_data import CallbackData
from aiogram.types import Message, CallbackQuery
Expand Down Expand Up @@ -81,7 +79,7 @@ async def create_subcategory_buttons(category_id: int, page: int = 0):
return subcategories_builder


async def all_categories(message: Union[Message, CallbackQuery]):
async def all_categories(message: Message | CallbackQuery):
if isinstance(message, Message):
category_inline_buttons = await create_category_buttons(0)
zero_level_callback = create_callback_all_categories(0)
Expand Down Expand Up @@ -146,12 +144,13 @@ async def select_quantity(callback: CallbackQuery):
category = await CategoryService.get_by_primary_key(category_id)
available_qty = await ItemService.get_available_quantity(subcategory_id, category_id)
await callback.message.edit_text(
text=Localizator.get_text(BotEntity.USER, "select_quantity").format(category_name=category.name,
subcategory_name=subcategory.name,
price=price,
description=description,
quantity=available_qty,
currency_sym=Localizator.get_currency_symbol()),
text=Localizator.get_text(BotEntity.USER, "select_quantity").format(
category_name=category.name,
subcategory_name=subcategory.name,
price=price,
description=description,
quantity=available_qty,
currency_sym=Localizator.get_currency_symbol()),
reply_markup=count_builder.as_markup())


Expand Down Expand Up @@ -193,13 +192,14 @@ async def add_to_cart_confirmation(callback: CallbackQuery):
subcategory = await SubcategoryService.get_by_primary_key(subcategory_id)
category = await CategoryService.get_by_primary_key(category_id)
await callback.message.edit_text(
text=Localizator.get_text(BotEntity.USER, "buy_confirmation").format(category_name=category.name,
subcategory_name=subcategory.name,
price=price,
description=description,
quantity=quantity,
total_price=total_price,
currency_sym=Localizator.get_currency_symbol()),
text=Localizator.get_text(BotEntity.USER, "buy_confirmation").format(
category_name=category.name,
subcategory_name=subcategory.name,
price=price,
description=description,
quantity=quantity,
total_price=total_price,
currency_sym=Localizator.get_currency_symbol()),
reply_markup=confirmation_builder.as_markup())


Expand Down
7 changes: 2 additions & 5 deletions handlers/user/cart.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
from typing import Union, List

from typing import List
from aiogram import types, F, Router
from aiogram.enums import ParseMode
from aiogram.filters.callback_data import CallbackData
from aiogram.types import CallbackQuery, Message
from aiogram.utils.keyboard import InlineKeyboardBuilder

import config
from handlers.common.common import add_pagination_buttons
from handlers.user.all_categories import create_callback_all_categories
from models.cartItem import CartItem
Expand Down Expand Up @@ -70,7 +67,7 @@ async def create_cart_item_buttons(telegram_id: int, page: int = 0):
return cart_builder


async def show_cart(message: Union[Message, CallbackQuery]):
async def show_cart(message: Message | CallbackQuery):
telegram_id = message.from_user.id
user = await UserService.get_by_tgid(message.from_user.id)
cart_items = len(await CartItemService.get_all_items_by_user_id(user.id))
Expand Down
9 changes: 3 additions & 6 deletions handlers/user/my_profile.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
from typing import Union

from aiogram import types, Router, F
from aiogram.filters.callback_data import CallbackData
from aiogram.types import CallbackQuery, Message
from aiogram.utils.keyboard import InlineKeyboardBuilder

from crypto_api.CryptoApiManager import CryptoApiManager
from handlers.common.common import add_pagination_buttons
from handlers.user.cart import create_message_with_bought_items
Expand All @@ -23,7 +20,7 @@
class MyProfileCallback(CallbackData, prefix="my_profile"):
level: int
action: str
args_for_action: Union[int, str]
args_for_action: int | str
page: int


Expand Down Expand Up @@ -57,7 +54,7 @@ async def get_my_profile_message(telegram_id: int):
currency_sym=Localizator.get_currency_symbol())


async def my_profile(message: Union[Message, CallbackQuery]):
async def my_profile(message: Message | CallbackQuery):
current_level = 0
top_up_button = types.InlineKeyboardButton(
text=Localizator.get_text(BotEntity.USER, "top_up_balance_button"),
Expand Down Expand Up @@ -107,7 +104,7 @@ async def top_up_balance(callback: CallbackQuery):
top_up_methods_builder.button(text=Localizator.get_text(BotEntity.USER, "usdt_erc20_top_up"),
callback_data=create_callback_profile(current_level + 1,
args_for_action="ETH_USDT"))
top_up_methods_builder.button(text=Localizator.get_text(BotEntity.USER, "usdc_trc20_top_up"),
top_up_methods_builder.button(text=Localizator.get_text(BotEntity.USER, "usdc_erc20_top_up"),
callback_data=create_callback_profile(current_level + 1,
args_for_action="ETH_USDC"))
top_up_methods_builder.row(back_to_profile_button)
Expand Down
2 changes: 1 addition & 1 deletion l10n/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@
"subcategories": "📦 <b>Unterkategorien:</b>",
"top_up_balance_button": "➕ Guthaben aufladen",
"top_up_balance_msg": "💵 <b>Zahlen Sie den Betrag, den Sie aufladen möchten, an die Adresse von {bot_name}</b> \n\n<b>Wichtig</b>\n<i>Für jeden Benutzer wird eine eindeutige BTC/LTC/SOL/ETH/TRX-Adresse vergeben.\nDie Aufladung erfolgt innerhalb von 5 Minuten nach der Überweisung.\n\nNach einer erfolgreichen Guthabenaktualisierung muss sich das Guthaben in Ihrem Profil ändern.</i>\n\n<b>ACHTUNG!\nKlicken Sie auf „Guthaben aktualisieren“ ERST NACHDEM IHRE TRANSAKTION <u>MINDESTENS EINE BESTÄTIGUNG</u> IN DER BLOCKCHAIN HAT.</b>\n\n<b>Ihre {crypto_name}-Adresse\n</b><code>{addr}</code>",
"usdc_trc20_top_up": "USDC TRC-20",
"usdc_erc20_top_up": "USDC ERC-20",
"usdt_erc20_top_up": "USDT ERC-20",
"usdt_trc20_top_up": "USDT TRC-20"
}
Expand Down
10 changes: 5 additions & 5 deletions l10n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,14 @@
"notification_seed": "🔑 Seed: <code>{seed}</code>",
"pick_statistics_entity": "📊 Pick statistics entity",
"refund_by_tgid": "🆔 ID:{telegram_id}|{currency_sym}{total_price}|{subcategory}",
"refund_by_username": "👤 @{telegram_username}|{currency_sym}{total_price}|{subcategory}",
"refund_confirmation_by_tgid": "❓ <b>Do you really want to refund user with ID:{telegram_id}\nfor purchasing {quantity} {subcategory}\nin the amount of {currency_sym}{total_price}</b>",
"refund_confirmation_by_username": "❓ <b>Do you really want to refund user @{telegram_username}\nfor purchasing {quantity} {subcategory}\nin the amount of {currency_sym}{total_price}</b>",
"refund_by_username": "👤 @{telegram_username}|{currency_sym}{total_price:.2f}|{subcategory}",
"refund_confirmation_by_tgid": "❓ <b>Do you really want to refund user with ID:{telegram_id}\nfor purchasing {quantity} {subcategory}\nin the amount of {currency_sym}{total_price:.2f}</b>",
"refund_confirmation_by_username": "❓ <b>Do you really want to refund user @{telegram_username}\nfor purchasing {quantity} {subcategory}\nin the amount of {currency_sym}{total_price:.2f}</b>",
"refund_menu": "↩️ <b>Refund menu:</b>",
"restocking": "🔄 Restocking Message",
"restocking_message_category": "\n📦 {category}\n",
"restocking_message_header": "🆕 New Stock Alert! 🆕\n",
"sales_statistics": "📊 <b>Sales statistics for the last {timedelta} days.\n\uD83D\uDCB0 Total profit: {currency_sym}{total_profit}\n\uD83D\uDECD\uFE0F Items sold: {items_sold}\n\uD83D\uDCBC Total buys: {buys_count}</b>",
"sales_statistics": "📊 <b>Sales statistics for the last {timedelta} days.\n\uD83D\uDCB0 Total profit: {currency_sym}{total_profit:.2f}\n\uD83D\uDECD\uFE0F Items sold: {items_sold}\n\uD83D\uDCBC Total buys: {buys_count}</b>",
"send_everyone": "📢 Send to Everyone",
"sending_result": "✅ <b>Message sent to {counter} out of {len} active users.\nTotal users:{users_count}</b>",
"sending_started": "🚀 Sending started",
Expand Down Expand Up @@ -135,7 +135,7 @@
"subcategories": "📦 <b>Subcategories:</b>",
"top_up_balance_button": "➕ Top Up Balance",
"top_up_balance_msg": "💵 <b>Deposit to the address the amount you want to top up the {bot_name}</b> \n\n<b>Important</b>\n<i>A unique BTC/LTC/SOL/ETH/TRX addresses is given for each user\nThe top up takes place within 5 minutes after the transfer.\n\nAfter a successful balance refresh, the balance must change in your profile.</i>\n\n<b>ATTENTION!\nCLICK “Refresh balance” ONLY AFTER YOUR TRANSACTION HAS <u>AT LEAST ONE CONFIRMATION</u> ON THE BLOCKCHAIN.</b>\n\n<b>Your {crypto_name} address\n</b><code>{addr}</code>",
"usdc_trc20_top_up": "USDC TRC-20",
"usdc_erc20_top_up": "USDC ERC-20",
"usdt_erc20_top_up": "USDT ERC-20",
"usdt_trc20_top_up": "USDT TRC-20",
"checkout": "\uD83D\uDECD\uFE0F Checkout",
Expand Down
8 changes: 2 additions & 6 deletions multibot.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import logging
import sys
from typing import Any, Dict, Union

from typing import Any, Dict
from aiohttp import web

import config

from aiogram import Bot, Dispatcher, F, Router
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.enums import ParseMode
Expand All @@ -19,7 +16,6 @@
TokenBasedRequestHandler,
setup_application,
)

from db import create_db_and_tables
from utils.custom_filters import AdminIdFilter

Expand All @@ -36,7 +32,7 @@
OTHER_BOTS_URL = f"{BASE_URL}{OTHER_BOTS_PATH}"


def is_bot_token(value: str) -> Union[bool, Dict[str, Any]]:
def is_bot_token(value: str) -> bool | Dict[str, Any]:
try:
validate_token(value)
except TokenValidationError:
Expand Down
Binary file modified requirements.txt
Binary file not shown.
2 changes: 2 additions & 0 deletions run.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# grequests monkey patching, more info at https://github.com/gevent/gevent/issues/1016
import grequests
from aiogram import types, F, Router
from aiogram.filters import Command
from aiogram.utils.keyboard import InlineKeyboardBuilder
Expand Down
Loading