Compare commits

...

3 Commits

Author SHA1 Message Date
b0b0f04a9b Added down time messages 2023-01-05 13:08:08 +01:00
9e009aea43 Minor naming improvements 2023-01-05 13:01:57 +01:00
42d00383bf Removed legacy 2023-01-05 13:01:18 +01:00
12 changed files with 33 additions and 130 deletions

View File

@ -54,7 +54,16 @@ if __name__ == "__main__":
app.start()
try:
app.send_message(configGet("owner"), f"Starting up with pid `{pid}`")
if path.exists(path.join(configGet("cache", "locations"), "shutdown_time")):
downtime = relativedelta(datetime.now(), datetime.fromtimestamp(jsonLoad(path.join(configGet("cache", "locations"), "shutdown_time"))))
if downtime.days >= 1:
app.send_message(configGet("owner"), locale("startup_downtime_days", "message").format(pid, downtime.days))
elif downtime.hours >= 1:
app.send_message(configGet("owner"), locale("startup_downtime_hours", "message").format(pid, downtime.hours))
else:
app.send_message(configGet("owner"), locale("startup_downtime_minutes", "message").format(pid, downtime.minutes))
else:
app.send_message(configGet("owner"), locale("startup", "message").format(pid))
except bad_request_400.PeerIdInvalid:
logWrite(f"Could not send startup message to bot owner. Perhaps user has not started the bot yet.")
@ -63,7 +72,7 @@ if __name__ == "__main__":
idle()
try:
app.send_message(configGet("owner"), f"Shutting with pid `{pid}`")
app.send_message(configGet("owner"), locale("shutdown", "message").format(pid))
except bad_request_400.PeerIdInvalid:
logWrite(f"Could not send shutdown message to bot owner. Perhaps user has not started the bot yet.")

View File

@ -38,7 +38,9 @@
"sponsor_got": "Отримано форму на спонсорство від `{0}`\n\nІм'я тг: `{1}`\nЮзернейм: @{2}\n\n**Дані форми:**\n{3}",
"shutdown": "Вимкнення бота з підом `{0}`",
"startup": "Запуск бота з підом `{0}`",
"startup_downtime": "Запуск бота з підом `{0}` (лежав {1})",
"startup_downtime_minutes": "Запуск бота з підом `{0}` (лежав {1} хв.)",
"startup_downtime_hours": "Запуск бота з підом `{0}` (лежав {1} год.)",
"startup_downtime_days": "Запуск бота з підом `{0}` (лежав {1} дн.)",
"approved": "Вітаємо! Твою анкету переглянули та підтвердили твоє право на вступ. Скористайся кнопкою під повідомленням щоб вступити до нашої лампової спільноти!",
"approved_joined": "Вітаємо! Твою анкету переглянули та підтвердили її правильність. Дякуємо за витрачений на заповнення час та гарного дня!",
"read_rules": "Будь ласка, прочитай ці правила перш ніж натискати на кнопку та приєднуватись до чату.",

View File

