Skip to content

Commit

Permalink
add new payment
Browse files Browse the repository at this point in the history
  • Loading branch information
ebosh-alt committed Feb 8, 2023
1 parent f8f4c16 commit 121f574
Show file tree
Hide file tree
Showing 26 changed files with 324 additions and 44 deletions.
1 change: 1 addition & 0 deletions .idea/design_skillbot.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/jsLibraryMappings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

71 changes: 71 additions & 0 deletions Payments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import time
from asyncio import run
from multiprocessing import Process

import schedule as schedule
from yookassa import Payment

import functions
import texts
from Enum_classes import Flags
from config import users, bot, WEBHOOK_HOST


class Checking:
def __init__(self) -> None:
self.p0 = Process()

def start_process(self, func, arg=None):
if arg is not None:
self.p0 = Process(target=func, args=(arg,))
else:
self.p0 = Process(target=func)
self.p0.start()

def stop_process(self):
self.p0.terminate()

def check_pay(self, key: str):
try:
res = Payment.find_one(key)
return True
except:
return False

async def work(self):
list_user_id: list = users.get_keys()

for user_id in list_user_id:
try:
user = users.get(user_id)

if not user.payment and user.flag == Flags.Payment:
if self.check_pay(user.key_payment):
await bot.send_message(chat_id=user_id,
text=texts.text_after_pay,
reply_markup=functions.create_keyboard(
name_buttons=["Начать историю"]
),
parse_mode="Markdown",
disable_web_page_preview=True,
)
user.payment = True
user.flag = Flags.NONE
users.update_info(user)

except:
pass

def start_schedule(self):
while True:
schedule.run_pending()
run(self.work())
time.sleep(1)




if __name__ == "__main__":
checking = Checking()
checking.check_pay("2b75bee3-000f-5000-8000-136a5ca22d9b")
checking.start_process(func=checking.start_schedule)
65 changes: 44 additions & 21 deletions Reminders.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@
from datetime import datetime
from multiprocessing import Process

import schedule

import functions
import texts
from config import users, time_reminder_2, bot, time_reminder_1
from config import users, time_reminder_2, bot, time_reminder_1, WEBHOOK_HOST, link_to_site


class Reminders:
def __init__(self) -> None:
self.p0 = Process()
schedule.every().day.at("17:52").do(self.send_mes_1, mes=texts.text_for_reminder_3)

def start_process(self, func, arg=None):
if arg is not None:
Expand All @@ -21,34 +25,53 @@ def start_process(self, func, arg=None):
def stop_process(self):
self.p0.terminate()

async def send_mes_1(self, mes: str):
list_user_id: list = users.get_keys()
for user_id in list_user_id:
user = users.get(user_id)
print(user_id)
# if not user.payment:
# await bot.send_message(chat_id=user_id,
# text=mes,
# reply_markup=functions.inl_create_keyboard(buttons=
# [["Оплатить 2990 руб.",
# WEBHOOK_HOST + f"/pay?user_id={user_id}&price=2990.00"]]))

@staticmethod
async def work():
list_user_id = users.get_keys()
now_time = datetime.now()

for user_id in list_user_id:
try:
user = users.get(user_id)
if not user.payment and user.count_reminder != 2:
time_transition_payment = datetime.utcfromtimestamp(user.time_transition_payment)
if (now_time - time_transition_payment) > time_reminder_1 and user.count_reminder == 0:
await bot.send_message(chat_id=user_id,
text=texts.text_for_reminder_1,
parse_mode="Markdwon")
user.count_reminder += 1

elif (now_time - time_transition_payment) > time_reminder_2 and user.count_reminder == 1:
await bot.send_message(chat_id=user_id,
text=texts.text_for_reminder_2,
parse_mode="Markdown")
user.count_reminder += 1

users.update_info(user)
except:
pass

