Compare commits

...

8 Commits

Author SHA1 Message Date
Profitroll
af862a3454 Added messages to sponsor's locale 2022-12-23 01:49:38 +01:00
Profitroll
1eb98750a7 Changed sponsorship locale 2022-12-23 01:44:21 +01:00
Profitroll
eecb71a91e Updated label_set 2022-12-23 01:44:07 +01:00
Profitroll
426b1550f6 Initialized /cancel command 2022-12-23 01:40:23 +01:00
Profitroll
0302d8c1ae Removed unused 2022-12-23 01:40:07 +01:00
Profitroll
5a6a96d3f9 Delete sponsorships on expiry 2022-12-22 22:14:35 +01:00
Profitroll
12da1b2376 Added LabelTooLongError() and changed names 2022-12-22 22:11:36 +01:00
Profitroll
7db8c9ac5c Fixed label length on set 2022-12-22 22:11:15 +01:00
8 changed files with 48 additions and 32 deletions

View File

@ -68,6 +68,11 @@ class UserInvalidError(Exception):
self.user = user
super().__init__(f"Could not find HoloUser by using {type(self.user)} as an input type")
class LabelTooLongError(Exception):
def __init__(self, label: str) -> None:
self.label = label
super().__init__(f"Could not set label to '{label}' because it is {len(label)} characters long (16 is maximum)")
class HoloUser():
"""This object represents a user of HoloChecker bot.
It is primarily used to interact with a database in a more python-friendly way,
@ -270,20 +275,22 @@ class HoloUser():
logWrite(f"Could not notify admin about failure when sending message! Admin has never interacted with bot!")
await context.reply_text(locale("message_error", "message"), quote=should_quote(context))
async def set_label(self, chat: Chat, label: str) -> None:
async def label_set(self, chat: Chat, label: str) -> None:
"""Set label in destination group
### Args:
* chat (`Chat`): Telegram chat
* label (`str`): Label you want to set
"""
if len(label) > 16:
raise LabelTooLongError(label)
self.label = label
self.set("label", label)
await app.promote_chat_member(configGet("destination_group"), self.id)
await app.promote_chat_member(configGet("destination_group"), self.id, privileges=ChatPrivileges(can_pin_messages=True, can_manage_video_chats=True))
if not await isAnAdmin(self.id):
await app.set_administrator_title(configGet("destination_group"), self.id, label)
async def reset_label(self, chat: Chat) -> None:
async def label_reset(self, chat: Chat) -> None:
"""Reset label in destination group
### Args:
@ -294,7 +301,9 @@ class HoloUser():
await app.set_administrator_title(configGet("destination_group"), self.id, "")
if not await isAnAdmin(self.id):
await app.promote_chat_member(configGet("destination_group"), self.id, privileges=ChatPrivileges(
can_manage_chat=False
can_manage_chat=False,
can_pin_messages=False,
can_manage_video_chats=False
))
def application_state(self) -> tuple[Literal["none", "fill", "approved", "rejected"], bool]:
@ -498,9 +507,12 @@ class HoloUser():
await msg.reply_text(locale(f"sponsor{stage+1}", "message", locale=self.locale), reply_markup=ForceReply(placeholder=str(locale(f"sponsor{stage+1}", "force_reply", locale=self.locale))))
elif stage == 4:
if len(query) > 16:
await msg.reply_text(locale("label_too_long", "message"))
return
progress["sponsorship"]["label"] = query
col_tmp.update_one({"user": {"$eq": self.id}, "type": {"$eq": "sponsorship"}}, {"$set": {"sponsorship": progress["sponsorship"], "complete": True}})
await msg.reply_text("Sponsorship application is filled. Want to send it?", reply_markup=ReplyKeyboardMarkup(locale("confirm", "keyboard", locale=self.locale), resize_keyboard=True))
await msg.reply_text(locale("sponsor_confirm", "message"), reply_markup=ReplyKeyboardMarkup(locale("confirm", "keyboard", locale=self.locale), resize_keyboard=True))
else:
return

View File