@ -11,7 +11,7 @@ from dateutil.relativedelta import relativedelta
from modules.database import col_applications
from modules import custom_filters
# Applications command =========================================================================================================
# Application command ==========================================================================================================
@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.command(["application"], prefixes=["/"]) & custom_filters.admin)
async def cmd_application(app: Client, msg: Message):
@ -55,42 +55,6 @@ async def cmd_application(app: Client, msg: Message):
logWrite(f"User {msg.from_user.id} requested application of {holo_user.id}")
await msg.reply_text(locale("contact", "message", locale=msg.from_user).format(holo_user.id, "\n".join(application_content), application_status), parse_mode=ParseMode.MARKDOWN, quote=should_quote(msg))
# if (path.exists(f"{configGet('data', 'locations')}{sep}users{sep}{msg.command[1]}.json") and jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{msg.command[1]}.json")["approved"]):
# user_id = int(msg.command[1])
# else:
# list_of_users = []
# async for m in app.get_chat_members(configGet("users", "groups"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]):
# list_of_users.append(m)
# user_id = list_of_users[0].user.id
# try:
# user_data = jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{user_id}.json")
# application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")[str(user_id)]
# application_content = []
# i = 1
# for question in configGet("application", file=str(msg.from_user.id)):
# if i == 2:
# age = relativedelta(datetime.now(), datetime.strptime(application['application']['2'], '%d.%m.%Y'))
# application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {application['application']['2']} ({age.years} р.)")
# else:
# application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {application['application'][question]}")
# i += 1
# if user_data["sent"]:
# if user_data["approved"]:
# application_status = locale("application_status_accepted", "message").format((await app.get_users(application["approved_by"])).first_name, datetime.fromtimestamp(application["approval_date"]).strftime("%d.%m.%Y, %H:%M"))
# elif application["rejected"]:
# application_status = locale("application_status_rejected", "message").format((await app.get_users(application["rejected_by"])).first_name, datetime.fromtimestamp(application["refusal_date"]).strftime("%d.%m.%Y, %H:%M"))
# else:
# application_status = locale("application_status_on_hold", "message")
# else:
# if user_data["approved"]:
# application_status = locale("application_status_accepted", "message").format((await app.get_users(application["approved_by"])).first_name, datetime.fromtimestamp(application["approval_date"]).strftime("%d.%m.%Y, %H:%M"))
# elif application["rejected"]:
# application_status = locale("application_status_rejected", "message").format((await app.get_users(application["rejected_by"])).first_name, datetime.fromtimestamp(application["refusal_date"]).strftime("%d.%m.%Y, %H:%M"))
# else:
# application_status = locale("application_status_not_send", "message")
# logWrite(f"User {msg.from_user.id} requested application of {user_id}")
# await msg.reply_text(locale("contact", "message").format(str(user_id), "\n".join(application_content), application_status), quote=should_quote(msg))
except IndexError:
await msg.reply_text(locale("application_invalid_syntax", "message", locale=msg.from_user), quote=should_quote(msg))

View File

@ -6,9 +6,11 @@ from modules.utils import should_quote, logWrite, locale
from modules.database import col_tmp, col_spoilers
from modules import custom_filters
# Cancel command ===============================================================================================================
@app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.command("cancel", prefixes=["/"]))
async def command_cancel(app: Client, msg: Message):
col_tmp.delete_many( {"user": msg.from_user.id} )
col_spoilers.delete_many( {"user": msg.from_user.id, "completed": False} )
await msg.reply_text(locale("cancel", "message", locale=msg.from_user), quote=should_quote(msg))
logWrite(f"Cancelling all ongoing tmp operations for {msg.from_user.id}")
logWrite(f"Cancelling all ongoing tmp operations for {msg.from_user.id}")
# ==============================================================================================================================

View File

@ -9,8 +9,9 @@ from classes.holo_user import HoloUser, UserNotFoundError, UserInvalidError
from modules.utils import jsonLoad, should_quote, logWrite, locale, download_tmp, create_tmp, find_user
from modules import custom_filters
# Identify command =============================================================================================================
@app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.command("identify", prefixes=["/"]) & custom_filters.admin)
async def command_identify(app: Client, msg: Message):
async def cmd_identify(app: Client, msg: Message):
if len(msg.command) != 2:
await msg.reply_text(locale("identify_invalid_syntax", "message", locale=msg.from_user))
@ -60,4 +61,5 @@ async def command_identify(app: Client, msg: Message):
quote=should_quote(msg)
)
logWrite(f"User {msg.from_user.id} identified user {holo_user.id}")
logWrite(f"User {msg.from_user.id} identified user {holo_user.id}")
# ==============================================================================================================================

View File

@ -6,6 +6,7 @@ from modules.utils import locale, should_quote, find_user
from classes.holo_user import HoloUser, LabelTooLongError
from modules import custom_filters
# Label command ================================================================================================================
@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.command(["label"], prefixes=["/"]) & custom_filters.admin)
async def cmd_label(app: Client, msg: Message):
@ -34,4 +35,5 @@ async def cmd_label(app: Client, msg: Message):
await msg.reply_text(f"Setting **{target.id}**'s label to **{label}**...", quote=should_quote(msg))
else:
await msg.reply_text(f"User not found")
await msg.reply_text(f"User not found")
# ==============================================================================================================================

View File

