Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
* добавлена оплата по YooMoney.
  • Loading branch information
rashidovich2 authored Oct 6, 2022
1 parent 157b36c commit 08376cd
Show file tree
Hide file tree
Showing 49 changed files with 435 additions and 26 deletions.
12 changes: 6 additions & 6 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
from tgbot.services.api_sqlite import create_dbx
from tgbot.utils.misc.bot_commands import set_commands
from tgbot.utils.misc.bot_logging import bot_logger
from tgbot.utils.misc_functions import check_update, check_bot_data, on_startup_notify, update_profit_day, \
update_profit_week, autobackup_admin, check_mail
from tgbot.utils.misc_functions import on_startup_notify, update_profit_day, \
update_profit_week, autobackup_admin

colorama.init()

Expand All @@ -23,8 +23,8 @@
async def scheduler_start(aSession):
scheduler.add_job(update_profit_week, "cron", day_of_week="mon", hour=00, minute=1)
scheduler.add_job(update_profit_day, "cron", hour=00)
scheduler.add_job(check_update, "cron", hour=00, args=(aSession,))
scheduler.add_job(check_mail, "cron", hour=12, args=(aSession,))
#scheduler.add_job(check_update, "cron", hour=00, args=(aSession,))
#scheduler.add_job(check_mail, "cron", hour=12, args=(aSession,))
scheduler.add_job(autobackup_admin, "cron", hour=00)


Expand All @@ -37,13 +37,13 @@ async def on_startup(dp: Dispatcher):
await dp.bot.get_updates(offset=-1)

await set_commands(dp)
await check_bot_data()
#await check_bot_data()
await scheduler_start(aSession)
await on_startup_notify(dp, aSession)

bot_logger.warning("BOT WAS STARTED")
print(colorama.Fore.LIGHTYELLOW_EX + "~~~~~ Bot was started ~~~~~")
print(colorama.Fore.LIGHTBLUE_EX + "~~~~~ TG developer: @raclear ~~~~~")
print(colorama.Fore.LIGHTBLUE_EX + "~~~~~ TG developer: @raclear Repo fork from: @djimbo ~~~~~")
print(colorama.Fore.RESET)

if len(get_admins()) == 0: print("***** ENTER ADMIN ID IN settings.ini *****")
Expand Down
Binary file added tgbot/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added tgbot/data/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added tgbot/data/__pycache__/config.cpython-310.pyc
Binary file not shown.
Binary file added tgbot/data/__pycache__/loader.cpython-310.pyc
Binary file not shown.
2 changes: 1 addition & 1 deletion tgbot/data/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
BOT_TOKEN = read_config['settings']['token'].strip().replace(" ", "") # Токен бота
PATH_DATABASE = "tgbot/data/database.db" # Путь к БД
PATH_LOGS = "tgbot/data/logs.log" # Путь к Логам
BOT_VERSION = "1.0" # Версия бота
BOT_VERSION = "1.1" # Версия бота


# Получение администраторов бота
Expand Down
Binary file added tgbot/handlers/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
84 changes: 83 additions & 1 deletion tgbot/handlers/admin_payment.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from tgbot.data.loader import dp
from tgbot.keyboards.inline_admin import payment_choice_finl
from tgbot.services.api_qiwi import QiwiAPI
from tgbot.services.api_yoo import YooAPI
from tgbot.services.api_sqlite import update_paymentx, get_paymentx
from tgbot.utils.misc.bot_filters import IsAdmin

Expand All @@ -29,7 +30,7 @@ async def payment_systems_edit(call: CallbackQuery):

get_payment = get_paymentx()

if get_payment['qiwi_login'] != "None" and get_payment['qiwi_token'] != "None" or way_status == "False":
if get_payment['qiwi_login'] != "None" and get_payment['qiwi_token'] != "None" or get_payment['yoo_client_id'] != "None" or way_status == "False":
if way_pay == "Form":
if get_payment['qiwi_secret'] != "None" or way_status == "False":
update_paymentx(way_form=way_status)
Expand All @@ -38,6 +39,13 @@ async def payment_systems_edit(call: CallbackQuery):
"❗ Приватный ключ отсутствует. Измените киви и добавьте приватный ключ для включения оплаты по Форме",
True)
return
elif way_pay == "ForYm":
if get_payment['yoo_client_id'] != "None" or way_status == "False":
update_paymentx(way_formy=way_status)
else:
await call.answer(
"❗ Приватный ключ отсутствует. Измените yoomoney и добавьте приватный ключ для включения оплаты по Форме",
True)
elif way_pay == "Number":
update_paymentx(way_number=way_status)
elif way_pay == "Nickname":
Expand Down Expand Up @@ -81,6 +89,16 @@ async def payment_qiwi_balance(message: Message, state: FSMContext):

