Changed the way how commands work

This commit is contained in:
Profitroll 2023-01-03 21:36:26 +01:00
parent ff95d9556d
commit 3d4dd29205
4 changed files with 338 additions and 94 deletions

132
README.md
View File

@ -60,6 +60,23 @@ You can see config file with all the comments below:
"size": 512, "size": 512,
"location": "logs" "location": "logs"
}, },
"features": {
"applications": {
"enabled": true
},
"sponsorships": {
"enabled": true
},
"warnings": {
"enabled": false
},
"invites_check": {
"enabled": true
},
"dinovoice": {
"enabled": false
}
},
"scheduler": { "scheduler": {
"birthdays": { "birthdays": {
"time": 9, "time": 9,
@ -85,6 +102,119 @@ You can see config file with all the comments below:
"locations": { "locations": {
"cache": "cache", "cache": "cache",
"locale": "locale" "locale": "locale"
},
"commands": {
"rules": {
"permissions": [
"users",
"admins"
],
"modules": [
"general"
]
},
"cancel": {
"permissions": [
"users",
"admins"
],
"modules": [
"applications",
"sponsorships"
]
},
"nearby": {
"permissions": [
"users",
"admins",
"group_users",
"group_admins"
],
"modules": [
"applications"
]
},
"warn": {
"permissions": [
"group_users"
],
"modules": [
"warnings"
]
},
"reapply": {
"permissions": [
"users",
"admins"
],
"modules": [
"applications"
]
},
"sponsorship": {
"permissions": [
"users",
"admins"
],
"modules": [
"sponsorships"
]
},
"reboot": {
"permissions": [
"admins",
"group_admins"
],
"modules": [
"general"
]
},
"label": {
"permissions": [
"admins",
"group_admins"
],
"modules": [
"applications"
]
},
"message": {
"permissions": [
"admins",
"group_admins"
],
"modules": [
"general"
]
},
"identify": {
"permissions": [
"admins",
"group_admins"
],
"modules": [
"applications",
"sponsorships"
]
},
"application": {
"permissions": [
"admins",
"group_admins"
],
"modules": [
"applications"
]
},
"applications": {
"permissions": [
"admins",
"group_admins"
],
"modules": [
"applications"
]
}
} }
} }
``` ```
@ -99,4 +229,4 @@ After all of that you're good to go! Happy using :)
* [x] Check sponsorship on Holo girls * [x] Check sponsorship on Holo girls
* [x] /nearby command * [x] /nearby command
* [x] Complete messenger between user and admins * [x] Complete messenger between user and admins
* [x] Get application by id and user_id * [x] Get application by id and user_id

View File

@ -72,5 +72,118 @@
"locations": { "locations": {
"cache": "cache", "cache": "cache",
"locale": "locale" "locale": "locale"
},
"commands": {
"rules": {
"permissions": [
"users",
"admins"
],
"modules": [
"general"
]
},
"cancel": {
"permissions": [
"users",
"admins"
],
"modules": [
"applications",
"sponsorships"
]
},
"nearby": {
"permissions": [
"users",
"admins",
"group_users",
"group_admins"
],
"modules": [
"applications"
]
},
"warn": {
"permissions": [
"group_users"
],
"modules": [
"warnings"
]
},
"reapply": {
"permissions": [
"users",
"admins"
],
"modules": [
"applications"
]
},
"sponsorship": {
"permissions": [
"users",
"admins"
],
"modules": [
"sponsorships"
]
},
"reboot": {
"permissions": [
"admins",
"group_admins"
],
"modules": [
"general"
]
},
"label": {
"permissions": [
"admins",
"group_admins"
],
"modules": [
"applications"
]
},
"message": {
"permissions": [
"admins",
"group_admins"
],
"modules": [
"general"
]
},
"identify": {
"permissions": [
"admins",
"group_admins"
],
"modules": [
"applications",
"sponsorships"
]
},
"application": {
"permissions": [
"admins",
"group_admins"
],
"modules": [
"applications"
]
},
"applications": {
"permissions": [
"admins",
"group_admins"
],
"modules": [
"applications"
]
}
} }
} }