@ -38,7 +38,6 @@ async def cmd_nearby(app: Client, msg: Message):
# Find all users registered in the area provided
output = []
applications_nearby = col_applications.find( {"application.3.location": { "$nearSphere": {"$geometry": {"type": "Point", "coordinates": [location[0], location[1]]}, "$maxDistance": configGet("search_radius")*1000} } } )
# {"application": {"3": {"location": {"$near": { "$geometry": { "type": "Point", "coordinates": location }, "$maxDistance": 30000 }} } } } )
for entry in applications_nearby:
if not entry["user"] == msg.from_user.id:
@ -56,18 +55,4 @@ async def cmd_nearby(app: Client, msg: Message):
await msg.reply_text(locale("nearby_result", "message", locale=holo_user).format("\n".join(output)), quote=should_quote(msg))
else:
await msg.reply_text(locale("nearby_empty", "message", locale=holo_user), quote=should_quote(msg))
# 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

@ -1,21 +1,24 @@
from app import app
from os import getpid
from os import getpid, makedirs, path
from sys import exit
from time import time
from pyrogram import filters
from pyrogram.types import Message
from pyrogram.client import Client
from modules.utils import locale, logWrite, should_quote
from modules.utils import configGet, jsonSave, locale, logWrite, should_quote
from modules.scheduled import scheduler
from modules import custom_filters
pid = getpid()
# Shutdown command =============================================================================================================
# Reboot command ===============================================================================================================
@app.on_message(custom_filters.enabled_general & ~filters.scheduled & filters.private & filters.command(["kill", "die", "reboot"], prefixes=["/"]) & custom_filters.admin)
async def cmd_kill(app: Client, msg: Message):
logWrite(f"Shutting down bot with pid {pid}")
await msg.reply_text(locale("shutdown", "message", locale=msg.from_user).format(pid), quote=should_quote(msg))
scheduler.shutdown()
makedirs(configGet("cache", "locations"), exist_ok=True)
jsonSave({"timestamp": time()}, path.join(configGet("cache", "locations"), "shutdown_time"))
exit()
# ==============================================================================================================================

View File

@ -9,9 +9,9 @@ from modules import custom_filters
pid = getpid()
# Shutdown command =============================================================================================================
# Reset commands command =======================================================================================================
@app.on_message(custom_filters.enabled_general & ~filters.scheduled & filters.private & filters.command(["resetcommands"], prefixes=["/"]) & custom_filters.admin)
async def cmd_kill(app: Client, msg: Message):
async def cmd_resetcommands(app: Client, msg: Message):
if msg.from_user.id == configGet("owner"):

View File