user = users.get(user_id)
if not user.payment and user.count_reminder != 1:
time_transition_payment = datetime.utcfromtimestamp(user.time_transition_payment)
if (now_time - time_transition_payment) > time_reminder_1 and user.count_reminder == 0:
await bot.send_message(chat_id=user_id,
text=texts.text_for_reminder,
reply_markup=functions.inl_create_keyboard(
buttons=[["Оплатить 2990 руб.",
WEBHOOK_HOST + f"/pay?user_id={user_id}&price=2990.00"],
["Узнать подробнее", link_to_site]]),
parse_mode="Markdown",
disable_web_page_preview=True)
user.count_reminder += 1
users.update_info(user)

if now_time.time().strftime("%H:%M") == "17:59":

if not user.payment:
await bot.send_message(chat_id=user_id,
text=texts.text_for_reminder_3,
reply_markup=functions.inl_create_keyboard(buttons=
[["Оплатить 2990 руб.",
WEBHOOK_HOST + f"/pay?user_id={user_id}&price=2990.00"]]))


def start_schedule(self):
while True:
schedule.run_pending()
run(self.work())
time.sleep(10)

Expand Down
5 changes: 4 additions & 1 deletion Users.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@

class User:
def __init__(self, key: int = None, flag: Flags = Flags.NONE, payment: bool = False, username: str = None,
time_transition_payment: int = None, count_reminder: int = 0) -> None:
time_transition_payment: int = None, count_reminder: int = 0, key_payment: str = None) -> None:
self.key: int = key
self.flag: Flags = flag
self.payment: bool = payment
self.username: str = username
self.time_transition_payment: int = time_transition_payment
self.count_reminder: int = count_reminder
self.key_payment = key_payment

def get_tuple(self) -> tuple:
return (self.key,
Expand All @@ -19,6 +20,7 @@ def get_tuple(self) -> tuple:
self.username,
self.time_transition_payment,
self.count_reminder,
self.key_payment,
)


Expand All @@ -39,6 +41,7 @@ def get(self, id: int) -> User | bool:
username=obj_tuple[3],
time_transition_payment=obj_tuple[4],
count_reminder=obj_tuple[5],
key_payment=obj_tuple[6],
)
return obj
return False
Binary file modified __pycache__/Enum_classes.cpython-311.pyc
Binary file not shown.
Binary file modified __pycache__/Openai.cpython-311.pyc
Binary file not shown.
Binary file added __pycache__/Payments.cpython-311.pyc
Binary file not shown.
Binary file modified __pycache__/Reminders.cpython-311.pyc
Binary file not shown.
Binary file modified __pycache__/SQLite.cpython-311.pyc
Binary file not shown.
Binary file modified __pycache__/Users.cpython-311.pyc
Binary file not shown.
Binary file modified __pycache__/config.cpython-311.pyc
Binary file not shown.
Binary file modified __pycache__/functions.cpython-311.pyc
Binary file not shown.
Binary file modified __pycache__/keyboards.cpython-311.pyc
Binary file not shown.
Binary file modified __pycache__/texts.cpython-311.pyc
Binary file not shown.
26 changes: 21 additions & 5 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from Openai import OpenAi
from Users import Users

api_key = "5993284335:AAHuoszGTlENSxll7RzDEfvkRracX_rRBIc"
api_key = "5333826486:AAGWXbywv1pQ9AJ75d1zafg2xwBRBjtyYnI"
openai_api_key = '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'

bot = Bot(token=api_key)
Expand All @@ -21,17 +21,33 @@
'flag': 'integer',
'payment': 'integer',
'username': 'text',
'time_transition_payment': 'int',
'count_reminder': 'int',
'time_transition_payment': 'integer',
'count_reminder': 'integer',
'key_payment': 'text',
}
users = Users(db_file_name=db_file_name, args=args, table_name=table_name)
time_reminder_1 = datetime.timedelta(hours=1)
time_reminder_2 = datetime.timedelta(hours=4)
OpenAI = OpenAi(openai_api_key)

code_for_payment = "SBND18244887"

introductory_part = "Ты Никки — робот, который учит дизайну и правилам дизайна. Тебе нужно ответить на вопрос твоего " \
"ученика. Он спрашивает:"
OpenAI = OpenAi(openai_api_key)

text_for_pay = "\n\nБолее подробно я отвечу после начала курса — для этого [активируйте полную версию](https://www.skillbots.ru/design?utm_source=trial_tg&utm_medium=tgbot) 😊"
text_for_pay = "\n\nБолее подробно я отвечу после начала курса — для этого [активируйте полную версию](" \
"https://www.skillbots.ru/design?utm_source=trial_tg&utm_medium=tgbot) 😊"

WEBHOOK_HOST = "https://3bbf-109-252-118-243.ngrok.io"
WEBHOOK_PATH = f"/{api_key}"
WEBAPP_HOST = '0.0.0.0'
WEBAPP_PORT = "80"
WEBHOOK_URL = WEBHOOK_HOST + WEBHOOK_PATH

link_to_site = "https://www.skillbots.ru/design?utm_source=error_code_tg&utm_medium=tgbot"

link_to_bot = "https://t.me/test_for_flow_evg_bot"

user = users.get(686171972)
user.payment = False
users.update_info(user)
Binary file modified db.db
Binary file not shown.
Binary file added db.db-shm
Binary file not shown.
Binary file added db.db-wal
Binary file not shown.
64 changes: 64 additions & 0 deletions functions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,44 @@
from aiogram import types
from bs4 import BeautifulSoup
from yookassa import Payment, Configuration

Configuration.account_id = '873492'
Configuration.secret_key = 'test_rFwIwdtgIwpyQgI555vYUd7u_Nd8p3u2A2h5o5diF0Q'


def create_pay(user_id: str, price: str) -> str:
payment = Payment.create({
"amount": {
"value": price,
"currency": "RUB"
},
"confirmation": {
"type": "embedded"
},
"capture": True,
"description": user_id
})
return payment.confirmation.confirmation_token





def render_html(pay_token: str) -> str:
with open("./templates/index.html", "r", encoding='utf-8') as inf:
txt = inf.read()
soup = BeautifulSoup(txt, 'html.parser')
with open("./templates/index.js", "r", encoding='utf-8') as inf:
txt = inf.read()
new_soup = BeautifulSoup(txt, 'html.parser').prettify().split(" ")
new_soup[15] = f"'{pay_token}',"
txt = "<script>"
for i in new_soup:
txt += i + ' '
txt += "\n </script>"
new_soup = BeautifulSoup(txt, 'html.parser')
soup.body.append(new_soup)
return soup.prettify()


def create_keyboard(name_buttons: list, ) -> types.ReplyKeyboardMarkup:
Expand All @@ -10,3 +50,27 @@ def create_keyboard(name_buttons: list, ) -> types.ReplyKeyboardMarkup:
)
keyboard.add(*array)
return keyboard


def inl_create_keyboard(buttons: list[list], ):
keyboard = types.InlineKeyboardMarkup(row_width=len(buttons), resize_keyboard=True)
array = []
for button in buttons:
if len(button) == 1:
array.append(
types.InlineKeyboardButton(text=button[0])
)
if len(button) == 2:
array.append(
types.InlineKeyboardButton(text=button[0], url=button[1])
)
if len(button) == 3:
array.append(
types.InlineKeyboardButton(text=button[0], url=button[1], callback_data="pay")
)
keyboard.add(*array)
return keyboard


if __name__ == "__main__":
render_html(create_pay("55"))
5 changes: 0 additions & 5 deletions keyboards.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
from aiogram import types

# start_keyboard = types.ReplyKeyboardMarkup(row_width=3).add(
# types.KeyboardButton(text='Структура курса'),
# types.KeyboardButton(text='Сюжет курса'),
# types.KeyboardButton(text='Хочу начать'),
# )
name_buttons_by_start = ['Структура курса', 'Сюжет курса', 'Хочу начать']


Loading

0 comments on commit 121f574

Please sign in to comment.