await (await QiwiAPI(message)).get_balance()

######################################## YooMoney ################################
# Изменение реквизитов Yoo
@dp.message_handler(IsAdmin(), text="💳 Изменить Yoo 🖍", state="*")
async def payment_qiwi_edit(message: Message, state: FSMContext):
await state.finish()

await state.set_state("here_yoo_acc_number")
await message.answer("<b>💳 Введите <code>номер счета </code> Yoo аккаунта 🖍</b>")



######################################## ПРИНЯТИЕ QIWI ########################################
# Принятие логина для QIWI
Expand All @@ -101,6 +119,21 @@ async def payment_qiwi_edit_login(message: Message, state: FSMContext):
"🥝 Введите <code>номер (через +7, +380)</code> QIWI кошелька 🖍")


# Принятие acc_number для Yoo
@dp.message_handler(IsAdmin(), state="here_yoo_acc_number")
async def payment_qiwi_edit_login(message: Message, state: FSMContext):
#if message.text.startswith("+"):
await state.update_data(here_yoo_acc_number=message.text)

await state.set_state("here_yoo_token")
await message.answer(
"<b>🥝 Введите <code>токен API</code> Yoo кошелька 🖍</b>\n"
"❕ Получить можно тут 👉 <a href='https://yoomoney.ru/api'><b>Нажми на меня</b></a>\n"
"❕ При получении токена, ставьте только первые 3 галочки.",
disable_web_page_preview=True
)


# Принятие токена для QIWI
@dp.message_handler(IsAdmin(), state="here_qiwi_token")
async def payment_qiwi_edit_token(message: Message, state: FSMContext):
Expand All @@ -114,6 +147,33 @@ async def payment_qiwi_edit_token(message: Message, state: FSMContext):
disable_web_page_preview=True
)

# Принятие токена для Yoo
@dp.message_handler(IsAdmin(), state="here_yoo_token")
async def payment_qiwi_edit_token(message: Message, state: FSMContext):
await state.update_data(here_yoo_token=message.text)

await state.set_state("here_yoo_client_id")
await message.answer(
"<b>🥝 Введите <code>Клиентский ID 🖍</code></b>\n"
"❕ Получить можно тут 👉 <a href='https://yoomoney.ru/p2p-admin/transfers/api'><b>Нажми на меня</b></a>\n"
"❕ Вы можете пропустить добавление оплаты по Форме, отправив: <code>0</code>",
disable_web_page_preview=True
)

# Принятие клиентского ID для Yoo
@dp.message_handler(IsAdmin(), state="here_yoo_client_id")
async def payment_qiwi_edit_token(message: Message, state: FSMContext):
await state.update_data(here_yoo_client_id=message.text)

await state.set_state("here_yoo_redirect_url")
await message.answer(
"<b>🥝 Введите <code>Redirect URL 🖍</code></b>\n"
"❕ Получить можно тут 👉 <a href='https://yoomoney.ru/p2p-admin/transfers/api'><b>Нажми на меня</b></a>\n"
"❕ Вы можете пропустить добавление оплаты по Форме, отправив: <code>0</code>",
disable_web_page_preview=True
)



# Принятие приватного ключа для QIWI
@dp.message_handler(IsAdmin(), state="here_qiwi_secret")
Expand All @@ -131,3 +191,25 @@ async def payment_qiwi_edit_secret(message: Message, state: FSMContext):
await asyncio.sleep(0.5)

await (await QiwiAPI(cache_message, qiwi_login, qiwi_token, qiwi_secret, True)).pre_checker()

# Принятие приватного ключа для Yoo
@dp.message_handler(IsAdmin(), state="here_yoo_redirect_url")
async def payment_qiwi_edit_secret(message: Message, state: FSMContext):
async with state.proxy() as data:
acc_number = data['here_yoo_acc_number']
token = data['here_yoo_token']
client_id = data['here_yoo_client_id']
if message.text == "0": redirect_url = "None"
if message.text != "0": redirect_url = message.text

await state.finish()