@ -12,6 +12,7 @@ makedirs(f'{configGet("cache", "locations")}{sep}avatars', exist_ok=True)
# Importing
from modules.commands.application import *
from modules.commands.applications import *
from modules.commands.cancel import *
from modules.commands.label import *
from modules.commands.message import *
from modules.commands.nearby import *

View File

@ -20,7 +20,8 @@
"question3_found": "Використовую наступний результат:\n• {0} ({1})",
"question3_error": "⚠️ **Сталась помилка**\nНе вдалось отримати географічну мітку. Розробника повідомлено про цю помилку. Будь ласка, спробуйте ще раз.",
"question3_traceback": "⚠️ **Сталась помилка**\nПомилка отримання геокодингу для `{0}`\nПомилка: `{1}`\n\nTraceback:\n```\n{2}\n```",
"sponsorship_apply": " Розпочато заповнення форми на отримання бонусів за платну підписку на холодівчат.",
"sponsorship_apply": " Оформіть платну підписку на когось з Холо, заповніть форму та отримайте особливу роль в якості винагороди!",
"sponsorship_applying": " Розпочато заповнення форми на отримання бонусів за платну підписку на холодівчат.",
"sponsor1": "На яку саме дівчину платна підписка?",
"sponsor2": "До якої дати (`ДД.ММ.РРРР`) підписка?",
"sponsor2_invalid": "Будь ласка, введи дату формату `ДД.ММ.РРРР`",
@ -29,6 +30,7 @@
"sponsor4": "Яку роль ти бажаєш отримати?",
"sponsorship_application_empty": "❌ **Дія неможлива**\nУ тебе немає заповненої та схваленої анкети. Заповни таку за допомогою /reapply та спробуй ще раз після її підтвердження.",
"confirm": "Супер, дякуємо!\n\nБудь ласка, перевір правильність даних:\n{0}\n\nВсе правильно?",
"sponsor_confirm": "Здається, це все. Перевір чи все правильно та жмакни кнопку на клавіатурі щоб продовжити.",
"application_sent": "Дякуємо! Ми надіслали твою анкетку на перевірку. Ти отримаєш повідомлення як тільки її перевірять та приймуть рішення. До тих пір від тебе більше нічого не потребується. Гарного дня! :)",
"sponsorship_sent": "Дякуємо! Ми надіслали форму на перевірку. Ти отримаєш повідомлення як тільки її перевірять та приймуть рішення. Гарного дня! :)",
"application_got": "Отримано анкету від `{0}`\n\nІм'я тг: `{1}`\nЮзернейм: @{2}\n\n**Дані анкети:**\n{3}",
@ -87,6 +89,7 @@
"joined_false_link": "Користувач **{0}** (`{1}`) приєднався до групи не за своїм посиланням",
"sponsorships_expires": "⚠️ **Нагадування**\nНадана платна підписка припинить діяти **за {0} д**. Будь ласка, оновіть дані про неї командою /sponsorship інакше роль буде втрачено!",
"sponsorships_expired": "⚠️ **Нагадування**\nТермін дії вказаної підписки сплив. Для повторного отримання ролі користуйся командою /sponsorship.",
"label_too_long": "Довжина назви ролі не повинна перевищувати 16 символів",
"voice_message": [
"why are u gae",
"руки відірвало? пиши як людина",
@ -188,7 +191,9 @@
"rules_home": " Показано головну правил",
"rules_additional": " Показано додаткові правила",
"reapply_stopped": " Перервано заповнення анкети",
"sponsor_started": " Заповнення форми розпочато"
"sponsor_started": " Заповнення форми розпочато",
"sponsor_accepted": "✅ Форму {0} схвалено",
"sponsor_rejected": "❌ Форму {0} відхилено"
},
"inline": {
"forbidden": {

View File

@ -19,7 +19,7 @@ async def callback_query_sponsor_apply(app, clb):
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.message.edit(text=locale("sponsorship_applying", "message"), reply_markup=InlineKeyboardMarkup(edited_markup))
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)
@ -34,18 +34,18 @@ async def callback_query_sponsor_yes(app, clb):
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"]}})
col_sponsorships.update_one({"user": holo_user.id}, {"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"])
await holo_user.label_set(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)
await clb.answer(text=locale("sponsor_accepted", "callback").format(fullclb[2]), show_alert=False)
@app.on_callback_query(filters.regex("sponsor_no_[\s\S]*"))
async def callback_query_sponsor_no(app, clb):
@ -62,4 +62,4 @@ async def callback_query_sponsor_no(app, clb):
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)
await clb.answer(text=locale("sponsor_rejected", "callback").format(fullclb[2]), show_alert=False)