@ -93,9 +93,6 @@ async def confirm_yes(app: Client, msg: Message, kind: Literal["application", "s
return
# configSet(["sent"], True, file=str(holo_user.id))
# configSet(["confirmed"], True, file=str(holo_user.id))
if configGet("enabled", "features", "sponsorships") is True:
if (kind == "sponsorship") or ((holo_user.sponsorship_state()[0] == "fill") and (holo_user.sponsorship_state()[1] is True)):

View File

@ -6,7 +6,6 @@ from pyrogram.client import Client
from classes.holo_user import HoloUser
from modules.utils import configGet, logWrite, locale, all_locales
from modules.database import col_messages, col_spoilers
from bson import ObjectId
async def message_involved(msg: Message) -> bool:
message = col_messages.find_one({"destination.id": msg.reply_to_message.id, "destination.chat": msg.reply_to_message.chat.id})
@ -47,9 +46,6 @@ async def any_stage(app: Client, msg: Message):
adm_context=await isAnAdmin(msg.from_user.id)
)
# await msg.reply_text(locale("message_sent", "message"), quote=should_quote(msg))
# col_messages.insert_one({"origin": {"chat": msg.chat.id, "id": msg.id}, "destination": {"chat": new_message.chat.id, "id": new_message.id}})
return
if msg.text is not None:
@ -102,63 +98,6 @@ async def any_stage(app: Client, msg: Message):
await msg.reply_text(locale("spoiler_using_description", "message", locale=msg.from_user).format(msg.text), reply_markup=ReplyKeyboardRemove())
await msg.reply_text(locale("spoiler_ready", "message", locale=msg.from_user), quote=False, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("spoiler_send", "button", locale=msg.from_user), switch_inline_query=f"spoiler:{spoiler['_id'].__str__()}")]]))
# user_stage = configGet("stage", file=str(msg.from_user.id))
# if user_stage == 1:
# await msg.reply_text(locale(f"question{user_stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage+1}", "force_reply"))))
# logWrite(f"User {msg.from_user.id} completed stage {user_stage} of application")
# configSet(["application", str(user_stage)], str(msg.text), file=str(msg.from_user.id))
# configSet(["stage"], user_stage+1, file=str(msg.from_user.id))
# elif user_stage == 2:
# try:
# configSet(["application", str(user_stage)], str(msg.text), file=str(msg.from_user.id))
# input_dt = datetime.strptime(msg.text, "%d.%m.%Y")
# if datetime.now() <= input_dt:
# logWrite(f"User {msg.from_user.id} failed stage {user_stage} due to joking")
# await msg.reply_text(locale("question2_joke", "message"), reply_markup=ForceReply(placeholder=str(locale("question2", "force_reply"))))
# elif ((datetime.now() - input_dt).days) < ((datetime.now() - datetime.now().replace(year=datetime.now().year - configGet("age_allowed"))).days):
# logWrite(f"User {msg.from_user.id} failed stage {user_stage} due to being underage")
# await msg.reply_text(locale("question2_underage", "message").format(str(configGet("age_allowed"))), reply_markup=ForceReply(placeholder=str(locale("question2", "force_reply"))))
# else:
# logWrite(f"User {msg.from_user.id} completed stage {user_stage} of application")
# await msg.reply_text(locale(f"question{user_stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage+1}", "force_reply"))))
# configSet(["stage"], user_stage+1, file=str(msg.from_user.id))
# except ValueError:
# logWrite(f"User {msg.from_user.id} failed stage {user_stage} due to sending invalid date format")
# await msg.reply_text(locale(f"question2_invalid", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage}", "force_reply"))))
# else:
# if user_stage <= 9:
# logWrite(f"User {msg.from_user.id} completed stage {user_stage} of application")
# await msg.reply_text(locale(f"question{user_stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage+1}", "force_reply"))))
# configSet(["application", str(user_stage)], str(msg.text), file=str(msg.from_user.id))
# configSet(["stage"], user_stage+1, file=str(msg.from_user.id))
# else:
# if not configGet("sent", file=str(msg.from_user.id)):
# if not configGet("confirmed", file=str(msg.from_user.id)):
# configSet(["application", str(user_stage)], str(msg.text), file=str(msg.from_user.id))
# application_content = []
# i = 1
# for question in configGet("application", file=str(msg.from_user.id)):
# application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {configGet('application', file=str(msg.from_user.id))[question]}")
# i += 1
# await msg.reply_text(locale("confirm", "message").format("\n".join(application_content)), reply_markup=ReplyKeyboardMarkup(locale("confirm", "keyboard"), resize_keyboard=True))
# #configSet("sent", True, file=str(msg.from_user.id))
# #configSet("application_date", int(time()), file=str(msg.from_user.id))
# else:
# if not configGet("approved", file=str(msg.from_user.id)) and not configGet("rejected", file=str(msg.from_user.id)):
# await msg.reply_text(locale("already_sent", "message"))
# else:
# if not configGet("approved", file=str(msg.from_user.id)) and not configGet("rejected", file=str(msg.from_user.id)):
# await msg.reply_text(locale("already_sent", "message"))
@app.on_message(~ filters.scheduled & filters.group)
async def message_in_group(app: Client, msg: Message):

View File

@ -31,8 +31,6 @@ async def welcome_pass(app: Client, msg: Message, once_again: bool = True) -> No
logWrite(f"User {msg.from_user.id} confirmed starting the application")
await msg.reply_text(locale("question1", "message", locale=msg.from_user), reply_markup=ForceReply(placeholder=locale("question1", "force_reply", locale=msg.from_user)))
# configSet(["stage"], 1, file=str(msg.from_user.id))
# configSet(["sent"], False, file=str(msg.from_user.id))
welcome_2 = []
for pattern in all_locales("welcome", "keyboard"):