cache_message = await message.answer("<b>🥝 Проверка введённых Yoo данных... 🔄</b>")
await asyncio.sleep(0.5)
#await update_paymentx()
await (await YooAPI(acc_number, token, client_id, redirect_url)).update_yoo()
await message.answer(
"<b>Данные yoomoney успешно обновлены!</b>\n"
"❕ Вы можете пропустить добавление оплаты по Форме, отправив: <code>0</code>",
disable_web_page_preview=True
)
2 changes: 1 addition & 1 deletion tgbot/handlers/main_start.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
'buy_item_open', 'buy_item_confirm']

# Игнор-колбэки пополнений
prohibit_refill = ['user_refill', 'refill_choice', 'Pay:', 'Pay:Form', 'Pay:Number', 'Pay:Nickname']
prohibit_refill = ['user_refill', 'refill_choice', 'Pay:', 'Pay:Form', 'Pay:ForYm', 'Pay:Number', 'Pay:Nickname']


####################################################################################################
Expand Down
44 changes: 40 additions & 4 deletions tgbot/handlers/user_transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
from tgbot.data.loader import dp
from tgbot.keyboards.inline_user import refill_bill_finl, refill_choice_finl
from tgbot.services.api_qiwi import QiwiAPI
from tgbot.services.api_yoo import YooAPI
from tgbot.services.api_sqlite import update_userx, get_refillx, add_refillx, get_userx
from tgbot.utils.const_functions import get_date, get_unix
from tgbot.utils.misc_functions import send_admins

min_input_qiwi = 5 # Минимальная сумма пополнения в рублях
min_input_yoo = 5


# Выбор способа пополнения
Expand Down Expand Up @@ -46,10 +48,15 @@ async def refill_get(message: Message, state: FSMContext):
if min_input_qiwi <= pay_amount <= 300000:
get_way = (await state.get_data())['here_pay_way']
await state.finish()

get_message, get_link, receipt = await (
await QiwiAPI(cache_message, user_bill_pass=True)
).bill_pay(pay_amount, get_way)
if get_way == 'Form':
get_message, get_link, receipt = await (
await QiwiAPI(cache_message, user_bill_pass=True)
).bill_pay(pay_amount, get_way)
elif get_way == 'ForYm':
print("test")
get_message, get_link, receipt = await (
await YooAPI(cache_message) #, acc_number=410011512189686
).bill_pay(pay_amount, get_way)

if get_message:
await cache_message.edit_text(get_message, reply_markup=refill_bill_finl(get_link, receipt, get_way))
Expand Down Expand Up @@ -88,6 +95,35 @@ async def refill_check_form(call: CallbackQuery):
await call.message.edit_text("<b>❌ Счёт был отклонён.</b>")


#Проверка оплаты через форму Yoo
@dp.callback_query_handler(text_contains="Pay:ForYm")
async def refill_check_formy(call: CallbackQuery):
receipt = call.data.split(":")[2]
print(call.data)
#print(receipt)

pay_status, pay_amount = await (
await YooAPI()
).check_formy(receipt)

#print(pay_status, pay_amount)

if pay_status == "success":
get_refill = get_refillx(refill_receipt=receipt)
if get_refill is None:
await refill_success(call, receipt, pay_amount, "ForYm")
else:
await call.answer("❗ Ваше пополнение уже было зачислено.", True)
elif pay_status == "EXPIRED":
await call.message.edit_text("<b>❌ Время оплаты вышло. Платёж был удалён.</b>")
elif pay_status == "WAITING":
await call.answer("❗ Платёж не был найден.\n"
"⌛ Попробуйте чуть позже.", True, cache_time=5)
elif pay_status == "REJECTED":
await call.message.edit_text("<b>❌ Счёт был отклонён.</b>")



# Проверка оплаты по переводу (по нику или номеру)
@dp.callback_query_handler(text_startswith=['Pay:Number', 'Pay:Nickname'])
async def refill_check_send(call: CallbackQuery):
Expand Down
Binary file added tgbot/keyboards/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
6 changes: 5 additions & 1 deletion tgbot/keyboards/inline_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,25 @@ def payment_choice_finl():
status_form_kb = ikb("✅", callback_data="change_payment:Form:False")
status_number_kb = ikb("✅", callback_data="change_payment:Number:False")
status_nickname_kb = ikb("✅", callback_data="change_payment:Nickname:False")
status_formy_kb = ikb("✅", callback_data="change_payment:ForYm:False")

if get_payments['way_form'] == "False":
status_form_kb = ikb("❌", callback_data="change_payment:Form:True")
if get_payments['way_number'] == "False":
status_number_kb = ikb("❌", callback_data="change_payment:Number:True")
if get_payments['way_nickname'] == "False":
status_nickname_kb = ikb("❌", callback_data="change_payment:Nickname:True")
if get_payments['way_formy'] == "False":
status_formy_kb = ikb("❌", callback_data="change_payment:ForYm:True")

keyboard.add(
ikb("📋 По форме", url="https://vk.cc/bYjKGM"), status_form_kb
).row(
ikb("📞 По номеру", url="https://vk.cc/bYjKEy"), status_number_kb
).row(
ikb("Ⓜ По никнейму", url="https://vk.cc/c8s66X"), status_nickname_kb
)
).row(
ikb("📋 По Yoo", url="https://vk.cc/bYjKGM"), status_formy_kb)

return keyboard

Expand Down
7 changes: 6 additions & 1 deletion tgbot/keyboards/inline_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,13 @@ def refill_choice_finl():
active_kb.append(InlineKeyboardButton("📞 QIWI номер", callback_data="refill_choice:Number"))
if get_payments['way_nickname'] == "True":
active_kb.append(InlineKeyboardButton("Ⓜ QIWI никнейм", callback_data="refill_choice:Nickname"))
if get_payments['way_formy'] == "True":
active_kb.append(InlineKeyboardButton("📋 Yoo форма", callback_data="refill_choice:ForYm"))

if len(active_kb) == 3:
if len(active_kb) == 4:
keyboard.add(active_kb[0], active_kb[1])
keyboard.add(active_kb[2], active_kb[3])
elif len(active_kb) == 3:
keyboard.add(active_kb[0], active_kb[1])
keyboard.add(active_kb[2])
elif len(active_kb) == 2:
Expand Down
2 changes: 1 addition & 1 deletion tgbot/keyboards/reply_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def menu_frep(user_id):
def payments_frep():
keyboard = ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.row("🥝 Изменить QIWI 🖍", "🥝 Проверить QIWI ♻", "🥝 Баланс QIWI 👁")
keyboard.row("⬅ Главное меню", "🖲 Способы пополнений")
keyboard.row("⬅ Главное меню", "💳 Изменить Yoo 🖍", "🖲 Способы пополнений")

return keyboard

Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added tgbot/services/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
21 changes: 21 additions & 0 deletions tgbot/services/api_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,24 @@ async def close(self) -> None:
return None

await self._session.close()

# Асинхронная сессия для запросов
class RequestsSession:
def __init__(self) -> None:
self._session: Optional[aiohttp.ClientSession] = None

# Вызов сессии
async def get_session(self) -> aiohttp.ClientSession:
if self._session is None:
new_session = aiohttp.ClientSession()
self._session = new_session

return self._session

# Закрытие сессии
async def close(self) -> None:
if self._session is None:
return None

await self._session.close()

16 changes: 11 additions & 5 deletions tgbot/services/api_sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ def create_dbx():
print("DB was not found(1/8) | Creating...")

# Создание БД с хранением данных платежных систем
if len(con.execute("PRAGMA table_info(storage_payment)").fetchall()) == 7:
if len(con.execute("PRAGMA table_info(storage_payment)").fetchall()) == 13:
print("DB was found(2/8)")
else:
con.execute("CREATE TABLE storage_payment("
Expand All @@ -492,12 +492,18 @@ def create_dbx():
"qiwi_nickname TEXT,"
"way_form TEXT,"
"way_number TEXT,"
"way_nickname TEXT)")
"way_nickname TEXT,"
"way_formy TEXT,"
"user_id INTEGER,"
"yoo_token TEXT,"
"yoo_client_id TEXT,"
"yoo_redirect_url TEXT,"
"yoo_acc_number INTEGER)")

con.execute("INSERT INTO storage_payment("
"qiwi_login, qiwi_token, qiwi_secret, qiwi_nickname, way_form, way_number, way_nickname) "
"VALUES (?, ?, ?, ?, ?, ?, ?)",
['None', 'None', 'None', 'None', 'False', 'False', 'False'])
"qiwi_login, qiwi_token, qiwi_secret, qiwi_nickname, way_form, way_number, way_nickname, way_formy, yoo_token, yoo_client_id, yoo_redirect_url, yoo_acc_number) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
['None', 'None', 'None', 'None', 'False', 'False', 'False', 'False', 'None', 'None', 'None', 'None'])
print("DB was not found(2/8) | Creating...")

# Создание БД с хранением настроек
Expand Down
Loading

0 comments on commit 08376cd

Please sign in to comment.