View File

@ -0,0 +1,7 @@
from app import app
from pyrogram import filters
from modules.utils import should_quote
@app.on_message(~ filters.scheduled & filters.command("cancel", prefixes=["/"]))
async def command_cancel(app, msg):
await msg.reply_text("Command exists.", quote=should_quote(msg))

View File

@ -1,7 +1,7 @@
from app import app, isAnAdmin
from pyrogram import filters
from modules.utils import should_quote, find_user
from classes.holo_user import HoloUser
from modules.utils import locale, should_quote, find_user
from classes.holo_user import HoloUser, LabelTooLongError
@app.on_message(~ filters.scheduled & filters.private & filters.command(["label"], prefixes=["/"]))
async def cmd_label(app, msg):
@ -21,11 +21,15 @@ async def cmd_label(app, msg):
label = " ".join(msg.command[2:])
if label.lower() == "reset":
await target.reset_label(msg.chat)
await target.label_reset(msg.chat)
await msg.reply_text(f"Resetting **{target.id}**'s label...", quote=should_quote(msg))
else:
await target.set_label(msg.chat, label)
try:
await target.label_set(msg.chat, label)
except LabelTooLongError:
await msg.reply_text(locale("label_too_long", "message"))
return
await msg.reply_text(f"Setting **{target.id}**'s label to **{label}**...", quote=should_quote(msg))
else:

View File

@ -1,4 +1,3 @@
from datetime import datetime
from app import app, isAnAdmin
from pyrogram import filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
@ -12,17 +11,4 @@ async def cmd_sponsorship(app, msg):
await msg.reply_text(locale("sponsorship_apply", "message"), reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text=str(locale("sponsor_apply", "button")), callback_data=f"sponsor_apply_{msg.from_user.id}")]]), quote=should_quote(msg))
else:
await msg.reply_text(locale("sponsorship_application_empty", "message"))
# if not path.exists(f"{configGet('data', 'locations')}{sep}sponsors{sep}{msg.from_user.id}.json"):
# jsonSave(jsonLoad(f"{configGet('data', 'locations')}{sep}sponsor_default.json"), f"{configGet('data', 'locations')}{sep}sponsors{sep}{msg.from_user.id}.json")
# sponsor = jsonLoad(f"{configGet('data', 'locations')}{sep}sponsors{sep}{msg.from_user.id}.json")
# if sponsor["approved"]:
# if sponsor["expires"] is not None:
# if datetime.strptime(sponsor["expires"], "%d.%m.%Y") > datetime.now():
# await msg.reply_text(f"You have an active sub til **{sponsor['expires']}**.")
# else:
# await msg.reply_text(f"Your sub expired {int((datetime.now()-datetime.strptime(sponsor['expires'], '%d.%m.%Y')).days)} days ago.")
# elif sponsor["approved"]:
# await msg.reply_text(f"Your sub expiration date is not valid.")
# else:
# await msg.reply_text(f"You have no active subscription.")
# ==============================================================================================================================

View File

@ -61,10 +61,11 @@ if configGet("enabled", "scheduler", "sponsorships"):
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"))
await holo_user.label_reset(configGet("destination_group"))
col_sponsorships.find_one_and_delete({"user": holo_user.id})
try:
tg_user = await app.get_users(entry["user"])
logWrite(f"Notified user that sponsorship expires in {until_expiry} days")
logWrite(f"Notified user that sponsorship expired")
except Exception as exp:
logWrite(f"Could not find user {entry['user']} notify about sponsorship expired due to '{exp}'")
except Exception as exp: