Added sponsorship support

This commit is contained in:
2022-12-22 15:05:27 +01:00
parent ac5a0d112f
commit 95e9fdf460
8 changed files with 294 additions and 43 deletions

View File

@@ -77,7 +77,7 @@ async def callback_query_reapply_reject(app, clb):
async def callback_query_reapply_old(app, clb):
fullclb = clb.data.split("_")
message = await app.get_messages(clb.from_user.id, int(fullclb[2]))
await confirm_yes(app, message)
await confirm_yes(app, message, kind="application")
await clb.message.edit(clb.message.text, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("done", "button", locale=clb.from_user), "nothing")]]))
# Start a new application when user reapplies after leaving the chat

View File

@@ -1,10 +1,10 @@
from datetime import datetime
from app import app
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ForceReply
from pyrogram import filters
from classes.holo_user import HoloUser
from modules.utils import configGet, locale, logWrite
from modules.database import col_tmp,col_sponsorships
from modules.database import col_tmp, col_sponsorships
# Callbacks sponsorship ========================================================================================================
@app.on_callback_query(filters.regex("sponsor_apply_[\s\S]*"))
@@ -15,24 +15,51 @@ async def callback_query_sponsor_apply(app, clb):
logWrite(f"User {holo_user.id} applied for sponsorship")
col_tmp.insert_one(
{
"user": holo_user.id,
"type": "sponsorship",
"complete": False,
"sent": False,
"state": "fill",
"stage": 1,
"sponsorship": {
"streamer": None,
"expires": datetime.fromtimestamp(0),
"proof": None,
"label": ""
}
}
)
holo_user.sponsorship_restart()
edited_markup = [[InlineKeyboardButton(text=str(locale("sponsor_started", "button")), callback_data="nothing")]]
await clb.message.edit(text=locale("sponsorship_apply", "message"), reply_markup=InlineKeyboardMarkup(edited_markup))
await clb.answer(text=locale("sponsor_started", "callback").format(holo_user.id), show_alert=False)
await app.send_message(holo_user.id, locale(f"sponsor1", "message", locale=holo_user.locale), reply_markup=ForceReply(placeholder=str(locale(f"sponsor1", "force_reply", locale=holo_user.locale))))
await clb.answer(text=locale("sponsor_started", "callback").format(holo_user.id), show_alert=False)
@app.on_callback_query(filters.regex("sponsor_yes_[\s\S]*"))
async def callback_query_sponsor_yes(app, clb):
fullclb = clb.data.split("_")
holo_user = HoloUser(int(fullclb[2]))
await app.send_message(configGet("admin_group"), locale("sponsor_approved_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True)
await app.send_message(holo_user.id, locale("sponsor_approved", "message", locale=holo_user))
logWrite(f"User {holo_user.id} got approved by {clb.from_user.id}")
if col_sponsorships.find_one({"user": holo_user.id}) is not None:
col_sponsorships.update_one({"date": {"$eq": datetime.now()}, "admin": {"$eq": clb.from_user.id}, "sponsorship": {"$eq": col_tmp.find_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "sponsorship"}})["sponsorship"]}})
else:
col_sponsorships.insert_one({"user": holo_user.id, "date": datetime.now(), "admin": clb.from_user.id, "sponsorship": col_tmp.find_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "sponsorship"}})["sponsorship"]})
col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "sponsorship"}}, {"$set": {"state": "approved", "sent": False}})
await holo_user.set_label(configGet("destination_group"), col_tmp.find_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "sponsorship"}})["sponsorship"]["label"])
edited_markup = [[InlineKeyboardButton(text=str(locale("accepted", "button")), callback_data="nothing")]]
await app.edit_message_caption(clb.message.chat.id, clb.message.id, caption=clb.message.caption, reply_markup=InlineKeyboardMarkup(edited_markup))
await clb.answer(text=f"✅ Confirmed {fullclb[2]}", show_alert=False)
@app.on_callback_query(filters.regex("sponsor_no_[\s\S]*"))
async def callback_query_sponsor_no(app, clb):
fullclb = clb.data.split("_")
holo_user = HoloUser(int(fullclb[2]))
await app.send_message(configGet("admin_group"), locale("sponsor_rejected_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True)
await app.send_message(holo_user.id, locale("sponsor_rejected", "message", locale=holo_user))
logWrite(f"User {holo_user.id} got rejected by {clb.from_user.id}")
col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "sponsorship"}}, {"$set": {"state": "rejected", "sent": False}})
edited_markup = [[InlineKeyboardButton(text=str(locale("declined", "button")), callback_data="nothing")]]
await app.edit_message_caption(clb.message.chat.id, clb.message.id, caption=clb.message.caption, reply_markup=InlineKeyboardMarkup(edited_markup))
await clb.answer(text=f"❌ Rejected {fullclb[2]}", show_alert=False)