View File

@ -238,33 +238,18 @@
], ],
"rules_additional": "Додаткові правила, які несуть рекомендаційний характер, та не мають явних покарань за порушення:\n1⃣) У чаті немає заборони на російську мову. Ми поважаємо кожного українця і не бажаємо розпалювати мовні конфлікти.\n2⃣) У чаті немає заборони на російський контент. Але, майте на увазі, що учасники, здебільшого, не будуть зацікавлені у тому, щоб обговорювати його і він може бути проігнорованим.\n3⃣) Не зловживайте матами. Намагайтесь спілкуватись чистою мовою.\n4⃣) Поважайте авторські права контентмейкерів. Якщо ви знаходите арт, анімацію, музику тощо, на офіційних ресурсах (pixiv, twitter, deviantart тощо), відправляйте на нього посилання.\nЯкщо хтось із учасників відправив арт із не офіційного ресурсу і ви бажаєте дізнатись його автора, відправте у відповідь повідомлення із текстом `/search` на повідомлення із артом.", "rules_additional": "Додаткові правила, які несуть рекомендаційний характер, та не мають явних покарань за порушення:\n1⃣) У чаті немає заборони на російську мову. Ми поважаємо кожного українця і не бажаємо розпалювати мовні конфлікти.\n2⃣) У чаті немає заборони на російський контент. Але, майте на увазі, що учасники, здебільшого, не будуть зацікавлені у тому, щоб обговорювати його і він може бути проігнорованим.\n3⃣) Не зловживайте матами. Намагайтесь спілкуватись чистою мовою.\n4⃣) Поважайте авторські права контентмейкерів. Якщо ви знаходите арт, анімацію, музику тощо, на офіційних ресурсах (pixiv, twitter, deviantart тощо), відправляйте на нього посилання.\nЯкщо хтось із учасників відправив арт із не офіційного ресурсу і ви бажаєте дізнатись його автора, відправте у відповідь повідомлення із текстом `/search` на повідомлення із артом.",
"commands": { "commands": {
"rules": "Правила спільноти", "application": "Переглянути анкету користувача",
"applications": "Отримати всі анкети як JSON",
"cancel": "Відмінити актуальну дію", "cancel": "Відмінити актуальну дію",
"identify": "Дізнатись дані про користувача за айді",
"label": "Встановити нікнейм користувачу",
"message": "Надіслати користувачу повідомлення",
"nearby": "Показати користувачів поблизу", "nearby": "Показати користувачів поблизу",
"reapply": "Повторно заповнити анкету", "reapply": "Повторно заповнити анкету",
"sponsorship": "Отримати роль за спонсорство"
},
"commands_admin": {
"reboot": "Перезапустити бота", "reboot": "Перезапустити бота",
"label": "Встановити нікнейм користувачу", "rules": "Правила спільноти",
"message": "Надіслати користувачу повідомлення", "sponsorship": "Отримати роль за спонсорство",
"identify": "Дізнатись дані про користувача за айді",
"warnings": "Переглянути попередження користувача",
"application": "Переглянути анкету користувача",
"applications": "Отримати всі анкети як JSON"
},
"commands_group_admin": {
"reboot": "Перезапустити бота",
"label": "Встановити нікнейм користувачу",
"nearby": "Показати користувачів поблизу",
"message": "Надіслати користувачу повідомлення",
"identify": "Дізнатись дані про користувача за айді",
"warnings": "Переглянути попередження користувача",
"application": "Переглянути анкету користувача",
"applications": "Отримати всі анкети як JSON"
},
"commands_group_destination": {
"warn": "Попередити користувача", "warn": "Попередити користувача",
"nearby": "Показати користувачів поблизу" "warnings": "Переглянути попередження користувача"
} }
} }

View File

@ -50,113 +50,129 @@ if configGet("enabled", "scheduler", "cache_avatars"):
# Check for birthdays # Check for birthdays
if configGet("enabled", "scheduler", "birthdays"): if configGet("enabled", "features", "applications") is True:
@scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "birthdays")) if configGet("enabled", "scheduler", "birthdays") is True:
async def check_birthdays(): @scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "birthdays"))
for entry in col_applications.find(): async def check_birthdays():
if entry["application"]["2"].strftime("%d.%m") == datetime.now().strftime("%d.%m"): for entry in col_applications.find():
try: if entry["application"]["2"].strftime("%d.%m") == datetime.now().strftime("%d.%m"):
tg_user = await app.get_users(entry["user"]) try:
await app.send_message( configGet("admin_group"), locale("birthday", "message").format(str(tg_user.first_name), str(tg_user.username), str(relativedelta(datetime.now(), entry["application"]["2"], '%d.%m.%Y').years)) ) # type: ignore tg_user = await app.get_users(entry["user"])
logWrite(f"Notified admins about {entry['user']}'s birthday") await app.send_message( configGet("admin_group"), locale("birthday", "message").format(str(tg_user.first_name), str(tg_user.username), str(relativedelta(datetime.now(), entry["application"]["2"], '%d.%m.%Y').years)) ) # type: ignore
except Exception as exp: logWrite(f"Notified admins about {entry['user']}'s birthday")
logWrite(f"Could not find user {entry['user']} to send a message about birthday due to '{exp}'") except Exception as exp:
continue logWrite(f"Could not find user {entry['user']} to send a message about birthday due to '{exp}'")
logWrite("Birthdays check performed") continue
logWrite("Birthdays check performed")
# Check for expired sponsorships # Check for expired sponsorships
if configGet("enabled", "scheduler", "sponsorships"): if configGet("enabled", "features", "sponsorships") is True:
@scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "sponsorships")) if configGet("enabled", "scheduler", "sponsorships") is True:
async def check_sponsors(): @scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "sponsorships"))
for entry in col_sponsorships.find({"sponsorship.expires": {"$lt": datetime.now()+timedelta(days=2)}}): async def check_sponsors():
try: for entry in col_sponsorships.find({"sponsorship.expires": {"$lt": datetime.now()+timedelta(days=2)}}):
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.label_reset(configGet("destination_group"))
col_sponsorships.find_one_and_delete({"user": holo_user.id})
try: try:
tg_user = await app.get_users(entry["user"]) tg_user = await app.get_users(entry["user"])
logWrite(f"Notified user that sponsorship expired") 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: except Exception as exp:
logWrite(f"Could not find user {entry['user']} notify about sponsorship expired due to '{exp}'") logWrite(f"Could not find user {entry['user']} notify about sponsorship expiry due to '{exp}'")
except Exception as exp: continue
logWrite(f"Could not reset label of user {entry['user']} due to '{exp}'") for entry in col_sponsorships.find({"sponsorship.expires": {"$lt": datetime.now()}}):
continue try:
logWrite("Sponsorships check performed") holo_user = HoloUser(entry["user"])
await app.send_message( entry["user"], locale("sponsorships_expired", "message") ) # type: ignore
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 expired")
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")
# Register all bot commands # Register all bot commands
@scheduler.scheduled_job(trigger="date", run_date=datetime.now()+timedelta(seconds=3)) @scheduler.scheduled_job(trigger="date", run_date=datetime.now()+timedelta(seconds=3))
async def commands_register(): async def commands_register():
commands = {
"users": [],
"admins": [],
"group_users": [],
"group_admins": [],
"locales": {}
}
valid_locales = [] valid_locales = []
files_locales = listdir(f'{configGet("locale", "locations")}') files_locales = listdir(f'{configGet("locale", "locations")}')
for entry in files_locales: for entry in files_locales:
if entry.endswith(".json"): if entry.endswith(".json"):
valid_locales.append(".".join(entry.split(".")[:-1])) valid_locales.append(".".join(entry.split(".")[:-1]))
commands["locales"][".".join(entry.split(".")[:-1])] = {
"users": [],
"admins": [],
"group_users": [],
"group_admins": []
}
config_modules = configGet("features")
config_commands = configGet("commands")
for command in config_commands:
enabled = False
for module in config_commands[command]["modules"]:
if config_modules[module] == module:
enabled = True
if enabled is False:
continue
for permission in config_commands[command]["permissions"]:
commands[permission].append(BotCommand(command, locale("commands")[command]))
for lc in valid_locales:
commands["locales"][lc][permission].append(BotCommand(command, locale("commands", locale=lc)[command]))
# Registering user commands # Registering user commands
commands_list = [] await app.set_bot_commands(commands["users"])
for command in locale("commands"):
commands_list.append(BotCommand(command, locale("commands")[command]))
await app.set_bot_commands(commands_list)
logWrite("Registered user commands for default locale") logWrite("Registered user commands for default locale")
# Registering user commands for each locale # Registering user commands for each locale
for lc in valid_locales: for lc in valid_locales:
commands_list = [] await app.set_bot_commands(commands["locales"][lc]["users"], language_code=lc)
for command in locale("commands", locale=lc):
commands_list.append(BotCommand(command, locale("commands",locale=lc)[command]))
await app.set_bot_commands(commands_list, language_code=lc)
logWrite(f"Registered user commands for locale {lc}") logWrite(f"Registered user commands for locale {lc}")
# Registering admin commands # Registering admin/owner commands
commands_admin_list = [] for admin in configGet("admins")+[configGet("owner")]:
for command in locale("commands"):
commands_admin_list.append(BotCommand(command, locale("commands")[command]))
for command in locale("commands_admin"):
commands_admin_list.append(BotCommand(command, locale("commands_admin")[command]))
for admin in configGet("admins"):
try: try:
await app.set_bot_commands(commands_admin_list, scope=BotCommandScopeChat(chat_id=admin)) await app.set_bot_commands(commands["admins"], scope=BotCommandScopeChat(chat_id=admin))
logWrite(f"Registered admin commands for admin {admin}") if admin == configGet("owner"):
logWrite(f"Registered admin commands for owner {configGet('owner')}")
else:
logWrite(f"Registered admin commands for admin {admin}")
except bad_request_400.PeerIdInvalid: except bad_request_400.PeerIdInvalid:
pass pass
try:
await app.set_bot_commands(commands_admin_list, scope=BotCommandScopeChat(chat_id=configGet("owner")))
logWrite(f"Registered admin commands for owner {configGet('owner')}")
except bad_request_400.PeerIdInvalid:
logWrite(f"Could not register commands for bot owner. Perhaps user has not started the bot yet.")
# Registering admin group commands # Registering admin group commands
commands_group_admin_list = []
for command in locale("commands_group_admin"):
commands_group_admin_list.append(BotCommand(command, locale("commands_group_admin")[command]))
try: try:
await app.set_bot_commands(commands_group_admin_list, scope=BotCommandScopeChat(chat_id=configGet("admin_group"))) await app.set_bot_commands(commands["group_admins"], scope=BotCommandScopeChat(chat_id=configGet("admin_group")))
logWrite("Registered admin group commands for default locale") logWrite("Registered admin group commands for default locale")
except bad_request_400.ChannelInvalid: except bad_request_400.ChannelInvalid:
logWrite(f"Could not register commands for admin group. Bot is likely not in the group.") logWrite(f"Could not register commands for admin group. Bot is likely not in the group.")
# Registering destination group commands # Registering destination group commands
commands_group_destination_list = []
for command in locale("commands_group_destination"):
commands_group_destination_list.append(BotCommand(command, locale("commands_group_destination")[command]))
try: try:
await app.set_bot_commands(commands_group_destination_list, scope=BotCommandScopeChat(chat_id=configGet("destination_group"))) await app.set_bot_commands(commands["group_users"], scope=BotCommandScopeChat(chat_id=configGet("destination_group")))
logWrite("Registered destination group commands") logWrite("Registered destination group commands")
except bad_request_400.ChannelInvalid: except bad_request_400.ChannelInvalid:
logWrite(f"Could not register commands for destination group. Bot is likely not in the group.") logWrite(f"Could not register commands for destination group. Bot is likely not in the group.")