Skip to content

Commit

Permalink
debug parsing posts and continue subscribe
Browse files Browse the repository at this point in the history
  • Loading branch information
salko-ua committed Jun 2, 2024
1 parent de7c126 commit a29c2ed
Show file tree
Hide file tree
Showing 11 changed files with 426 additions and 407 deletions.
14 changes: 8 additions & 6 deletions control_db/premium_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from aiosqlite import Row
from dateutil.relativedelta import relativedelta
from typing import Optional

from control_db.create_db import BaseDBPart


Expand Down Expand Up @@ -90,8 +90,8 @@ async def delete_premium_user(self, telegram_id):
async def add_premium_user(self, telegram_id):
telegram_id_exists = await (
await self.cur.execute(
"""SELECT COUNT(`telegram_id`) FROM `premium_user` WHERE telegram_id = ? AND is_premium = ?""",
(telegram_id, 1),
"""SELECT COUNT(`telegram_id`) FROM `premium_user` WHERE telegram_id = ?""",
(telegram_id,),
)
).fetchall()

Expand All @@ -115,7 +115,8 @@ async def add_premium_user(self, telegram_id):

if not bool(telegram_id_exists[0][0]):
await self.cur.execute(
"""INSERT INTO premium_user(telegram_id, is_premium, expiration_date, bought_premium, date_purchase) VALUES (?,?,?,?,?)""",
"""INSERT INTO premium_user(telegram_id, is_premium, expiration_date, bought_premium, date_purchase)
VALUES (?,?,?,?,?)""",
(telegram_id, 1, next_month, 1, current_datetime),
)
return await self.base.commit()
Expand All @@ -125,8 +126,9 @@ async def add_premium_user(self, telegram_id):
).strftime("%d.%m.%Y")

await self.cur.execute(
"""UPDATE premium_user SET expiration_date = ?, bought_premium = ?, date_purchase = ? WHERE telegram_id = ?; """,
(continue_data, (bought_premium[0][0] + 1), current_datetime, telegram_id),
"""UPDATE premium_user SET is_premium = ?, expiration_date = ?, bought_premium = ?, date_purchase = ?
WHERE telegram_id = ?; """,
(1, continue_data, (bought_premium[0][0] + 1), current_datetime, telegram_id),
)
return await self.base.commit()

Expand Down
83 changes: 21 additions & 62 deletions handlers/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ async def admin(message: Message):

@router.message(F.text.startswith("add"))
async def add_fucking_stupid_people(message: Message):
if not message.from_user.id in ADMINS:
if message.from_user.id not in ADMINS:
return

db = await Database.setup()
data = (message.text).split()
data = message.text.split()

await db.add_premium_user(data[1])
await db.update_premium_operations(
Expand All @@ -59,7 +59,7 @@ async def add_fucking_stupid_people(message: Message):
transaction_status="Approved",
price=data[2],
)
# [N] NOTIFY ADMINISTARTOR
# [N] NOTIFY ADMINISTRATOR
await bot.send_message(
chat_id=-1001902595324,
message_thread_id=392,
Expand All @@ -76,7 +76,7 @@ async def add_fucking_stupid_people(message: Message):
expiration_date = await db.get_expiration_date(data[1])
await bot.send_message(
chat_id=data[1],
text=f"Дякую за підписку, її продовженно до {expiration_date}",
text=f"Дякую за підписку, її продовження до {expiration_date}",
reply_markup=hide_kb(),
)
return
Expand All @@ -90,7 +90,7 @@ async def add_fucking_stupid_people(message: Message):

@router.message(F.text == "Всі Користувачі 👥")
async def all_people_from_db(message: Message):
if not message.from_user.id in ADMINS:
if message.from_user.id not in ADMINS:
return
await message.delete()

Expand All @@ -110,67 +110,26 @@ async def all_people_from_db(message: Message):
await message.answer_document(file)


@router.message(F.text.startswith("delete"))
async def delete_fucking_stupid_people(message: Message):
if not message.from_user.id in ADMINS:
return

db = await Database.setup()
data = (message.text).split()

try:
await db.delete_premium_user(data[1])
except:
pass

try:
await db.delete_premium_operation(data[1])
except:
pass


@router.message(F.text == "Всі Користувачі 👥")
async def all_people_from_db(message: Message):
if not message.from_user.id in ADMINS:
return
await message.delete()

db = await Database.setup()
all_users = await db.get_all_user()
text = "Всі Користувачі 👥"
for telegram_id, first_name, username, parsing_post, date_join in all_users:
date_join = datetime.strptime(date_join, "%Y-%m-%d %H:%M:%S.%f")
formatted_date = date_join.strftime("%Y-%m-%d %H:%M")
text += f"\nID: {telegram_id}"
text += f"\nІм`я: {first_name}"
text += f"\nПсевдонім: {username}"
text += f"\nСтворив постів: {parsing_post}"
text += f"\nПриєднався: {formatted_date}\n\n"

file = types.BufferedInputFile(file=text.encode(), filename=f"Всі Користувачі.txt")
await message.answer_document(file)


@router.message(F.text == "Всі Кориистувачі 👑")
@router.message(F.text == "Всі Користувачі 👑")
async def all_premium_from_db(message: Message):
if not message.from_user.id in ADMINS:
if message.from_user.id not in ADMINS:
return
await message.delete()

db = await Database.setup()
all_premium = await db.get_all_premium()
text = "Всі користувачі 👑"
for (
telegram_id,
is_premium,
expiration_date,
bought_premium,
date_purchase,
telegram_id,
is_premium,
expiration_date,
bought_premium,
date_purchase,
) in all_premium:
text += f"\nID: {telegram_id}"
text += f"\nПреміум: {'активний' if is_premium else 'не активний'}"
text += f"\nПокупок: {bought_premium}"
text += f"\nКупив\Продовжив: {date_purchase}"
text += f"\nКупив\\Продовжив: {date_purchase}"
text += f"\nДіє до: {expiration_date}\n\n"

file = types.BufferedInputFile(file=text.encode(), filename=f"Користувачі що купували.txt")
Expand All @@ -179,7 +138,7 @@ async def all_premium_from_db(message: Message):

@router.message(F.text == "Користувачі що не мали 👑")
async def people_ex(message: Message):
if not message.from_user.id in ADMINS:
if message.from_user.id not in ADMINS:
return
await message.delete()

Expand All @@ -202,7 +161,7 @@ async def people_ex(message: Message):
@router.message(F.text == "Статистика 📊")
async def stats(message: Message):
await message.delete()
if not message.from_user.id in ADMINS:
if message.from_user.id not in ADMINS:
return

db = await Database.setup()
Expand All @@ -226,24 +185,24 @@ async def stats(message: Message):
f"Статистика по доходу 📊:\n"
f"День:\n"
f"К-ть покупок - {stats_1day['count']}\n"
f"Зароблено грошей - {stats_1day['sum'] if stats_1day['sum'] else zero}\n\n"
f"Зароблено гривень - {stats_1day['sum'] if stats_1day['sum'] else zero}\n\n"
f"Тиждень:\n"
f"К-ть покупок - {stats_7day['count']}\n"
f"Зароблено грошей - {stats_7day['sum'] if stats_7day['sum'] else zero}\n\n"
f"Зароблено гривень - {stats_7day['sum'] if stats_7day['sum'] else zero}\n\n"
f"Місяць:\n"
f"К-ть покупок - {stats_30day['count']}\n"
f"Зароблено грошей - {stats_30day['sum'] if stats_30day['sum'] else zero}\n\n"
f"Зароблено гривень - {stats_30day['sum'] if stats_30day['sum'] else zero}\n\n"
f"За весь час:\n"
f"К-ть покупок - {stats_all_time['count']}\n"
f"Зароблено грошей - {stats_all_time['sum'] if stats_all_time['sum'] else zero}\n\n"
f"Зароблено гривень - {stats_all_time['sum'] if stats_all_time['sum'] else zero}\n\n"
)

await message.answer(text=generated_message, reply_markup=hide_kb())


@router.message(F.text == "Розсилка 📢")
async def alarm(message: Message):
if not message.from_user.id in ADMINS:
if message.from_user.id not in ADMINS:
return

text = "Кому написати? 🤔\nОсобисто 👤\nВсім користувачам👥\nПреміум користувачам👑"
Expand Down Expand Up @@ -281,7 +240,7 @@ async def send_mixed_news2(message: Message, state: FSMContext):
await bot.send_message(
chat_id=message.text, text=f"Адміністратор бота написав: \n{message_text}"
)
await message.answer("Повідомлення надісланно")
await message.answer("Повідомлення надіслано")
except:
await message.answer("Користувача не знайдено!")

Expand Down
5 changes: 3 additions & 2 deletions handlers/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ async def send_about_information(query: CallbackQuery, text: str) -> None:
await query.message.edit_text(
text=text, parse_mode="HTML", reply_markup=about()
)
except:
except Exception as e:
print(f"SEND ABOUT INFORMATION: {e}\n USER STUPID PRESS THE SAME BUTTON")
await query.answer(f"Ви уже переглядаєте {query.data}")


Expand Down Expand Up @@ -163,7 +164,7 @@ async def about_information(query: CallbackQuery):


@router.message(F.text == "Підписка 👑")
async def premium(message: Message):
async def premium(message: Message, text=None):
await message.delete()
db = await Database.setup()
telegram_id = message.from_user.id
Expand Down
4 changes: 2 additions & 2 deletions handlers/parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ async def main(message: Message, bot: Bot):
await get_data(message)
await db.update_count_parsing_post(telegram_id)
await db.add_url(telegram_id, url=message.text, date=date)
except Exception as exeception:
except Exception as e:
text_for_admin = (
f"У користувача {telegram_id} сталася помилка\n"
f"Details: {exeception}\n"
f"Details: {e}\n"
f"TraceBack: \n\n{traceback.format_exc()}\n"
f"Посилання: {message.text}"
)
Expand Down
33 changes: 17 additions & 16 deletions handlers/payments.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ def create_hash(to_encode: list[str | int | None]) -> str:
to_hash = ""
for element in to_encode:
to_hash += (str(element) if element is not None else "") + ";"
hash = hmac.new(SECRET_KEY.encode("utf-8"), to_hash[:-1].encode("utf-8"), "MD5").hexdigest()
return hash
return hmac.new(SECRET_KEY.encode("utf-8"), to_hash[:-1].encode("utf-8"), "MD5").hexdigest()


def generate_random_string(length: int) -> str:
Expand All @@ -86,9 +85,9 @@ async def create_payment(
order_date: int,
amount: int,
currency: str,
product_name: list,
product_count: list,
product_price: list,
product_name: tuple,
product_count: tuple,
product_price: tuple,
) -> CreateInvoice:
merchant_signature = create_hash(
[
Expand Down Expand Up @@ -162,7 +161,7 @@ async def get_payment_info(order_reference: str, merchant_account: str) -> Check

@router.callback_query(F.data == "Продовжити підписку 💳")
@router.callback_query(F.data == "Придбати підписку 💳")
async def payment(query: CallbackQuery):
async def payment(query: CallbackQuery, message=None):
db = await Database.setup()
amount = 300
currency = "UAH"
Expand All @@ -185,7 +184,7 @@ async def payment(query: CallbackQuery):
description = (
"👑 Підписка на телеграм бота для парсингу\n\n"
"💸 Тариф: 1 місяць / 300 грн\n\n"
"🛠 Послуги: Відкриття доступу до парсингу даних с сайту ОЛХ"
"🛠 Послуги: Відкриття доступу до парсингу даних з сайту ОЛХ"
)

if response.reason_code == 1100:
Expand Down Expand Up @@ -229,11 +228,12 @@ async def check_status_invoice(
order_reference=response.order_reference,
)

# [N] NOTIFY ADMINISTARTOR
# [N] NOTIFY ADMINISTRATOR
await bot.send_message(
chat_id=-1001902595324,
message_thread_id=392,
text=f"Оплата пройшла успішно @{await db.get_username(telegram_id)} {telegram_id}\nКод оплати {response.reason_code}\nКод підписки {reference}",
text=f"Оплата успішно проведена @{await db.get_username(telegram_id)} {telegram_id}"
f"\nКод оплати {response.reason_code}\nКод підписки {reference}",
)
await bot.send_message(
text=f"Підписка {telegram_id} додалась 🟩",
Expand All @@ -246,7 +246,7 @@ async def check_status_invoice(
expiration_date = await db.get_expiration_date(telegram_id)
await bot.send_message(
chat_id=telegram_id,
text=f"Дякую за підписку, її продовженно до {expiration_date}",
text=f"Дякую за підписку, її продовжено до {expiration_date}",
reply_markup=hide_kb(),
)
return
Expand All @@ -260,11 +260,11 @@ async def check_status_invoice(
return

if response.transaction_status == "Declined" and response.reason_code != 1151:
# [N] TRY DELETE OLD MESSAGE
# [N] TRY TO DELETE OLD MESSAGE
try:
await bot.delete_message(chat_id=telegram_id, message_id=message_id)
except:
pass
except Exception as e:
print(f"CHECK STATUS INVOICE: {e}")

# [N] UPDATE CODE IN BD
await db.update_premium_operations(
Expand All @@ -273,17 +273,18 @@ async def check_status_invoice(
order_reference=response.order_reference,
)

# [N] NOTIFY ADMINISTARTOR
# [N] NOTIFY ADMINISTRATOR
await bot.send_message(
chat_id=-1001902595324,
message_thread_id=392,
text=f"Оплата провалилась @{await db.get_username(telegram_id)} {telegram_id}\nКод оплати {response.reason_code}\nКод підписки {reference}",
text=f"Оплата провалилась @{await db.get_username(telegram_id)} {telegram_id}"
f"\nКод оплати {response.reason_code}\nКод підписки {reference}",
)

# [N] SEND NOTIFY
await bot.send_message(
chat_id=telegram_id,
text=f"Оплату нажаль було відхиленно 😕\nЯкщо є питання за додатковою інформацією зверніться до @realtor_057",
text=f"Оплату нажаль було відхилено 😕\nЯкщо є питання за додатковою інформацією зверніться до @realtor_057",
reply_markup=hide_kb(),
)
return
Expand Down
12 changes: 6 additions & 6 deletions handlers/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ async def check_all_invoice(lock):
async with lock:
db = await Database.setup()
order_reference = await db.check_all_order_reference()
if order_reference != []:
if order_reference:
for reference in order_reference:
try:
response = await get_payment_info(reference[0], MERCHANT_ACCOUNT)
Expand Down Expand Up @@ -66,19 +66,19 @@ async def check_all_premium(lock):
if text_user:
await notify_status_premium(
text_user=text_user,
texr_admin=text_admin,
text_admin=text_admin,
telegram_id=telegram_id,
)


async def notify_status_premium(text_user: str, texr_admin: str, telegram_id: int) -> None:
async def notify_status_premium(text_user: str, text_admin: str, telegram_id: int) -> None:
try:
await bot.send_message(text=texr_admin, chat_id=-1001902595324, message_thread_id=481)
await bot.send_message(text=text_admin, chat_id=-1001902595324, message_thread_id=481)
await bot.send_message(
text=text_user, chat_id=telegram_id, reply_markup=buy_premium_kb(True)
)
except:
pass
except Exception as e:
print(f'NOTIFY BLOCK ERROR: {e}')


async def create_tasks():
Expand Down
Loading

0 comments on commit a29c2ed

Please sign in to comment.