View File

@@ -1,8 +1,11 @@
from os import remove, sep
from typing import Literal
from uuid import uuid1
from dateutil.relativedelta import relativedelta
from datetime import datetime
from app import app
from pyrogram import filters
from pyrogram.types import ReplyKeyboardRemove, InlineKeyboardMarkup, InlineKeyboardButton
from pyrogram.types import ReplyKeyboardRemove, InlineKeyboardMarkup, InlineKeyboardButton, ForceReply
from pyrogram.enums.parse_mode import ParseMode
from classes.holo_user import HoloUser
from modules.utils import all_locales, configGet, locale, logWrite
@@ -14,13 +17,11 @@ confirmation_1 = []
for pattern in all_locales("confirm", "keyboard"):
confirmation_1.append(pattern[0][0])
@app.on_message(~ filters.scheduled & filters.private & filters.command(confirmation_1, prefixes=[""]))
async def confirm_yes(app, msg):
async def confirm_yes(app, msg, kind: Literal["application", "sponsorship"] = "unknown"):
holo_user = HoloUser(msg.from_user)
if (holo_user.application_state()[0] == "fill") and (holo_user.application_state()[1] is True):
await msg.reply_text(locale("application_sent", "message"), reply_markup=ReplyKeyboardRemove())
if (kind == "application") or ((holo_user.application_state()[0] == "fill") and (holo_user.application_state()[1] is True)):
tmp_application = col_tmp.find_one({"user": holo_user.id, "type": "application"})
@@ -28,6 +29,11 @@ async def confirm_yes(app, msg):
logWrite(f"Application of {holo_user.id} is nowhere to be found.")
return
if tmp_application["sent"] is True:
return
await msg.reply_text(locale("application_sent", "message"), reply_markup=ReplyKeyboardRemove())
application_content = []
i = 1
@@ -47,7 +53,7 @@ async def confirm_yes(app, msg):
i += 1
if tmp_application["reapply"]:
await app.send_message(chat_id=configGet("admin_group"), text=(locale("reapply_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.last_name, msg.from_user.username, "\n".join(application_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(
await app.send_message(chat_id=configGet("admin_group"), text=(locale("reapply_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(application_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(text=str(locale("reapply_yes", "button")), callback_data=f"reapply_yes_{holo_user.id}")
@@ -59,7 +65,7 @@ async def confirm_yes(app, msg):
)
)
else:
await app.send_message(chat_id=configGet("admin_group"), text=(locale("application_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.last_name, msg.from_user.username, "\n".join(application_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(
await app.send_message(chat_id=configGet("admin_group"), text=(locale("application_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(application_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(text=str(locale("sub_yes", "button")), callback_data=f"sub_yes_{holo_user.id}")
@@ -81,19 +87,74 @@ async def confirm_yes(app, msg):
col_tmp.update_one({"user": holo_user.id, "type": "application"}, {"$set": {"sent": True}})
return
# configSet(["sent"], True, file=str(holo_user.id))
# configSet(["confirmed"], True, file=str(holo_user.id))
if (kind == "sponsorship") or ((holo_user.sponsorship_state()[0] == "fill") and (holo_user.sponsorship_state()[1] is True)):
tmp_sponsorship = col_tmp.find_one({"user": holo_user.id, "type": "sponsorship"})
if tmp_sponsorship is None:
logWrite(f"Sponsorship of {holo_user.id} is nowhere to be found.")
return
if tmp_sponsorship["sent"] is True:
return
await msg.reply_text(locale("sponsorship_sent", "message"), reply_markup=ReplyKeyboardRemove())
sponsorship_content = []
for question in tmp_sponsorship['sponsorship']:
if question == "expires":
sponsorship_content.append(f"{locale(f'question_{question}', 'message', 'sponsor_titles')} {tmp_sponsorship['sponsorship'][question].strftime('%d.%m.%Y')}")
elif question == "proof":
filename = uuid1()
with open(f"tmp{sep}{filename}.jpg", "wb") as f:
f.write(tmp_sponsorship['sponsorship']['proof'])
else:
sponsorship_content.append(f"{locale(f'question_{question}', 'message', 'sponsor_titles')} {tmp_sponsorship['sponsorship'][question]}")
await app.send_photo(chat_id=configGet("admin_group"), photo=f"tmp{sep}{filename}.jpg", caption=(locale("sponsor_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(sponsorship_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(text=str(locale("sponsor_yes", "button")), callback_data=f"sponsor_yes_{holo_user.id}")
],
[
InlineKeyboardButton(text=str(locale("sponsor_no", "button")), callback_data=f"sponsor_no_{holo_user.id}")
]
]
)
)
remove(f"tmp{sep}{filename}.jpg")
logWrite(f"User {holo_user.id} sent his sponsorship application and it will now be reviewed")
col_tmp.update_one({"user": holo_user.id, "type": "sponsorship"}, {"$set": {"sent": True}})
return
confirmation_2 = []
for pattern in all_locales("confirm", "keyboard"):
confirmation_2.append(pattern[1][0])
@app.on_message(~ filters.scheduled & filters.private & filters.command(confirmation_2, prefixes=[""]))
async def confirm_no(app, msg):
async def confirm_no(app, msg, kind: Literal["application", "sponsorship"] = "unknown"):
holo_user = HoloUser(msg.from_user)
if (holo_user.application_state()[0] == "fill") and (holo_user.application_state()[1] is True):
if (kind == "application") or ((holo_user.application_state()[0] == "fill") and (holo_user.application_state()[1] is True)):
holo_user.application_restart()
await welcome_pass(app, msg, once_again=True)
logWrite(f"User {msg.from_user.id} restarted the application due to typo in it")
return
if (kind == "sponsorship") or ((holo_user.sponsorship_state()[0] == "fill") and (holo_user.sponsorship_state()[1] is True)):
holo_user.sponsorship_restart()
await app.send_message(holo_user.id, locale(f"sponsor1", "message", locale=holo_user.locale), reply_markup=ForceReply(placeholder=str(locale(f"sponsor1", "force_reply", locale=holo_user.locale))))
logWrite(f"User {msg.from_user.id} restarted the sponsorship application due to typo in it")
return
# ==============================================================================================================================

View File

@@ -52,6 +52,7 @@ async def any_stage(app, msg):
if msg.text is not None:
await holo_user.application_next(msg.text, msg=msg)
await holo_user.sponsorship_next(msg.text, msg=msg)
# user_stage = configGet("stage", file=str(msg.from_user.id))

View File

@@ -1,6 +1,13 @@
from app import app
from pyrogram import filters
from classes.holo_user import HoloUser
@app.on_message(~ filters.scheduled & filters.photo & filters.private)
async def sponsor_proof(app, msg):
pass
if msg.via_bot is None:
holo_user = HoloUser(msg.from_user)
await holo_user.sponsorship_next(msg.text, msg=msg, photo=msg.photo)

View File

@@ -5,9 +5,10 @@ from app import app
from pyrogram.types import BotCommand, BotCommandScopeChat
from pyrogram.errors import bad_request_400
from pyrogram.enums.chat_members_filter import ChatMembersFilter
from classes.holo_user import HoloUser
from modules.utils import configGet, locale, logWrite
from dateutil.relativedelta import relativedelta
from modules.database import col_applications
from modules.database import col_applications, col_sponsorships
scheduler = AsyncIOScheduler()
@@ -47,6 +48,28 @@ if configGet("enabled", "scheduler", "birthdays"):
if configGet("enabled", "scheduler", "sponsorships"):
@scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "sponsorships"))
async def check_sponsors():
for entry in col_sponsorships.find({"sponsorship.expires": {"$lt": datetime.now()+timedelta(days=2)}}):
try:
tg_user = await app.get_users(entry["user"])
until_expiry = relativedelta(datetime.now(), entry["sponsorship"]["expires"]).days
await app.send_message( tg_user, locale("sponsorships_expires", "message").format(until_expiry) ) # type: ignore
logWrite(f"Notified user that sponsorship expires in {until_expiry} days")
except Exception as exp:
logWrite(f"Could not find user {entry['user']} notify about sponsorship expiry due to '{exp}'")
continue
for entry in col_sponsorships.find({"sponsorship.expires": {"$lt": datetime.now()}}):
try:
holo_user = HoloUser(entry["user"])
await app.send_message( entry["user"], locale("sponsorships_expired", "message") ) # type: ignore
await holo_user.reset_label(configGet("destination_group"))
try:
tg_user = await app.get_users(entry["user"])
logWrite(f"Notified user that sponsorship expires in {until_expiry} days")
except Exception as exp:
logWrite(f"Could not find user {entry['user']} notify about sponsorship expired due to '{exp}'")
except Exception as exp:
logWrite(f"Could not reset label of user {entry['user']} due to '{exp}'")
continue
logWrite("Sponsorships check performed")