10 Commits

Author SHA1 Message Date
da3dd3a2fe Changed debug logging logic 2023-01-09 12:39:39 +01:00
3e166a3fca Fixed inline query caching 2023-01-09 12:21:21 +01:00
d090b18655 Added additional caching message on debug 2023-01-09 12:11:29 +01:00
e2d28f442c Changed inline caching time 2023-01-09 12:10:07 +01:00
496240c48b Fixed id attribute in sponsorships scheduler 2023-01-09 11:39:24 +01:00
Profitroll
0bf5ae70eb Improved inline query usage filters 2023-01-07 10:20:58 +01:00
Profitroll
bcaf80e2e1 Fixed reply_document() issue 2023-01-07 00:38:53 +01:00
Profitroll
21bf460b28 Fixes + improved logging 2023-01-07 00:38:35 +01:00
Profitroll
a4bbb837d7 Added delay for label setting 2023-01-06 21:27:47 +01:00
Profitroll
1a438fc32e Fixed api method 2023-01-06 21:27:32 +01:00
7 changed files with 65 additions and 49 deletions

View File

@@ -1,4 +1,5 @@
from datetime import datetime
from asyncio import sleep
from traceback import format_exc
from app import app, isAnAdmin
from typing import Any, List, Literal, Union
@@ -123,11 +124,11 @@ class HoloUser():
# Check if any text available and log message sending
if text is not None:
logWrite(f"{context.from_user.id} sent message '{text}' to {self.id}")
logWrite(f"{context.from_user.id} sent message '{text}' to {self.id} (source message: {context.id})")
elif caption is not None:
logWrite(f"{context.from_user.id} sent message '{caption}' to {self.id}")
logWrite(f"{context.from_user.id} sent message '{caption}' to {self.id} (source message: {context.id})")
else:
logWrite(f"{context.from_user.id} sent message to {self.id}")
logWrite(f"{context.from_user.id} sent message to {self.id} (source message: {context.id})")
# Add notices for admin or user
if text is not None:
@@ -164,7 +165,7 @@ class HoloUser():
elif file is not None:
if isinstance(file, Document):
file = file.file_id
new_message = await origin.reply_document(file, caption=caption, quote=True)
new_message = await origin.reply_cached_media(file, caption=caption, quote=True)
elif animation is not None:
if isinstance(animation, Animation):
animation = animation.file_id
@@ -189,7 +190,7 @@ class HoloUser():
elif file is not None:
if isinstance(file, Document):
file = file.file_id
new_message = await app.send_document(self.id, file, caption=caption)
new_message = await app.send_cached_media(self.id, file, caption=caption)
elif animation is not None:
if isinstance(animation, Animation):
animation = animation.file_id
@@ -227,6 +228,7 @@ class HoloUser():
try:
await app.promote_chat_member(configGet("users", "groups"), self.id, privileges=ChatPrivileges(can_pin_messages=True, can_manage_video_chats=True))
if not await isAnAdmin(self.id):
await sleep(0.5)
await app.set_administrator_title(configGet("users", "groups"), self.id, label)
self.set("label", label)
except Exception as exp:

View File

@@ -34,14 +34,21 @@ async def cmd_reapply(app: Client, msg: Message):
await welcome_pass(app, msg, once_again=True)
else:
await msg.reply_text(locale("reapply_left_chat", "message", locale=holo_user), reply_markup=InlineKeyboardMarkup([
[
InlineKeyboardButton(locale("reapply_old_one", "button", locale=holo_user), f"reapply_old_{msg.id}")
],
[
InlineKeyboardButton(locale("reapply_new_one", "button", locale=holo_user), f"reapply_new_{msg.id}")
]
]))
if holo_user.sponsorship_state()[1] is True:
await msg.reply_text(locale("reapply_left_chat", "message", locale=holo_user), reply_markup=InlineKeyboardMarkup([
[
InlineKeyboardButton(locale("reapply_old_one", "button", locale=holo_user), f"reapply_old_{msg.id}")
],
[
InlineKeyboardButton(locale("reapply_new_one", "button", locale=holo_user), f"reapply_new_{msg.id}")
]
]))
else:
holo_user.application_restart(reapply=True)
await welcome_pass(app, msg, once_again=True)
else:

View File

@@ -24,42 +24,35 @@ async def cmd_resetcommands(app: Client, msg: Message):
if entry.endswith(".json"):
valid_locales.append(".".join(entry.split(".")[:-1]))
if configGet("debug") is True:
logWrite(f'Resetting commands in groups {configGet("admin", "groups")} and {configGet("users", "groups")}')
logWrite(f'Resetting commands in groups {configGet("admin", "groups")} and {configGet("users", "groups")}', debug=True)
await app.delete_bot_commands(scope=BotCommandScopeChat(chat_id=configGet("admin", "groups")))
await app.delete_bot_commands(scope=BotCommandScopeChat(chat_id=configGet("users", "groups")))
for admin in configGet("admins"):
try:
if configGet("debug") is True:
logWrite(f'Resetting commands for admin {admin}')
logWrite(f'Resetting commands for admin {admin}', debug=True)
await app.delete_bot_commands(scope=BotCommandScopeChat(chat_id=admin))
except bad_request_400.PeerIdInvalid:
pass
try:
if configGet("debug") is True:
logWrite(f'Resetting commands for owner {configGet("owner")}')
logWrite(f'Resetting commands for owner {configGet("owner")}', debug=True)
for lc in valid_locales:
if configGet("debug") is True:
logWrite(f'Resetting commands for owner {configGet("owner")} [{lc}]')
logWrite(f'Resetting commands for owner {configGet("owner")} [{lc}]', debug=True)
await app.delete_bot_commands(scope=BotCommandScopeChat(chat_id=configGet("owner")), language_code=lc)
await app.delete_bot_commands(scope=BotCommandScopeChat(chat_id=configGet("owner")))
except bad_request_400.PeerIdInvalid:
pass
for lc in valid_locales:
if configGet("debug") is True:
logWrite(f'Resetting commands for locale {lc}')
logWrite(f'Resetting commands for locale {lc}', debug=True)
await app.delete_bot_commands(scope=BotCommandScopeDefault(), language_code=lc)
if configGet("debug") is True:
logWrite(f'Resetting default commands')
logWrite(f'Resetting default commands', debug=True)
await app.delete_bot_commands()
await msg.reply_text("OK", quote=should_quote(msg))
if configGet("debug") is True:
logWrite(str(await app.get_bot_commands()))
logWrite(str(await app.get_bot_commands(scope=BotCommandScopeChat(chat_id=configGet("owner")))))
logWrite(str(await app.get_bot_commands()), debug=True)
logWrite(str(await app.get_bot_commands(scope=BotCommandScopeChat(chat_id=configGet("owner")))), debug=True)
# ==============================================================================================================================

View File

@@ -33,13 +33,13 @@ async def cmd_start(app: Client, msg: Message):
try:
spoiler = col_spoilers.find_one( {"_id": ObjectId(msg.command[1])} )
if spoiler["photo"] is not None:
await msg.reply_document(spoiler["photo"], caption=spoiler["caption"])
await msg.reply_cached_media(spoiler["photo"], caption=spoiler["caption"])
if spoiler["video"] is not None:
await msg.reply_cached_media(spoiler["video"], caption=spoiler["caption"])
if spoiler["animation"] is not None:
await msg.reply_cached_media(spoiler["animation"], caption=spoiler["caption"])
if spoiler["document"] is not None:
await msg.reply_document(spoiler["document"], caption=spoiler["caption"])
await msg.reply_cached_media(spoiler["document"], caption=spoiler["caption"])
if spoiler["text"] is not None:
await msg.reply_text(spoiler["text"])
except InvalidId:

View File

@@ -117,7 +117,7 @@ async def confirm_yes(app: Client, msg: Message, kind: Literal["application", "s
else:
sponsorship_content.append(f"{locale(f'question_{question}', 'message', 'sponsor_titles')} {tmp_sponsorship['sponsorship'][question]}")
await app.send_cached_media(chat_id=configGet("admin", "groups"), photo=tmp_sponsorship["sponsorship"]["proof"], 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(
await app.send_cached_media(configGet("admin", "groups"), tmp_sponsorship["sponsorship"]["proof"], 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}")

View File

@@ -11,7 +11,8 @@ from pyrogram.enums.chat_members_filter import ChatMembersFilter
from dateutil.relativedelta import relativedelta
from classes.errors.holo_user import UserNotFoundError, UserInvalidError
from classes.holo_user import HoloUser
from modules.utils import configGet, locale
from modules.logging import logWrite
from modules.utils import configGet, jsonLoad, locale
from modules.database import col_applications, col_spoilers
from bson.objectid import ObjectId
from bson.errors import InvalidId
@@ -64,22 +65,33 @@ async def inline_answer(client: Client, inline_query: InlineQuery):
)
return
results_forbidden = [
InlineQueryResultArticle(
title=locale("title", "inline", "forbidden", locale=inline_query.from_user),
input_message_content=InputTextMessageContent(
locale("message_content", "inline", "forbidden", locale=inline_query.from_user)
),
description=locale("description", "inline", "forbidden", locale=inline_query.from_user)
)
]
try:
holo_user = HoloUser(inline_query.from_user)
except (UserNotFoundError, UserInvalidError):
logWrite(f"Could not find application of {inline_query.from_user.id}, ignoring inline query", debug=True)
await inline_query.answer(
results=[
InlineQueryResultArticle(
title=locale("title", "inline", "forbidden", locale=inline_query.from_user),
input_message_content=InputTextMessageContent(
locale("message_content", "inline", "forbidden", locale=inline_query.from_user)
),
description=locale("description", "inline", "forbidden", locale=inline_query.from_user)
)
]
results=results_forbidden
)
return
if path.exists(path.join(configGet("cache", "locations"), "group_members")) and (inline_query.from_user.id not in jsonLoad(path.join(configGet("cache", "locations"), "group_members"))):
if path.exists(path.join(configGet("cache", "locations"), "admins")) and (inline_query.from_user.id not in jsonLoad(path.join(configGet("cache", "locations"), "admins"))):
logWrite(f"{inline_query.from_user.id} is not an admin and not in members group, ignoring inline query", debug=True)
await inline_query.answer(
results=results_forbidden
)
return
if holo_user.application_approved() or (await isAnAdmin(holo_user.id) is True):
max_results = configGet("inline_preview_count") if inline_query.query != "" else 200
@@ -161,5 +173,6 @@ async def inline_answer(client: Client, inline_query: InlineQuery):
await inline_query.answer(
results=results,
cache_time=10
)
cache_time=10,
is_personal=True
)

View File

@@ -22,8 +22,9 @@ if configGet("enabled", "scheduler", "cache_members"):
list_of_users = []
async for member in app.get_chat_members(configGet("users", "groups")):
list_of_users.append(member.user.id)
makedirs("cache", exist_ok=True)
makedirs(configGet("cache", "locations"), exist_ok=True)
jsonSave(list_of_users, path.join(configGet("cache", "locations"), "group_members"))
logWrite("User group caching performed", debug=True)
if configGet("enabled", "scheduler", "cache_admins"):
@scheduler.scheduled_job(trigger="interval", seconds=configGet("interval", "scheduler", "cache_admins"))
@@ -31,8 +32,9 @@ if configGet("enabled", "scheduler", "cache_admins"):
list_of_users = []
async for member in app.get_chat_members(configGet("admin", "groups")):
list_of_users.append(member.user.id)
makedirs("cache", exist_ok=True)
makedirs(configGet("cache", "locations"), exist_ok=True)
jsonSave(list_of_users, path.join(configGet("cache", "locations"), "admins"))
logWrite("Admin group caching performed", debug=True)
# Cache the avatars of group members
if configGet("enabled", "scheduler", "cache_avatars"):
@@ -76,7 +78,7 @@ if configGet("enabled", "features", "sponsorships") is True:
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
await app.send_message( tg_user.id, 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}'")
@@ -155,8 +157,7 @@ async def commands_register():
enabled = True
if enabled is False:
if configGet("debug") is True:
logWrite(f"Not registering {command} at all")
logWrite(f"Not registering {command} at all", debug=True)
continue
for permission in config_commands[command]["permissions"]:
@@ -219,4 +220,4 @@ async def commands_register():
if configGet("debug") is True:
print(commands, flush=True)
logWrite(f"Complete commands registration:\n{dumps(commands_raw, indent=4, ensure_ascii=False, encode_html_chars=False)}")
logWrite(f"Complete commands registration:\n{dumps(commands_raw, indent=4, ensure_ascii=False, encode_html_chars=False)}", debug=True)