Compare commits
251 Commits
ce182999a0
...
v1.3
Author | SHA1 | Date | |
---|---|---|---|
b5c9a0783e | |||
aef4dd091d | |||
a3f75bec7c | |||
1f45398de5 | |||
|
cb2f3358b2 | ||
74ae30d841 | |||
e235fe0ed2 | |||
bf8ec39584 | |||
972827d6c2 | |||
43e71c95c4 | |||
2a2ad9f96e | |||
ddb59fdfd5 | |||
5c55af9e65 | |||
fd992e89e7 | |||
cea5338706 | |||
a4faae5b45 | |||
2dc6a54299 | |||
cb3a975303 | |||
de984c2b78 | |||
38b43c07cb | |||
3304339244 | |||
393a7584d5 | |||
e50cdd53b3 | |||
3012c3d5ae | |||
8c21ae1844 | |||
3df57f1c42 | |||
5b8951fe07 | |||
64b7a6a4ba | |||
8d18ed2126 | |||
ed2361638a | |||
0c78f21c96 | |||
3f6fb51a4f | |||
23b2925ffa | |||
82a878aa6d | |||
360bdf2c72 | |||
f98fb0b6dc | |||
eaec6f2fe8 | |||
ee738d00b5 | |||
fd19b4cb0b | |||
|
c56385a181 | ||
66a1ea17ab | |||
b10a62c63e | |||
a3c27ab4bd | |||
eeff6d40ce | |||
7be7d5ac7b | |||
1ce47b0aaf | |||
f14e80856c | |||
431b2d048f | |||
7feaa7af56 | |||
834157030c | |||
a59a42ffd9 | |||
f4c1bf9587 | |||
adc8c83102 | |||
e3fd4b3576 | |||
4019f2f376 | |||
51b943b576 | |||
de552db4c8 | |||
8beb33b7c3 | |||
05e3916478 | |||
414bfefb21 | |||
fd5e0b5b22 | |||
bd925418fd | |||
42a4a2e58e | |||
95be1e72d3 | |||
ecbf7d8b78 | |||
92386ac8ce | |||
dabfa2ecef | |||
00a408ac6c | |||
b67b1daf7c | |||
f83751c07d | |||
f5e3cd5a50 | |||
478fb174c5 | |||
30dfe4ff04 | |||
bdc775dcbd | |||
717d636497 | |||
64b0562bc4 | |||
eced1b7984 | |||
da3dd3a2fe | |||
3e166a3fca | |||
d090b18655 | |||
e2d28f442c | |||
496240c48b | |||
|
0bf5ae70eb | ||
|
bcaf80e2e1 | ||
|
21bf460b28 | ||
|
a4bbb837d7 | ||
|
1a438fc32e | ||
234b73add0 | |||
742b529c33 | |||
78a37ca186 | |||
374effd5d7 | |||
|
1195df894c | ||
|
67f1ce535f | ||
|
b6d45545fc | ||
|
59dafc004d | ||
|
57518399a1 | ||
|
ee288a1983 | ||
373f2332a0 | |||
f4fb85f7a4 | |||
02a6960391 | |||
7939f8b65e | |||
5b28f9f588 | |||
6e44177907 | |||
4f0b9f8e3a | |||
78dee0591c | |||
b0b0f04a9b | |||
9e009aea43 | |||
42d00383bf | |||
4fba305b05 | |||
47e62946ab | |||
68c7cc0ada | |||
646db667d9 | |||
2e8277d6d2 | |||
19fc9308e4 | |||
c90495eb1c | |||
|
bdb2338ab9 | ||
|
496bb7d4a6 | ||
|
b437092fe7 | ||
|
9431763e6b | ||
|
4977b8f31a | ||
|
0739eeb87d | ||
|
0214a29a2e | ||
|
6b80b7d0fa | ||
|
3fd56e8b41 | ||
|
3eef04794a | ||
|
d59a1671b3 | ||
|
ccbc135ee4 | ||
083281e784 | |||
8cb3ef283b | |||
|
1268c33830 | ||
|
aad5c4f9f2 | ||
|
3d4dd29205 | ||
|
ff95d9556d | ||
|
b3c5f060a1 | ||
|
096a0498f8 | ||
|
d7936fa600 | ||
3442a478d4 | |||
ee7f9712c8 | |||
79304816b0 | |||
ccebccf086 | |||
b383ab6001 | |||
db60a538b2 | |||
e79edf1dff | |||
7edffd0b40 | |||
c8f89a7447 | |||
ea1dc542a3 | |||
6aa8128fc6 | |||
7854f88217 | |||
b401028dd1 | |||
642c23dd61 | |||
b2613c25a4 | |||
a7038e9d8f | |||
|
a59a7b738c | ||
626492fb3c | |||
1aed7bff7b | |||
ba13f36769 | |||
a82adc4d1f | |||
fe6d2514c7 | |||
2cfa5a8f8d | |||
950666e4ad | |||
ace71fd6be | |||
|
25be843cd8 | ||
|
e6589fc3e5 | ||
|
8b2abc2cfa | ||
|
c763fc537b | ||
|
22011829a5 | ||
|
e59aa98fd5 | ||
|
082acc85cf | ||
|
87d9afe74a | ||
|
5e06859b56 | ||
|
47896faf06 | ||
|
85112dc653 | ||
|
af862a3454 | ||
|
1eb98750a7 | ||
|
eecb71a91e | ||
|
426b1550f6 | ||
|
0302d8c1ae | ||
|
5a6a96d3f9 | ||
|
12da1b2376 | ||
|
7db8c9ac5c | ||
95e9fdf460 | |||
ac5a0d112f | |||
2db19acf6c | |||
6874268154 | |||
a906c0a1cc | |||
bc54abcc97 | |||
1b6f429be9 | |||
be55f8a3b1 | |||
d3945eea0c | |||
|
b345a5d776 | ||
|
f905a5c4df | ||
|
f4a2e655a6 | ||
|
741a01cff6 | ||
|
6b00f181f6 | ||
|
41eb6e46ee | ||
|
1d5ebd02fe | ||
|
43ce2d73b6 | ||
|
797d9de7e4 | ||
|
438f8f8c44 | ||
|
a769ea9ef5 | ||
|
fa08679b11 | ||
|
e5514cac7c | ||
|
8ccd2a858a | ||
|
8bb7c58c2a | ||
3b71cb3d85 | |||
09e5048d7f | |||
de4126b1a3 | |||
11da9de887 | |||
a3830f672f | |||
085a833b16 | |||
bc8cd8a8ce | |||
e61aa17a72 | |||
ee44987ae8 | |||
40483c17c1 | |||
2d75b01bfe | |||
9fb095b7c6 | |||
b0a3830c4f | |||
32ec34435d | |||
57428e530a | |||
b3ec78d54e | |||
4c82cd8515 | |||
6c3226ccd7 | |||
652069ffd8 | |||
3e2c301400 | |||
2924c808dd | |||
f471deedd2 | |||
9d0b66371a | |||
d7a087bcfb | |||
b09f30c3fd | |||
c91833f81e | |||
49bed307ad | |||
ee90e579b5 | |||
b0ff916e31 | |||
e603dd24ab | |||
98ed58447b | |||
909588e940 | |||
2ead4eaa06 | |||
f1990345ce | |||
3ffa6e32f9 | |||
31376278ba | |||
3009094caa | |||
db36c051d4 | |||
132e6235a0 | |||
e4fafd9075 | |||
2b09aaa7b0 | |||
6b84ef3779 | |||
d4256f0c8c | |||
4541c84eb9 | |||
9f3f29fa27 | |||
4c7a724c42 | |||
c06bf90417 |
10
.gitignore
vendored
10
.gitignore
vendored
@@ -157,11 +157,11 @@ config.json
|
|||||||
config_debug.json
|
config_debug.json
|
||||||
*.session
|
*.session
|
||||||
*.session-journal
|
*.session-journal
|
||||||
users
|
data
|
||||||
!users/.gitkeep
|
|
||||||
TASK.md
|
TASK.md
|
||||||
inline_bot.py
|
inline_bot.py
|
||||||
data/applications.json
|
|
||||||
!data/cache/avatars/.gitkeep
|
|
||||||
data/cache/avatars/*
|
|
||||||
.vscode
|
.vscode
|
||||||
|
migrate.py
|
||||||
|
venv_linux
|
||||||
|
validation/*
|
||||||
|
!validation/*.json
|
89
README.md
89
README.md
@@ -1,6 +1,11 @@
|
|||||||
# HoloCheckerBot
|
<h1 align="center">HoloCheckerBot</h1>
|
||||||
|
|
||||||
Small Telegram bot made on Pyrogram
|
<p align="center">Small Telegram bot made on Pyrogram</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://git.end-play.xyz/profitroll/HoloCheckerBot/src/branch/master/LICENSE"><img alt="License: GPL" src="https://img.shields.io/badge/License-GPL-blue"></a>
|
||||||
|
<a href="https://git.end-play.xyz/profitroll/HoloCheckerBot"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-000000.svg"></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
## What can this bot do?
|
## What can this bot do?
|
||||||
|
|
||||||
@@ -25,82 +30,14 @@ Small Telegram bot made on Pyrogram
|
|||||||
So bot has its "config_example.json" and it needs to be changed.
|
So bot has its "config_example.json" and it needs to be changed.
|
||||||
Copy this file to "config.json" and open it with any text editor.
|
Copy this file to "config.json" and open it with any text editor.
|
||||||
|
|
||||||
You can see config file with all the comments below:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"locale": "uk",
|
|
||||||
"debug": false,
|
|
||||||
"owner": 0,
|
|
||||||
"bot_id": 0,
|
|
||||||
"age_allowed": 0,
|
|
||||||
"api": "http://example.com",
|
|
||||||
"inline_preview_count": 7,
|
|
||||||
"admin_group": 0,
|
|
||||||
"destination_group": 0,
|
|
||||||
"remove_application_time": -1,
|
|
||||||
"admins": [],
|
|
||||||
"bot": {
|
|
||||||
"api_id": 0,
|
|
||||||
"api_hash": "",
|
|
||||||
"bot_token": ""
|
|
||||||
},
|
|
||||||
"database": {
|
|
||||||
"user": null,
|
|
||||||
"password": null,
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"port": 27017,
|
|
||||||
"name": "holochecker"
|
|
||||||
},
|
|
||||||
"logging": {
|
|
||||||
"size": 512,
|
|
||||||
"location": "logs"
|
|
||||||
},
|
|
||||||
"scheduler": {
|
|
||||||
"birthdays": {
|
|
||||||
"time": 9,
|
|
||||||
"enabled": true
|
|
||||||
},
|
|
||||||
"sponsorships": {
|
|
||||||
"time": 9,
|
|
||||||
"enabled": true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"locations": {
|
|
||||||
"cache": "cache",
|
|
||||||
"locale": "locale"
|
|
||||||
},
|
|
||||||
"commands": {
|
|
||||||
"rules": "Check out the rules",
|
|
||||||
"reapply": "Resubmit the application",
|
|
||||||
"sponsorship": "Apply for sponsor role"
|
|
||||||
},
|
|
||||||
"commands_admin": {
|
|
||||||
"reboot": "Restart the bot",
|
|
||||||
"message": "Send a message",
|
|
||||||
"label": "Set user's nickname",
|
|
||||||
"warnings": "Check user's warnings",
|
|
||||||
"application": "Check user's application",
|
|
||||||
"applications": "Retrieve all applications as a JSON"
|
|
||||||
},
|
|
||||||
"commands_group_admin": {
|
|
||||||
"reboot": "Restart the bot",
|
|
||||||
"message": "Send a message",
|
|
||||||
"label": "Set user's nickname",
|
|
||||||
"warnings": "Check user's warnings",
|
|
||||||
"application": "Check user's application",
|
|
||||||
"applications": "Retrieve all applications as a JSON"
|
|
||||||
},
|
|
||||||
"commands_group_destination": {
|
|
||||||
"warn": "Warn a user"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
After all of that you're good to go! Happy using :)
|
After all of that you're good to go! Happy using :)
|
||||||
|
|
||||||
## To-Do
|
## To-Do
|
||||||
|
|
||||||
|
* [ ] Stats and infographics
|
||||||
|
* [ ] Check group members without completed application
|
||||||
|
* [x] Replicate some functions of @spoilerobot
|
||||||
|
* [x] Check sponsorship on Holo girls
|
||||||
|
* [x] /nearby command
|
||||||
* [x] Complete messenger between user and admins
|
* [x] Complete messenger between user and admins
|
||||||
* [ ] Check sponsorship on Holo girls
|
* [x] Get application by id and user_id
|
||||||
* [ ] Get application by id and user_id
|
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
from os import makedirs, path, sep
|
from os import makedirs, path, sep
|
||||||
from fastapi import FastAPI, HTTPException
|
from fastapi import FastAPI, HTTPException
|
||||||
from fastapi.responses import FileResponse, JSONResponse
|
from fastapi.responses import FileResponse, JSONResponse, Response
|
||||||
from starlette.status import HTTP_404_NOT_FOUND
|
from starlette.status import HTTP_404_NOT_FOUND
|
||||||
from modules.utils import configGet
|
from modules.utils import configGet
|
||||||
|
|
||||||
@@ -8,13 +8,33 @@ makedirs(f'{configGet("cache", "locations")}{sep}avatars', exist_ok=True)
|
|||||||
|
|
||||||
app = FastAPI(title="HoloUA Avatars API", docs_url=None, redoc_url=None, version="1.0")
|
app = FastAPI(title="HoloUA Avatars API", docs_url=None, redoc_url=None, version="1.0")
|
||||||
|
|
||||||
|
|
||||||
@app.get("/check", response_class=JSONResponse, include_in_schema=False)
|
@app.get("/check", response_class=JSONResponse, include_in_schema=False)
|
||||||
|
@app.head("/check", response_class=JSONResponse, include_in_schema=False)
|
||||||
async def check():
|
async def check():
|
||||||
return JSONResponse({"detail": "I'm alright, thank you"})
|
return JSONResponse({"detail": "I'm alright, thank you"})
|
||||||
|
|
||||||
|
|
||||||
@app.get("/", response_class=FileResponse, include_in_schema=False)
|
@app.get("/", response_class=FileResponse, include_in_schema=False)
|
||||||
async def favicon(avatar_id: str):
|
async def avatar_get(avatar_id: str):
|
||||||
if path.exists(f'{configGet("cache", "locations")}{sep}avatars{sep}{avatar_id}'):
|
if path.exists(f'{configGet("cache", "locations")}{sep}avatars{sep}{avatar_id}'):
|
||||||
return FileResponse(f'{configGet("cache", "locations")}{sep}avatars{sep}{avatar_id}', media_type="image/jpg")
|
return FileResponse(
|
||||||
|
f'{configGet("cache", "locations")}{sep}avatars{sep}{avatar_id}',
|
||||||
|
media_type="image/jpg",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="File not found")
|
||||||
|
|
||||||
|
|
||||||
|
@app.head("/", response_class=Response, include_in_schema=False)
|
||||||
|
async def avatar_head(avatar_id: str):
|
||||||
|
if path.exists(f'{configGet("cache", "locations")}{sep}avatars{sep}{avatar_id}'):
|
||||||
|
return Response(
|
||||||
|
headers={
|
||||||
|
"Content-Length": path.getsize(
|
||||||
|
f'{configGet("cache", "locations")}{sep}avatars{sep}{avatar_id}'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="File not found")
|
raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="File not found")
|
32
app.py
32
app.py
@@ -1,18 +1,42 @@
|
|||||||
|
from os import path, sep
|
||||||
|
from ujson import JSONDecodeError
|
||||||
from modules.logging import logWrite
|
from modules.logging import logWrite
|
||||||
from modules.utils import configGet
|
from modules.utils import configGet, jsonLoad
|
||||||
from pyrogram.client import Client
|
from pyrogram.client import Client
|
||||||
from pyrogram.errors import bad_request_400
|
from pyrogram.errors import bad_request_400
|
||||||
|
from convopyro import Conversation
|
||||||
|
|
||||||
|
app = Client(
|
||||||
|
"holochecker",
|
||||||
|
bot_token=configGet("bot_token", "bot"),
|
||||||
|
api_id=configGet("api_id", "bot"),
|
||||||
|
api_hash=configGet("api_hash", "bot"),
|
||||||
|
)
|
||||||
|
|
||||||
|
Conversation(app)
|
||||||
|
|
||||||
app = Client("holochecker", bot_token=configGet("bot_token", "bot"), api_id=configGet("api_id", "bot"), api_hash=configGet("api_hash", "bot"))
|
|
||||||
|
|
||||||
async def isAnAdmin(admin_id):
|
async def isAnAdmin(admin_id):
|
||||||
|
# Check if user is mentioned in config
|
||||||
if (admin_id == configGet("owner")) or (admin_id in configGet("admins")):
|
if (admin_id == configGet("owner")) or (admin_id in configGet("admins")):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
# Check if user is probably in cache
|
||||||
|
if path.exists(f"cache{sep}admins") is True:
|
||||||
try:
|
try:
|
||||||
async for member in app.get_chat_members(configGet("admin_group")):
|
return True if admin_id in jsonLoad(f"cache{sep}admins") else False
|
||||||
|
except (FileNotFoundError, JSONDecodeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Check if user is in admin group
|
||||||
|
try:
|
||||||
|
async for member in app.get_chat_members(configGet("admin", "groups")):
|
||||||
if member.user.id == admin_id:
|
if member.user.id == admin_id:
|
||||||
return True
|
return True
|
||||||
except bad_request_400.ChannelInvalid:
|
except bad_request_400.ChannelInvalid:
|
||||||
logWrite(f"Could not get users in admin group to answer isAnAdmin(). Bot is likely not in the group.")
|
logWrite(
|
||||||
|
f"Could not get users in admin group to answer isAnAdmin(). Bot is likely not in the group."
|
||||||
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
return False
|
return False
|
8
classes/errors/geo.py
Normal file
8
classes/errors/geo.py
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
class PlaceNotFoundError(Exception):
|
||||||
|
"""Query provided did not lead to any city or populated area"""
|
||||||
|
|
||||||
|
def __init__(self, query):
|
||||||
|
self.query = query
|
||||||
|
super().__init__(
|
||||||
|
f"Could not find any place on geonames.org of feature classes A and P by query '{self.query}'"
|
||||||
|
)
|
38
classes/errors/holo_user.py
Normal file
38
classes/errors/holo_user.py
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
"""Exceptions that are meant to be used by HoloUser class
|
||||||
|
and other modules that handle those exceptions"""
|
||||||
|
|
||||||
|
|
||||||
|
class UserNotFoundError(Exception):
|
||||||
|
"""HoloUser could not find user with such an ID in database"""
|
||||||
|
|
||||||
|
def __init__(self, user, user_id):
|
||||||
|
self.user = user
|
||||||
|
self.user_id = user_id
|
||||||
|
super().__init__(
|
||||||
|
f"User of type {type(self.user)} with id {self.user_id} was not found"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class UserInvalidError(Exception):
|
||||||
|
"""Provided to HoloUser object is not supported"""
|
||||||
|
|
||||||
|
def __init__(self, user):
|
||||||
|
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 LabelSettingError(Exception):
|
||||||
|
def __init__(self, exp: Exception, trace: str) -> None:
|
||||||
|
super().__init__(
|
||||||
|
f"❌ **Could not set label**\n\nException: `{exp}`\n\n**Traceback:**\n```\n{trace}\n```"
|
||||||
|
)
|
File diff suppressed because it is too large
Load Diff
48
classes/templates.py
Normal file
48
classes/templates.py
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
"""Templates for temporary application/sponsorship records"""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
|
class DefaultApplicationTemp(dict):
|
||||||
|
def __init__(self, user: int, reapply: bool = False):
|
||||||
|
super().__init__({})
|
||||||
|
self.dict = {
|
||||||
|
"user": user,
|
||||||
|
"type": "application",
|
||||||
|
"complete": False,
|
||||||
|
"sent": False,
|
||||||
|
"state": "fill",
|
||||||
|
"reapply": reapply,
|
||||||
|
"stage": 1,
|
||||||
|
"application": {
|
||||||
|
"1": None,
|
||||||
|
"2": None,
|
||||||
|
"3": None,
|
||||||
|
"4": None,
|
||||||
|
"5": None,
|
||||||
|
"6": None,
|
||||||
|
"7": None,
|
||||||
|
"8": None,
|
||||||
|
"9": None,
|
||||||
|
"10": None,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class DefaultSponsorshipTemp(dict):
|
||||||
|
def __init__(self, user: int):
|
||||||
|
super().__init__({})
|
||||||
|
self.dict = {
|
||||||
|
"user": user,
|
||||||
|
"type": "sponsorship",
|
||||||
|
"complete": False,
|
||||||
|
"sent": False,
|
||||||
|
"state": "fill",
|
||||||
|
"stage": 1,
|
||||||
|
"sponsorship": {
|
||||||
|
"streamer": None,
|
||||||
|
"expires": datetime.fromtimestamp(0),
|
||||||
|
"proof": None,
|
||||||
|
"label": "",
|
||||||
|
},
|
||||||
|
}
|
@@ -2,14 +2,18 @@
|
|||||||
"locale": "uk",
|
"locale": "uk",
|
||||||
"debug": false,
|
"debug": false,
|
||||||
"owner": 0,
|
"owner": 0,
|
||||||
"bot_id": 0,
|
|
||||||
"age_allowed": 0,
|
"age_allowed": 0,
|
||||||
|
"age_maximum": 70,
|
||||||
"api": "http://example.com",
|
"api": "http://example.com",
|
||||||
|
"issues": "https://github.com/example/test/issues/new",
|
||||||
"inline_preview_count": 7,
|
"inline_preview_count": 7,
|
||||||
"admin_group": 0,
|
|
||||||
"destination_group": 0,
|
|
||||||
"remove_application_time": -1,
|
"remove_application_time": -1,
|
||||||
|
"search_radius": 50,
|
||||||
"admins": [],
|
"admins": [],
|
||||||
|
"groups": {
|
||||||
|
"admin": 0,
|
||||||
|
"users": 0
|
||||||
|
},
|
||||||
"bot": {
|
"bot": {
|
||||||
"api_id": 0,
|
"api_id": 0,
|
||||||
"api_hash": "",
|
"api_hash": "",
|
||||||
@@ -22,10 +26,37 @@
|
|||||||
"port": 27017,
|
"port": 27017,
|
||||||
"name": "holochecker"
|
"name": "holochecker"
|
||||||
},
|
},
|
||||||
|
"geocoding": {
|
||||||
|
"username": "demo"
|
||||||
|
},
|
||||||
"logging": {
|
"logging": {
|
||||||
"size": 512,
|
"size": 512,
|
||||||
"location": "logs"
|
"location": "logs"
|
||||||
},
|
},
|
||||||
|
"features": {
|
||||||
|
"general": {
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
"applications": {
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
"sponsorships": {
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
"warnings": {
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
"invites_check": {
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
"dinovoice": {
|
||||||
|
"enabled": false
|
||||||
|
},
|
||||||
|
"spoilers": {
|
||||||
|
"enabled": true,
|
||||||
|
"allow_external": true
|
||||||
|
}
|
||||||
|
},
|
||||||
"scheduler": {
|
"scheduler": {
|
||||||
"birthdays": {
|
"birthdays": {
|
||||||
"time": 9,
|
"time": 9,
|
||||||
@@ -34,6 +65,27 @@
|
|||||||
"sponsorships": {
|
"sponsorships": {
|
||||||
"time": 9,
|
"time": 9,
|
||||||
"enabled": true
|
"enabled": true
|
||||||
|
},
|
||||||
|
"cache_avatars": {
|
||||||
|
"interval": 6,
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
"cache_members": {
|
||||||
|
"interval": 30,
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
"cache_admins": {
|
||||||
|
"interval": 120,
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
"channels_monitor": {
|
||||||
|
"interval": 5,
|
||||||
|
"enabled": true,
|
||||||
|
"channels": []
|
||||||
|
},
|
||||||
|
"warnings_revocation": {
|
||||||
|
"interval": 6,
|
||||||
|
"enabled": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"locations": {
|
"locations": {
|
||||||
@@ -41,27 +93,151 @@
|
|||||||
"locale": "locale"
|
"locale": "locale"
|
||||||
},
|
},
|
||||||
"commands": {
|
"commands": {
|
||||||
"rules": "Check out the rules",
|
"rules": {
|
||||||
"reapply": "Resubmit the application",
|
"permissions": [
|
||||||
"sponsorship": "Apply for sponsor role"
|
"users",
|
||||||
|
"admins"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"general"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"commands_admin": {
|
"spoiler": {
|
||||||
"reboot": "Restart the bot",
|
"permissions": [
|
||||||
"message": "Send a message",
|
"users",
|
||||||
"label": "Set user's nickname",
|
"admins"
|
||||||
"warnings": "Check user's warnings",
|
],
|
||||||
"application": "Check user's application",
|
"modules": [
|
||||||
"applications": "Retrieve all applications as a JSON"
|
"spoilers"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"commands_group_admin": {
|
"cancel": {
|
||||||
"reboot": "Restart the bot",
|
"permissions": [
|
||||||
"message": "Send a message",
|
"users",
|
||||||
"label": "Set user's nickname",
|
"admins"
|
||||||
"warnings": "Check user's warnings",
|
],
|
||||||
"application": "Check user's application",
|
"modules": [
|
||||||
"applications": "Retrieve all applications as a JSON"
|
"spoilers",
|
||||||
|
"applications",
|
||||||
|
"sponsorships"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"commands_group_destination": {
|
"nearby": {
|
||||||
"warn": "Warn a user"
|
"permissions": [
|
||||||
|
"users",
|
||||||
|
"admins",
|
||||||
|
"group_admins"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"applications"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"warn": {
|
||||||
|
"permissions": [
|
||||||
|
"group_users_admins"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"warnings"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"warnings": {
|
||||||
|
"permissions": [
|
||||||
|
"admins",
|
||||||
|
"group_admins"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"warnings"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"reapply": {
|
||||||
|
"permissions": [
|
||||||
|
"users",
|
||||||
|
"admins"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"applications"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"sponsorship": {
|
||||||
|
"permissions": [
|
||||||
|
"users",
|
||||||
|
"admins"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"sponsorships"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"reboot": {
|
||||||
|
"permissions": [
|
||||||
|
"owner"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"general"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"label": {
|
||||||
|
"permissions": [
|
||||||
|
"admins",
|
||||||
|
"group_admins"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"applications"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"permissions": [
|
||||||
|
"users",
|
||||||
|
"admins",
|
||||||
|
"group_admins"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"general"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"identify": {
|
||||||
|
"permissions": [
|
||||||
|
"admins",
|
||||||
|
"group_admins"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"applications",
|
||||||
|
"sponsorships"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"issue": {
|
||||||
|
"permissions": [
|
||||||
|
"users",
|
||||||
|
"admins"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"general"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"export": {
|
||||||
|
"permissions": [
|
||||||
|
"admins",
|
||||||
|
"group_admins"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"general"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"application": {
|
||||||
|
"permissions": [
|
||||||
|
"admins",
|
||||||
|
"group_admins"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"applications"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"resetcommands": {
|
||||||
|
"permissions": [
|
||||||
|
"owner"
|
||||||
|
],
|
||||||
|
"modules": [
|
||||||
|
"general"
|
||||||
|
]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -1,9 +1,9 @@
|
|||||||
from os import getpid, makedirs
|
from os import getpid, makedirs
|
||||||
|
from time import time
|
||||||
from modules.utils import *
|
from modules.utils import *
|
||||||
from modules.inline import *
|
from modules.inline import *
|
||||||
from app import app
|
from app import app
|
||||||
|
|
||||||
from modules.commands_register import commands_register
|
|
||||||
from pyrogram import idle
|
from pyrogram import idle
|
||||||
|
|
||||||
pid = getpid()
|
pid = getpid()
|
||||||
@@ -12,75 +12,106 @@ makedirs(f'{configGet("cache", "locations")}{sep}avatars', exist_ok=True)
|
|||||||
|
|
||||||
# Importing
|
# Importing
|
||||||
from modules.commands.application import *
|
from modules.commands.application import *
|
||||||
from modules.commands.applications import *
|
from modules.commands.cancel import *
|
||||||
|
from modules.commands.export import *
|
||||||
|
from modules.commands.identify import *
|
||||||
|
from modules.commands.issue import *
|
||||||
from modules.commands.label import *
|
from modules.commands.label import *
|
||||||
from modules.commands.message import *
|
from modules.commands.message import *
|
||||||
|
from modules.commands.nearby import *
|
||||||
from modules.commands.reapply import *
|
from modules.commands.reapply import *
|
||||||
from modules.commands.reboot import *
|
from modules.commands.reboot import *
|
||||||
|
from modules.commands.resetcommands import *
|
||||||
from modules.commands.rules import *
|
from modules.commands.rules import *
|
||||||
|
from modules.commands.spoiler import *
|
||||||
from modules.commands.sponsorship import *
|
from modules.commands.sponsorship import *
|
||||||
from modules.commands.start import *
|
from modules.commands.start import *
|
||||||
from modules.commands.warn import *
|
from modules.commands.warn import *
|
||||||
from modules.commands.warnings import *
|
from modules.commands.warnings import *
|
||||||
|
|
||||||
|
from modules.callbacks.ban import *
|
||||||
from modules.callbacks.nothing import *
|
from modules.callbacks.nothing import *
|
||||||
from modules.callbacks.reapply import *
|
from modules.callbacks.reapply import *
|
||||||
from modules.callbacks.rules import *
|
from modules.callbacks.rules import *
|
||||||
|
from modules.callbacks.spoiler import *
|
||||||
|
from modules.callbacks.sponsorship import *
|
||||||
from modules.callbacks.sub import *
|
from modules.callbacks.sub import *
|
||||||
from modules.callbacks.sus import *
|
from modules.callbacks.sus import *
|
||||||
|
from modules.callbacks.warnings import *
|
||||||
|
|
||||||
from modules.handlers.confirmation import *
|
from modules.handlers.confirmation import *
|
||||||
from modules.handlers.contact import *
|
from modules.handlers.contact import *
|
||||||
from modules.handlers.group_join import *
|
from modules.handlers.group_join import *
|
||||||
|
from modules.handlers.voice import *
|
||||||
from modules.handlers.welcome import *
|
from modules.handlers.welcome import *
|
||||||
from modules.handlers.everything import *
|
from modules.handlers.everything import *
|
||||||
|
|
||||||
from modules.scheduled import *
|
from modules.scheduled import *
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
||||||
logWrite(f"Starting up with pid {pid}")
|
logWrite(f"Starting up with pid {pid}")
|
||||||
|
|
||||||
# Yes, it should be in some kind of async main() function but I don't give a shit.
|
# Yes, it should be in some kind of async main() function but I don't give a shit.
|
||||||
# I did compare performance, almost no difference and it's much more useful this way. Change my mind.
|
# I did compare performance, almost no difference and it's much more useful this way. Change my mind.
|
||||||
app.start()
|
app.start()
|
||||||
|
|
||||||
# if configGet("birthdays_notify"):
|
|
||||||
|
|
||||||
# every().day.at(configGet("birthdays_time")).do(check_birthdays, app)
|
|
||||||
|
|
||||||
# # Background tasks checker
|
|
||||||
# def background_task():
|
|
||||||
# try:
|
|
||||||
# while True:
|
|
||||||
# try:
|
|
||||||
# run_pending()
|
|
||||||
# #print('Checked')
|
|
||||||
# time.sleep(1)
|
|
||||||
# except:
|
|
||||||
# pass
|
|
||||||
# except KeyboardInterrupt:
|
|
||||||
# print('\nShutting down')
|
|
||||||
# killProc(pid)
|
|
||||||
# t = Thread(target=background_task)
|
|
||||||
# t.start()
|
|
||||||
|
|
||||||
try:
|
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")
|
||||||
|
)["timestamp"]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
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:
|
except bad_request_400.PeerIdInvalid:
|
||||||
logWrite(f"Could not send startup message to bot owner. Perhaps user has not started the bot yet.")
|
logWrite(
|
||||||
|
f"Could not send startup message to bot owner. Perhaps user has not started the bot yet."
|
||||||
commands_register(app)
|
)
|
||||||
|
|
||||||
scheduler.start()
|
scheduler.start()
|
||||||
|
|
||||||
idle()
|
idle()
|
||||||
|
|
||||||
try:
|
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:
|
except bad_request_400.PeerIdInvalid:
|
||||||
logWrite(f"Could not send shutdown message to bot owner. Perhaps user has not started the bot yet.")
|
logWrite(
|
||||||
|
f"Could not send shutdown message to bot owner. Perhaps user has not started the bot yet."
|
||||||
|
)
|
||||||
|
|
||||||
app.stop()
|
app.stop()
|
||||||
|
|
||||||
|
makedirs(configGet("cache", "locations"), exist_ok=True)
|
||||||
|
jsonSave(
|
||||||
|
{"timestamp": time()},
|
||||||
|
path.join(configGet("cache", "locations"), "shutdown_time"),
|
||||||
|
)
|
||||||
|
|
||||||
killProc(pid)
|
killProc(pid)
|
212
locale/en.disabled
Normal file
212
locale/en.disabled
Normal file
@@ -0,0 +1,212 @@
|
|||||||
|
{
|
||||||
|
"message": {
|
||||||
|
"start": "Hello and welcome! This bot was created to accept applications for joining our community. To continue, we are interested in the answer to one question:\n\nDo you want to join the Ukrainian community of Hololive fans?",
|
||||||
|
"goodbye": "Ok, thanks for your honesty! Sorry, but under such conditions we will not add you to the community. If you change your mind and want to join, just click the button.",
|
||||||
|
"privacy_notice": "We're glad to hear that!\n\nTo continue, you will need to fill out a short Application. Please take it seriously. We take personal data very seriously, so this Application will not be shared with any third parties, but will only be used for the community.",
|
||||||
|
"question1": "How can I contact you?",
|
||||||
|
"question2": "When is your birthday?",
|
||||||
|
"question3": "What city are you from or where do you live now?\n\n⚠️ Please do not provide exact addresses! \"Kyiv\" or \"Kyiv Oblast\" is a sufficient specification.\n\nExamples:\n- Kyiv\n- Odesa oblast\n- Makiivka (Luhansk oblast)",
|
||||||
|
"question4": "When did you first learn about Hololive?",
|
||||||
|
"question5": "What made you interested in Hololive?",
|
||||||
|
"question6": "Which girl's content do you like the most?",
|
||||||
|
"question7": "Name the content of at least five **JAPANESE** girls you like the most.",
|
||||||
|
"question8": "Do you watch streams of Hololive girls?",
|
||||||
|
"question9": "Whose songs from Hololive do you like the most?",
|
||||||
|
"question10": "And finally, tell us a little about yourself. About hobbies, what you like to do. In one message, please.",
|
||||||
|
"question2_underage": "Sorry, but you must be {0} years old to join us. These restrictions are in place to ensure that everyone in the community has fun with each other.",
|
||||||
|
"question2_invalid": "Please enter a date in the format `DD.MM.YYYY`.",
|
||||||
|
"question2_joke": "Joke, we get it. But please enter the real value.",
|
||||||
|
"question3_invalid": "City/population not found. Use the examples below to indicate where you live and try again:\n\n- Kyiv\n- Odesa region\n- Makiivka (Luhansk region).",
|
||||||
|
"question3_found": "Using the following result:\n- {0} ({1})",
|
||||||
|
"question3_error": "⚠️ **Error**\nCould not retrieve the geographic label. The developer has been notified of this error. Please try again.",
|
||||||
|
"question3_traceback": "⚠️ **Error occurred**\nError retrieving geocoding for `{0}`\nError: `{1}`\n\nTraceback:\n```\n{2}\n```",
|
||||||
|
"confirm": "Great, thanks!\n\nPlease check the data is correct:\n{0}\n\nEverything correct?",
|
||||||
|
"application_sent": "Thank you! We have sent your application for verification. You will receive a message as soon as it is checked and a decision is made. Until then, nothing more is required from you. Have a nice day :)",
|
||||||
|
"application_got": "Received an application from `{0}`\n\nName in tg: `{1}`\nUsername: @{2}\n\n**Application data:**\n{3}",
|
||||||
|
"reapply_got": "Received application change from `{0}`\n\nUsername: `{1}`\nUsername: @{2}\n\n**Application data:**\n{3}",
|
||||||
|
"shutdown": "Shutting down the bot with PID `{0}`",
|
||||||
|
"startup": "Starting the bot with PID `{0}`",
|
||||||
|
"startup_downtime": "Starting bot with PID `{0}` (was down for {1})",
|
||||||
|
"approved": "Congratulations! Your application has been reviewed and your eligibility has been confirmed. Use the button below the notification to join our lamp community!",
|
||||||
|
"approved_joined": "Congratulations! Your application has been reviewed and confirmed as correct. Thank you for your time and have a nice day!",
|
||||||
|
"read_rules": "Please read these rules before clicking the button and joining the chat.",
|
||||||
|
"rejected.": "Oh dear! Your application has been reviewed but not confirmed as eligible to join the community. Better luck next time!\n\nYou can try to reapply with the /reapply command.",
|
||||||
|
"rejected_russian": "Russian warship, go fuck yourself!",
|
||||||
|
"approved_by": "✅ **Application approved**\nAdmin **{0}** has reviewed and approved application `{1}`.",
|
||||||
|
"rejected_by": "❌ **Form rejected**\nAdmin **{0}** has reviewed and rejected form `{1}`.",
|
||||||
|
"rejected_by_agr": "❌ **Application rejected**\nAdmin **{0}** has reviewed and rejected application `{1}`, banning you from the community",
|
||||||
|
"rejected_by_rus": "❌ **Application rejected**\nAdmin **{0}** has reviewed and rejected the profile `{1}`, banning you from the community",
|
||||||
|
"contact": "Application `{0}`\n\n**Application data:**\n{1}\n\n{2}",
|
||||||
|
"application_status_accepted": "Accepted `{0}` on {1}",
|
||||||
|
"application_status_rejected": "Rejected `{0}` from {1}",
|
||||||
|
"application_status_on_hold": "Application still under review",
|
||||||
|
"application_status_not_send": "The application has not been sent yet",
|
||||||
|
"contact_invalid": "The submitted contact does not have a completed application form.",
|
||||||
|
"contact_not_member": "The sent contact is not a Telegram member.",
|
||||||
|
"already_sent": "The Application has already been sent, just wait. You will be informed immediately what decision will be made.",
|
||||||
|
"sus_joined": "User **{0}** (`{1}`) has joined the group without a personal invitation.",
|
||||||
|
"sus_allowed_by": "✅ **Access Allowed**\nAdmin **{0}** has allowed `{1}` to join the community without being personally invited.",
|
||||||
|
"sus_rejected_by": "❌ **Access denied**\nAdmin **{0}** has banned `{1}` for not being allowed to join the community via a personal link.",
|
||||||
|
"reapply_forbidden": "❌ **Action not possible**\nYour past application has not been approved or rejected yet.",
|
||||||
|
"reapply_in_progress": "❌ **Action not possible**\nYou are already filling out an application right now. If there is an error, just click the button below to start filling it out again.",
|
||||||
|
"reapply_restarted": "🔁 **Restarted**\nStarted filling out the application form again.",
|
||||||
|
"reapply_left_chat": "⚠️ **Reminder**\nIt seems that you left the chat in the past, but your profile is still available for use. Would you like to request membership using your old profile?",
|
||||||
|
"birthday": "User **{0}** (@{1}) has a birthday today! Turned {2} years old",
|
||||||
|
"application_invalid_syntax": "Invalid syntax! `/application ID/NAME/USERNAME`",
|
||||||
|
"warned": "**{0}** (`{1}`) rule violation warned",
|
||||||
|
"warned_reason": "Warned **{0}** (`{1}`)\n\n**Cause:**\n{2}",
|
||||||
|
"warnings_1": "User **{0}** (`{1}`) has **{2}** warnings",
|
||||||
|
"warnings_2": "User **{0}** (`{1}`) has **{2}** warnings",
|
||||||
|
"no_warnings": "User **{0}** (`{1}`) has no warnings",
|
||||||
|
"no_user_warnings": "No users found for query **{0}**",
|
||||||
|
"syntax_warnings": "Invalid syntax! `/warnings ID/NAME/USERNAME`",
|
||||||
|
"message_sent": "Message sent",
|
||||||
|
"message_no_user": "⚠️ **Sending Error**\nThe user ID provided is incorrect, so it was not possible to send the message to the user. Check if the ID is the same as the number that was shown in the Application.",
|
||||||
|
"message_invalid_syntax": "Invalid syntax! `/message ID MESSAGE`",
|
||||||
|
"message_from": "Message from **{0}** (`{1}`):\n\n",
|
||||||
|
"message_reply_notice": "\n\n**To send a reply to this message, tag it.**",
|
||||||
|
"message_error": "⚠️ **Error occurred**\nYour message could not be sent. The developer has been notified of this error.",
|
||||||
|
"message_traceback": "⚠️ **Error occurred**\nMessage error: `{0}` -> `{1}`\nError: `{2}`\n\nTraceback:\n```\n{3}\n```",
|
||||||
|
"no_user_application": "No users found for the query **{0}**",
|
||||||
|
"user_invalid": "The submitted user does not have a completed application.",
|
||||||
|
"joined_false_link": "User **{0}** (`{1}`) did not join the group using their link.",
|
||||||
|
"question_titles": {
|
||||||
|
"question1": "Name:",
|
||||||
|
"question2": "Birthday:",
|
||||||
|
"question3": "Residence:",
|
||||||
|
"question4": "Learned about Hololive:",
|
||||||
|
"question5": "Found interesting about Holo:",
|
||||||
|
"question6": "Like the content of:",
|
||||||
|
"question7": "Japanese hololive girls:",
|
||||||
|
"question8": "Watching streams:",
|
||||||
|
"question9": "Like songs:",
|
||||||
|
"question10": "About me:"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"keyboard": {
|
||||||
|
"welcome": [
|
||||||
|
[
|
||||||
|
"Yes, of course"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"No, thank you."
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"return": [
|
||||||
|
[
|
||||||
|
"I changed my mind, I want to"
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"confirm": [
|
||||||
|
[
|
||||||
|
"Yes, everything is correct"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"No, re-fill"
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"force_reply": {
|
||||||
|
"question1": "Name",
|
||||||
|
"question2": "Birthday",
|
||||||
|
"question3": "City or region",
|
||||||
|
"question4": "Approximate time",
|
||||||
|
"question5": "Reasons, features",
|
||||||
|
"question6": "Girl's name",
|
||||||
|
"question7": "Five Japanese Holo girls",
|
||||||
|
"question8": "Yes or no",
|
||||||
|
"question9": "Name of the girl or girls",
|
||||||
|
"question10": "A bit about yourself"
|
||||||
|
},
|
||||||
|
"button": {
|
||||||
|
"sub_yes": "✅ Accept",
|
||||||
|
"sub_no": "❌ Reject",
|
||||||
|
"sub_russian": "🇷🇺 Reject (Russian)",
|
||||||
|
"accepted": "✅ Accepted",
|
||||||
|
"declined": "❌ Rejected",
|
||||||
|
"join": "Join",
|
||||||
|
"sus_allow": "✅ Confirm permission",
|
||||||
|
"sus_reject": "❌ Permanently block",
|
||||||
|
"sus_allowed": "✅ Permission granted",
|
||||||
|
"sus_rejected": "❌ User blocked",
|
||||||
|
"reapply_yes": "✅ Accept",
|
||||||
|
"reapply_no": "❌ Reject",
|
||||||
|
"reapply_old_one": "✅ Send old one",
|
||||||
|
"reapply_new_one": "🔁 Fill in again",
|
||||||
|
"rules_home": "🏠 Home",
|
||||||
|
"rules_additional": "➕ Additional",
|
||||||
|
"rules_next": "Next ➡️",
|
||||||
|
"rules_prev": "⬅️ Back",
|
||||||
|
"applying_stop": "🛑 Interrupt filling",
|
||||||
|
"done": "✅ Done"
|
||||||
|
},
|
||||||
|
"callback": {
|
||||||
|
"sub_accepted": "✅ Application {0} has been approved",
|
||||||
|
"sub_rejected": "❌ Application {0} rejected",
|
||||||
|
"sub_russian": "🇷🇺 Application {0} rejected",
|
||||||
|
"sus_allowed": "✅ Access {0} allowed",
|
||||||
|
"sus_rejected": "❌ Access {0} denied",
|
||||||
|
"nothing": "🔔 Action already performed",
|
||||||
|
"rules_page": "ℹ️ Rule {0} shown",
|
||||||
|
"rules_home": "ℹ️ Home rule shown",
|
||||||
|
"rules_additional": "ℹ️ Additional rules shown",
|
||||||
|
"reapply_stopped": "ℹ️ Application stopped."
|
||||||
|
},
|
||||||
|
"inline": {
|
||||||
|
"forbidden": {
|
||||||
|
"title": "Action not available",
|
||||||
|
"description": "You do not have permission to view this",
|
||||||
|
"message_content": "No permission to view this."
|
||||||
|
},
|
||||||
|
"not_pm": {
|
||||||
|
"title": "Action not available",
|
||||||
|
"description": "This command is not available in channels.",
|
||||||
|
"message_content": "Action not available in channels."
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"title": "",
|
||||||
|
"description": "View {0}'s application (@{1})",
|
||||||
|
"message_content": "{0} (@{1})\n\n**Application Data:**\n{2}"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"rules_msg": "📢The rules can be supplemented and changed, depending on the need. In this case, violations that were committed before the introduction (change) of the rule will not be considered violations. You will be informed about all changes in the rules by means of pinned messages. But they will not be pinned on a permanent basis, so, from time to time, check the relevance of the rules in the bot.\n\n🔔If you see how one of the participants has violated the rules, tag one of the admins in response to a message that you think is a violation. In the post to the tag, indicate on which point you saw the violation. Or send a message to any of the administrators in private messages, and briefly describe the situation.\nList of administrators: @Chirkopol @Za_NerZula @Denialvapr\nFor questions about the functioning of the bot, please contact @Profitroll2281337\n\n❗️Any prohibited content can be sent to the chat using the bot - https://t.me/spoilerobot with a full description of the content contained under the spoiler. For an incorrect or incorrect description, a warning may be issued.\n\n‼️ Deleted or modified messages are still messages on your behalf that could be seen by chat participants and can be tracked through the admin panel.\n\n🔨 For violations - you will receive a warning. If you have 3 warnings, you will be banned for a day. For repeated violations, you will be immediately punished, without additional warnings.",
|
||||||
|
"rules": [
|
||||||
|
"1️⃣) \"HoloKyiv Chat\" and \"HoloUA (Hololive Ukraine) Chat\" are created exclusively for Ukrainians (13+). They can only contain people who: \n- Were born in Ukraine and currently reside in it.\n- Were born outside Ukraine but reside in it.\n- Were born in Ukraine but currently do not reside in it.\n\"HoloUA (Hololive Ukraine) Chat\" is open to all Ukrainians. To get into it, please fill in the form and wait for it to be approved by the administrators.\n\n\"HoloKyiv Chat\" can be accessed only in person if you live in Kyiv or are a close friend of one of the chat participants. To be added to the chat, write @Chirkopol in private messages.\n🔨 If in the process of communication it turns out that you are not Ukrainian, you will be removed from the chat until you become one. No offense. We are creating an exclusively Ukrainian community.",
|
||||||
|
"2️⃣) Distribution of NSFW content with direct or partially hidden pornographic content is prohibited. The content of \"erotic nature\" should be covered with \"questionable\" body parts.\nShock content with a large presence of blood and/or physical injuries is prohibited.",
|
||||||
|
"3️⃣) Anonymity of Hololive and Holostars participants is prohibited: \n- Photos\n- Names\n- Place of residence\n- Exact age (the word \"holohegs\" does not apply)\n- Details of personal life\n- Posts from rummage accounts or mentioning them with specific data (i.e. the phrase \"something happened on Kalli's irl channel\" is allowed, but \"something happened on *irl channel name*\" - no) \n- Details from the girls' past - only superficially and without specifics (i.e. \"was an office worker\" - ok, \"was in *company_name\" - no). \nExceptions - if the girls themselves mentioned it on the archive(!) streams.... This rule does not apply to those who are no longer in Hololive, or have never been part of it. But, please, treat the personal life of other vloggers with respect, and do not exaggerate with the deanons of their personalities.",
|
||||||
|
"4️⃣) Flooding with the same type of messages, emojis, emoticons, stickers, gifs, etc. is prohibited. The approximate number of messages that can receive a warning for this rule is 5. Each situation can be considered separately, but put all your thoughts in one message.",
|
||||||
|
"5️⃣) Video and audio messages that are not intended to convey what you have heard or seen are prohibited. If you want to tell us about how your day went, but do not have the opportunity to type a message, use the magical video-to-text converter - https://t.me/voicybot",
|
||||||
|
"6️⃣) Insults, threats, bullying, humiliation, trolling of participants, their family members, friends and other circle that is close to the chat participant are prohibited. Messages like: \"go to ... \" - are also insults. You can get a warning even if it was your friend. It will be removed if your friend confirms that he is not offended by you.\n🔨 If at the request of a member or administrator, you do not change the pace of communication and do not apologize, you will receive a warning.\nIf your behavior causes a member to leave the chat, the punishment may be more severe.",
|
||||||
|
"7️⃣) It is forbidden to provoke conflicts and incite hatred between chat participants.",
|
||||||
|
"8️⃣) Racism, sexism, homophobia and condemnation of political and (or) religious prejudice are prohibited. These topics can still be part of the dialogue if they do not contain direct condemnations, insults, etc.",
|
||||||
|
"9️⃣) Avatars, nicknames, roles that violate other rules are prohibited."
|
||||||
|
],
|
||||||
|
"rules_additional": "Additional rules that are advisory in nature, and have no explicit penalties for violations:\n1️⃣) There is no ban on the Russian language in the chat. We respect every Ukrainian and do not want to incite language conflicts.\n2️↪Mn_e_20E3↩) There is no ban on Russian content in the chat. But, keep in mind that participants, for the most part, will not be interested in discussing it and it may be ignored.) Do not abuse swear words. Try to communicate in clean language.\n4️⃣) Respect the copyright of content makers. If you find art, animation, music, etc., on official resources (pixiv, twitter, deviantart, etc.), send a link to it.\nIf someone sent art from a non-official resource and you want to know its author, send a message with the text `/search` to the message with the art.",
|
||||||
|
"commands": {
|
||||||
|
"rules": "Check out the rules",
|
||||||
|
"nearby": "Show users near the area",
|
||||||
|
"reapply": "Resubmit the application",
|
||||||
|
"sponsorship": "Apply for sponsor role"
|
||||||
|
},
|
||||||
|
"commands_admin": {
|
||||||
|
"reboot": "Restart the bot",
|
||||||
|
"message": "Send a message",
|
||||||
|
"label": "Set user's nickname",
|
||||||
|
"warnings": "Check user's warnings",
|
||||||
|
"application": "Check user's application",
|
||||||
|
"applications": "Retrieve all applications as a JSON"
|
||||||
|
},
|
||||||
|
"commands_group_admin": {
|
||||||
|
"reboot": "Restart the bot",
|
||||||
|
"message": "Send a message",
|
||||||
|
"label": "Set user's nickname",
|
||||||
|
"nearby": "Show users near the area",
|
||||||
|
"warnings": "Check user's warnings",
|
||||||
|
"application": "Check user's application",
|
||||||
|
"applications": "Retrieve all applications as a JSON"
|
||||||
|
},
|
||||||
|
"commands_group_destination": {
|
||||||
|
"warn": "Warn a user",
|
||||||
|
"nearby": "Show users near the area"
|
||||||
|
}
|
||||||
|
}
|
223
locale/uk.json
223
locale/uk.json
@@ -1,67 +1,142 @@
|
|||||||
{
|
{
|
||||||
"message": {
|
"message": {
|
||||||
"start": "Привіт і ласкаво просимо!\n\nЦей бот створено для прийому заявок на вступ до нашої спільноти. Для продовження нас цікавить відповідь на одне питання:\n\nЧи хочеш ти доєднатися до українського ком'юніті фанатів Хололайв?",
|
"start": "Привіт і ласкаво просимо!\n\nМи будуємо українське ком'юніті фанатів Гололайву і раді кожному, хто поділяє наші інтереси або тільки зацікавився цією тематикою та хоче дізнатись більше. Чим ми відрізняеємось від звичайного тематичного чату? Ми намагаємось створювати усі можливі умови, щоб люди знаходили однодумців у своїх містах та збирались разом. Інколи проводимо великі зустрічі на честь Голо-івентів у Києві. Збираємось у Дискорді для сумісних переглядів концертів, музичних топів, ігор тощо. Проводимо різні івенти у чаті. Об'єднуємось, щоб замовляти офіційний мерч із Японії. Підтримуємо україномовних кліперів та будуємо плани по поширенню нашого ком'юніті на майбутнє.\n\nЦей бот створений для прийому заявок на вступ до нашої чат-спільноти. Усі анкети, після підтвердження адміністрацією, можуть дивитися й інші учасники чату у будь-який момент. Тому, будь ласка, віднесіться до її заповнення відповідально.\n\nЯкщо вашу анкету відхилили, то, скоріше за все:\n1) Вона порушує перше правило чату (/rules - ознайомитись перед вступом до чату).\n2) Ви намагаєтесь додати до чату \"додатковий/запасний\" акаунт.\n3) Ви не дуже відповідально віднеслись до її заповнення.\n\nЯкщо із вашою анкетою щось не так, то вам через бота прийде повідомлення від адміністраторів для вирішення питання. Якщо ви зіштовхнулись із якоюсь проблемою або бот не надсилає вам необхідні повідомлення - напишіть мені у приватні повідомлення @Chirkopol.\n\nПісля прийому вашої анкети бот згенерує вам одноразове посилання. Не забудьте перейти по ньому, щоб потрапити до чату.\n\nДля продовження, нас цікавить відповідь на питання:\nЧи хочеш ти доєднатись до українського ком'юніті фанатів Гололайв та чи зобов'язуєшся ти дотримуватися усіх правил?",
|
||||||
"goodbye": "Добре, дякуємо за чесність! Вибачте, але за таких умов ми не будемо тебе додавати до спільноти. Якщо передумаєш та захочеш приєднатись - просто натисни на кнопку.",
|
"goodbye": "Добре, дякуємо за чесність! Вибачте, але за таких умов ми не будемо тебе додавати до спільноти. Якщо передумаєш та захочеш приєднатись - просто натисни на кнопку.",
|
||||||
"privacy_notice": "Раді це чути!\n\nДля продовження треба буде заповнити невеличку анкетку. Будь ласка, віднесись до цього серйозно. Ми відповідально ставимось до персональних даних, тому ця анкета не буде передана третім особам, а буде використана лише для проходження до спільноти.",
|
"privacy_notice": "Раді це чути!\n\nДля продовження треба буде заповнити невеличку анкетку. Будь ласка, віднесись до цього серйозно. Ми відповідально ставимось до персональних даних, тому ця анкета не буде передана третім особам, а буде використана лише для проходження до спільноти та подальшої взаємодії в ній.",
|
||||||
"question1": "Як до тебе можна звертатись?",
|
"question1": "Як до тебе можна звертатись?",
|
||||||
"question2": "Коли в тебе день народження?",
|
"question2": "Коли в тебе день народження?\n\nБудь ласка, у форматі ДД.ММ.РРРР",
|
||||||
"question3": "З якого ти міста та де проживаєш зараз?\n\n⚠️ Будь ласка, не вказуйте точних адрес! \"Київщина\" може бути достатньою конкретизацією.",
|
"question3": "З якого ти міста або де проживаєш зараз?\n\n⚠️ Будь ласка, не вказуйте точних адрес! \"Київ\" або \"Київська Область\" є достатньою конкретизацією.\n\nПриклади:\n• Київ\n• Одеська область\n• Макіївка (Луганська область)",
|
||||||
"question4": "Коли вперше довелось дізнатись про Хололайв?",
|
"question4": "Коли вперше довелось дізнатись про Хололайв?",
|
||||||
"question5": "Чим тебе зацікавив Хололайв?",
|
"question5": "Чим тебе зацікавив Хололайв?",
|
||||||
"question6": "Контент якої дівчини тобі подобається найбільше?",
|
"question6": "Контент якої дівчини тобі подобається найбільше?",
|
||||||
"question7": "Назви контент хоча б п'яти японських холодівчат, які тобі подобаються найбільше.",
|
"question7": "Назви контент хоча б п'яти **__--ЯПОНСЬКИХ--__** холодівчат, які тобі подобаються найбільше.",
|
||||||
"question8": "Чи дивишся ти стріми дівчат Хололайву?",
|
"question8": "Чи дивишся ти стріми дівчат Хололайву?",
|
||||||
"question9": "Чиї пісні з Хололайву тобі подобаються найбільше?",
|
"question9": "Чиї пісні з Хололайву тобі подобаються найбільше?",
|
||||||
"question10": "Ну і нарешті, розкажи трохи про себе. Про хобі, чим тобі подобається займатись. Одним повідомленням, будь ласка.",
|
"question10": "Ну і нарешті, розкажи трохи про себе. Про хобі, чим тобі подобається займатись. Одним повідомленням, будь ласка.",
|
||||||
|
"question_too_long": "Текст занадто довгий. Будь ласка, умісти відповідь у 256 символів.",
|
||||||
"question2_underage": "Вибач, але треба досягти віку {0} років, щоб приєднатись до нас. Такі обмеження існують для того, щоб всім у спільноті було цікаво одне з одним.",
|
"question2_underage": "Вибач, але треба досягти віку {0} років, щоб приєднатись до нас. Такі обмеження існують для того, щоб всім у спільноті було цікаво одне з одним.",
|
||||||
"question2_invalid": "Будь ласка, введи дату формату `ДД.ММ.РРРР`",
|
"question2_invalid": "Будь ласка, введи дату формату `ДД.ММ.РРРР`",
|
||||||
"question2_joke": "Шутнік, ми так і поняли. Але будь ласка, введи реальне значення.",
|
"question2_joke": "Шутнік, ми так і поняли. Але будь ласка, введи реальне значення.",
|
||||||
|
"question3_invalid": "Місто/населений пункт не знайдено. Користуйтесь прикладами нижче щоб вказати де ви проживаєте та спробуйте ще раз:\n\n• Київ\n• Одеська область\n• Макіївка (Луганська область)",
|
||||||
|
"question3_found": "Використовую наступний результат:\n• {0} ({1})",
|
||||||
|
"question3_error": "⚠️ **Сталась помилка**\nНе вдалось отримати географічну мітку. Розробника повідомлено про цю помилку. Будь ласка, спробуйте ще раз.",
|
||||||
|
"question3_traceback": "⚠️ **Сталась помилка**\nПомилка отримання геокодингу для `{0}`\nПомилка: `{1}`\n\nTraceback:\n```\n{2}\n```",
|
||||||
|
"question10_too_long": "Текст занадто довгий. Будь ласка, умісти відповідь у 1024 символи.",
|
||||||
|
"sponsorship_apply": "ℹ️ Оформіть платну підписку на когось з Холо, заповніть форму та отримайте особливу роль в якості винагороди!",
|
||||||
|
"sponsorship_applying": "ℹ️ Розпочато заповнення форми на отримання бонусів за платну підписку на холодівчат.",
|
||||||
|
"sponsor1": "На яку саме дівчину платна підписка?",
|
||||||
|
"sponsor1_invalid": "Будь ласка, введіть ім'я не довше за 240 символів",
|
||||||
|
"sponsor2": "До якої дати (`ДД.ММ.РРРР`) підписка?",
|
||||||
|
"sponsor2_invalid": "Будь ласка, введи дату формату `ДД.ММ.РРРР`",
|
||||||
|
"sponsor2_past": "Вказана дата знаходиться в минулому. Будь ласка, вкажіть правильний термін дії підписки",
|
||||||
|
"sponsor3": "Будь ласка, надішли одне фото для підтвердження дійсності підписки\n\nℹ️ **Підказка**\nПрочитай як правильно скрінити легітимне підтвердження підписки: https://telegra.ph/Pіdpiska-na-holo-dіvchinu-01-02",
|
||||||
|
"sponsor4": "Яку роль ти бажаєш отримати?\n\nℹ️ **Підказка**\nНазва ролі повинна бути якось пов'язана зі вказаною дівчиною, не повинна порушувати правила спільноти а також має бути не довше за 16 символів (обмеження Telegram).",
|
||||||
|
"sponsorship_application_empty": "❌ **Дія неможлива**\nУ тебе немає заповненої та схваленої анкети. Заповни таку за допомогою /reapply та спробуй ще раз після її підтвердження.",
|
||||||
"confirm": "Супер, дякуємо!\n\nБудь ласка, перевір правильність даних:\n{0}\n\nВсе правильно?",
|
"confirm": "Супер, дякуємо!\n\nБудь ласка, перевір правильність даних:\n{0}\n\nВсе правильно?",
|
||||||
"application_sent": "Дякуємо! Ми надіслали твою анкетку на перевірку. Ти отримаєш повідомлення як тільки її перевірять та приймуть рішення. До тих пір від тебе більше нічого не потребується. Гарного дня! :)",
|
"sponsor_confirm": "**Дані форми:**\nСтрімер: {0}\nПідписка до: {1}\nХочу роль: {2}\n\nПеревір чи все правильно та жмакни кнопку на клавіатурі щоб продовжити.",
|
||||||
"application_got": "Отримано анкету від `{0}`\n\nІм'я тг: `{1}`, `{2}`\nЮзернейм: @{3}\n\n**Дані анкети:**\n{4}",
|
"application_sent": "Дякуємо! Ми надіслали твою анкетку на перевірку. Ти отримаєш повідомлення, як тільки її перевірять та приймуть рішення.. До тих пір від тебе більше нічого не потребується :)",
|
||||||
"reapply_got": "Отримано змінити анкети від `{0}`\n\nІм'я тг: `{1}`, `{2}`\nЮзернейм: @{3}\n\n**Дані анкети:**\n{4}",
|
"sponsorship_sent": "Дякуємо! Ми надіслали форму на перевірку. Ти отримаєш повідомлення, як тільки її перевірять та приймуть рішення. :)",
|
||||||
|
"application_got": "Отримано анкету від `{0}`\n\nІм'я тг: `{1}`\nЮзернейм: @{2}\n\n**Дані анкети:**\n{3}",
|
||||||
|
"reapply_got": "Отримано оновлення анкети від `{0}`\n\nІм'я тг: `{1}`\nЮзернейм: @{2}\n\n**Дані анкети:**\n{3}",
|
||||||
|
"sponsor_got": "Отримано форму на спонсорство від `{0}`\n\nІм'я тг: `{1}`\nЮзернейм: @{2}\n\n**Дані форми:**\n{3}",
|
||||||
"shutdown": "Вимкнення бота з підом `{0}`",
|
"shutdown": "Вимкнення бота з підом `{0}`",
|
||||||
"startup": "Запуск бота з підом `{0}`",
|
"startup": "Запуск бота з підом `{0}`",
|
||||||
"startup_downtime": "Запуск бота з підом `{0}` (лежав {1})",
|
"startup_downtime_minutes": "Запуск бота з підом `{0}` (лежав {1} хв.)",
|
||||||
"approved": "Вітаємо! Твою анкету переглянули та підтвердили твоє право на вступ. Скористайся кнопкою під повідомленням щоб вступити до нашої лампової спільноти!",
|
"startup_downtime_hours": "Запуск бота з підом `{0}` (лежав {1} год.)",
|
||||||
|
"startup_downtime_days": "Запуск бота з підом `{0}` (лежав {1} дн.)",
|
||||||
|
"approved": "Вітаємо! Твою анкету переглянули та підтвердили твоє право на вступ.\n\nПеред тим, як ти натиснеш на кнопочку під повідомленням, щоб вступити до нашої лампової спільноти, дамо тобі трішечки додаткової інформації.\nПам'ятай, що натискаючи її, ти підтверджуєш, що ознайомився із нашими правилами (/rules) та зобов'язуєшся їх дотримуватись.\n\nПісля того, як потрапиш до чату, не закидуй цього бота далеко.\nПрописавши @holoua_bot у боті, ти відкриєш список із усіх наших анкет. Ти можеш натискати на будь-яку із них та дізнаватись про кожного із нас більше інформації.\nЗавдяки команді /nearby, ти зможеш дізнатись, чи є серед нас однодумці із твого міста.\nЯкщо у тебе є спонсорська підписка на будь-кого із учасниць Гололайву, то ти маєш право отримати унікальну роль у нашому чаті (/sponsorship) та виділятись серед інших учасників. (А ще зможеш отримати декілька додаткових функцій. Але нікому про це не кажи!)",
|
||||||
"approved_joined": "Вітаємо! Твою анкету переглянули та підтвердили її правильність. Дякуємо за витрачений на заповнення час та гарного дня!",
|
"approved_joined": "Вітаємо! Твою анкету переглянули та підтвердили її правильність. Дякуємо за витрачений на заповнення час та гарного дня!",
|
||||||
"read_rules": "Будь ласка, прочитай ці правила перш ніж натискати на кнопку та приєднуватись до чату.",
|
"read_rules": "Будь ласка, прочитай ці правила перш ніж натискати на кнопку та приєднуватись до чату.",
|
||||||
"refused": "Ой лишенько! Твою анкету переглянули, однак не підтвердили право на вступ до спільноти. Better luck next time!",
|
"rejected": "Ой лишенько! Твою анкету переглянули, однак не підтвердили право на вступ до спільноти. Better luck next time!\n\nТи можеш спробувати повторно заповнити анкету командою /reapply",
|
||||||
"refused_russian": "русский военньій корабль, иди нахуй!",
|
"rejected_russian": "русский военньій корабль, иди нахуй!",
|
||||||
"approved_by": "✅ **Анкету схвалено**\nАдмін **{0}** переглянув та схвалив анкету `{1}`.",
|
"approved_by": "✅ **Анкету схвалено**\nАдмін **{0}** переглянув та схвалив анкету `{1}`.",
|
||||||
"refused_by": "❌ **Анкету відхилено**\nАдмін **{0}** переглянув та відхилив анкету `{1}`.",
|
"rejected_by": "❌ **Анкету відхилено**\nАдмін **{0}** переглянув та відхилив анкету `{1}`.",
|
||||||
"refused_by_agr": "❌ **Анкету відхилено**\nАдмін **{0}** переглянув та відхилив анкету `{1}`, заборонивши вступ до спільноти.\nПричина: агресивна/токсична анкета.",
|
"rejected_by_agr": "❌ **Анкету відхилено**\nАдмін **{0}** переглянув та відхилив анкету `{1}`, заборонивши вступ до спільноти.\nПричина: агресивна/токсична анкета.",
|
||||||
"refused_by_rus": "❌ **Анкету відхилено**\nАдмін **{0}** переглянув та відхилив анкету `{1}`, заборонивши вступ до спільноти.\nПричина: русня.",
|
"rejected_by_rus": "❌ **Анкету відхилено**\nАдмін **{0}** переглянув та відхилив анкету `{1}`, заборонивши вступ до спільноти.\nПричина: русня.",
|
||||||
|
"sponsor_approved": "Вітаємо! Твою форму переглянули та підтвердили її правильність. Коли термін дії наданої підписки буде добігати кінця - ми нагадаємо, що треба оновити дані аби й надалі отримувати плюшки в чаті. Також можна повторно заповнити форму, якщо хочеться змінити бажане ім'я ролі або подовжити термін дії підписки завчасно, за допомогою команди /sponsorship. Гарного дня!",
|
||||||
|
"sponsor_rejected": "Ой лишенько! Твою форму переглянули, однак не підтвердили її. Можливо, щось не так з датами, або ж бажана роль не може бути надана.\n\nТи можеш спробувати повторно заповнити форму командою /sponsorship",
|
||||||
|
"sponsor_approved_by": "✅ **Підписку схвалено**\nАдмін **{0}** переглянув та схвалив форму `{1}`.",
|
||||||
|
"sponsor_rejected_by": "❌ **Підписку відхилено**\nАдмін **{0}** переглянув та відхилив форму `{1}`.",
|
||||||
"contact": "Анкета `{0}`\n\n**Дані анкети:**\n{1}\n\n{2}",
|
"contact": "Анкета `{0}`\n\n**Дані анкети:**\n{1}\n\n{2}",
|
||||||
"application_status_accepted": "Прийнята `{0}` від {1}",
|
"application_status_accepted": "Прийнята `{0}` від {1}",
|
||||||
"application_status_refused": "Відхилена `{0}` від {1}",
|
"application_status_rejected": "Відхилена `{0}` від {1}",
|
||||||
"application_status_on_hold": "Анкета все ще на розгляді",
|
"application_status_on_hold": "Анкета все ще на розгляді",
|
||||||
"application_status_not_send": "Анкета ще не була відправлена",
|
"application_status_not_send": "Анкета ще не була відправлена",
|
||||||
"contact_invalid": "Надісланий контакт не має розпочатої анкети.",
|
"contact_invalid": "Надісланий контакт не має завершеної анкети.",
|
||||||
"contact_not_member": "Надісланий контакт не є користувачем Telegram.",
|
"contact_not_member": "Надісланий контакт не є користувачем Telegram.",
|
||||||
"already_sent": "Анкету вже надіслано, просто почекай. Тобі одразу повідомлять, яке рішення буде прийнято.",
|
"already_sent": "Анкету вже надіслано, просто почекай. Тобі одразу повідомлять, яке рішення буде прийнято.",
|
||||||
"sus_joined": "Користувач **{0}** (`{1}`) зайшов до групи не за своїм персональним запрошенням.",
|
"sus_joined": "Користувач **{0}** (`{1}`) зайшов до групи не за своїм персональним запрошенням.",
|
||||||
"sus_allowed_by": "✅ **Доступ дозволено**\nАдмін **{0}** дозволив `{1}` вступити до спільноти не за персональним посиланням.",
|
"sus_allowed_by": "✅ **Доступ дозволено**\nАдмін **{0}** дозволив `{1}` вступити до спільноти не за персональним посиланням.",
|
||||||
"sus_refused_by": "❌ **Доступ заборонено**\nАдмін **{0}** заборонив `{1}` доступ до спільноти не за персональним посиланням.",
|
"sus_rejected_by": "❌ **Доступ заборонено**\nАдмін **{0}** заборонив `{1}` доступ до спільноти не за персональним посиланням.",
|
||||||
"reapply_forbidden": "❌ **Дія неможлива**\nТвоя минула анкета ще не була схвалена або відхилена.",
|
"reapply_forbidden": "❌ **Дія неможлива**\nТвоя минула анкета ще не була схвалена або відхилена.",
|
||||||
"reapply_in_progress": "❌ **Дія неможлива**\nТи прямо зараз вже заповнюєш анкету. Якщо в ній є помилка - просто натисни кнопку нижче щоб почати заповнювати спочатку.",
|
"reapply_in_progress": "❌ **Дія неможлива**\nТи прямо зараз вже заповнюєш анкету. Якщо в ній є помилка - просто натисни кнопку нижче щоб почати заповнювати спочатку.",
|
||||||
"reapply_restarted": "🔁 **Перезапущено**\nРозпочате заповнення анкети спочатку.",
|
"reapply_restarted": "🔁 **Перезапущено**\nРозпочате заповнення анкети спочатку.",
|
||||||
"reapply_left_chat": "⚠️ **Нагадування**\nЗдається, ти залишив чат у минулому, проте твоя анкета все ще доступна до використання. Подати запит на вступ користуючись старою анкетою?",
|
"reapply_left_chat": "⚠️ **Нагадування**\nЗдається, ти залишив чат у минулому, проте твоя анкета все ще доступна до використання. Подати запит на вступ користуючись старою анкетою?",
|
||||||
"birthday": "У користувача **{0}** (@{1}) сьогодні день народження! Виповнилось {2} років",
|
"birthday": "У користувача **{0}** (@{1}) сьогодні день народження! Виповнилось {2} років",
|
||||||
"application_invalid_syntax": "Неправильний синтаксис!\nТреба: `/application ID/NAME/USERNAME`",
|
"application_invalid_syntax": "Неправильний синтаксис!\nТреба: `/application ID/NAME/USERNAME`",
|
||||||
"warned": "Попереджено користувача **{0}** (`{1}`) про порушення правил",
|
"warned": "Попереджено **{0}** (`{1}`) про порушення правил",
|
||||||
"warnings_1": "Користувач **{0}** (`{1}`) має **{2}** попередження",
|
"warned_reason": "Попереджено **{0}** (`{1}`)\n\n**Причина:**\n{2}",
|
||||||
"warnings_2": "Користувач **{0}** (`{1}`) має **{2}** попереджень",
|
"warnings_1": "Користувач **{0}** (`{1}`) має **{2}** попередження\n\nОбрати та зняти попередження:\n`/warnings {3} revoke`",
|
||||||
|
"warnings_2": "Користувач **{0}** (`{1}`) має **{2}** попереджень\n\nОбрати та зняти попередження:\n`/warnings {3} revoke`",
|
||||||
|
"warnings_all": "**Список попереджень**\n\n{0}\n\nДля перегляду попереджень окремо взятого користувача слід використовувати `/warnings ID/NAME/USERNAME`",
|
||||||
|
"warnings_entry": "• {0} (`{1}`)\n Попереджень: {2}",
|
||||||
|
"warnings_empty": "Щось тут порожньо...\nЗ іншого боку, це добре!",
|
||||||
|
"warnings_revoke": "**Попередження {0}:**\n\n{1}\n\nБудь ласка, користуйтесь клавіатурою щоб зняти попередження з відповідним номером.",
|
||||||
"no_warnings": "Користувач **{0}** (`{1}`) не має попереджень",
|
"no_warnings": "Користувач **{0}** (`{1}`) не має попереджень",
|
||||||
"no_user_warnings": "Не знайдено користувачів за запитом **{0}**",
|
"no_user_warnings": "Не знайдено користувачів за запитом **{0}**",
|
||||||
"syntax_warnings": "Неправильний синтаксис!\nТреба: `/warnings ID/NAME/USERNAME`",
|
"syntax_warnings": "Неправильний синтаксис!\nТреба: `/warnings ID/NAME/USERNAME`",
|
||||||
|
"syntax_export": "Неправильний синтаксис!\nТреба: `/export applications/warnings/sponsorships/bans`",
|
||||||
|
"message_enter": "Надішліть повідомлення, яке треба переслати адмінам.\n\nЗверніть увагу, що повідомлення може містити лише одне медіа або файл.",
|
||||||
"message_sent": "Повідомлення надіслано",
|
"message_sent": "Повідомлення надіслано",
|
||||||
"message_no_user": "⚠️ **Помилка надсилання**\nВказано невірний ID користувача, тому не вдалось надіслати йому повідомлення. Перевірте чи в якості ID надано те число, яке було показане в анкеті.",
|
"message_no_user": "⚠️ **Помилка надсилання**\nВказано невірний ID користувача, тому не вдалось надіслати йому повідомлення. Перевірте чи в якості ID надано те число, яке було показане в анкеті.",
|
||||||
"message_invalid_syntax": "Неправильний синтаксис!\nТреба: `/message ID ПОВІДОМЛЕННЯ`",
|
"message_invalid_syntax": "Неправильний синтаксис!\nТреба: `/message ID ПОВІДОМЛЕННЯ`",
|
||||||
"message_from": "Повідомлення від **{0}** (`{1}`):\n\n",
|
"message_from": "Повідомлення від **{0}** (`{1}`):\n\n",
|
||||||
"message_reply_notice": "\n\n**Щоб надіслати відповідь на це повідомлення, тегніть його.**",
|
"message_reply_notice": "\n\n__Для того, щоб адміністрація побачила вашу відповідь, відправте її **реплаєм на це повідомлення**__",
|
||||||
"message_error": "⚠️ **Сталась помилка**\nНе вдалось надіслати ваше повідомлення. Розробника повідомлено про цю помилку.",
|
"message_error": "⚠️ **Сталась помилка**\nНе вдалось надіслати ваше повідомлення. Розробника повідомлено про цю помилку.",
|
||||||
"message_traceback": "⚠️ **Сталась помилка**\nПомилка повідомлень: `{0}` -> `{1}`\nПомилка: `{2}`\n\nTraceback:\n```\n{3}\n```",
|
"message_traceback": "⚠️ **Сталась помилка**\nПомилка повідомлень: `{0}` -> `{1}`\nПомилка: `{2}`\n\nTraceback:\n```\n{3}\n```",
|
||||||
|
"no_user_application": "Не знайдено користувачів за запитом **{0}**",
|
||||||
|
"user_invalid": "Надісланий користувач не має завершеної анкети.",
|
||||||
|
"joined_false_link": "Користувач **{0}** (`{1}`) приєднався до групи не за своїм посиланням",
|
||||||
|
"joined_application": "{0} (@{1})\n\n**Дані анкети:**\n{2}",
|
||||||
|
"sponsorships_expires": "⚠️ **Нагадування**\nНадана платна підписка припинить діяти **за {0} д**. Будь ласка, оновіть дані про неї командою /sponsorship інакше роль буде втрачено!",
|
||||||
|
"sponsorships_expired": "⚠️ **Нагадування**\nТермін дії вказаної підписки сплив. Для повторного отримання ролі користуйся командою /sponsorship.",
|
||||||
|
"label_too_long": "Довжина назви ролі не повинна перевищувати 16 символів",
|
||||||
|
"finish_sponsorship": "❌ **Дія неможлива**\nПерш ніж заповнювати анкету, треба завершити заповнення форми спонсора або перервати його командою /cancel.",
|
||||||
|
"finish_application": "❌ **Дія неможлива**\nПерш ніж заповнювати форму спонсора, треба завершити заповнення анкети.",
|
||||||
|
"nearby_invalid": "ℹ️ **Місце не знайдено**\nЗа наданим запитом не знайдено місце з координатами. Спробуйте ще раз формулючи запит в стилі \"Чернівці\" або \"Київська область\".",
|
||||||
|
"nearby_error": "⚠️ **Сталась помилка**\n\nПомилка: `{0}`\n\nTraceback:\n```\n{1}\n```",
|
||||||
|
"nearby_result": "Результати пошуку:\n\n{0}",
|
||||||
|
"nearby_empty": "Здається, нікого поблизу немає.",
|
||||||
|
"cancel": "Всі поточні операції скасовано.",
|
||||||
|
"cancel_reapply": "Всі поточні операції скасовано.\nЩоб знову заповнити анкету користуйся /reapply",
|
||||||
|
"identify_invalid_syntax": "Неправильний синтаксис!\nТреба: `/identify ID/NAME/USERNAME`",
|
||||||
|
"identify_not_found": "Не знайдено користувачів за запитом **{0}**",
|
||||||
|
"identify_success": "Користувач `{0}`\n\nІм'я: {1}\nЮзернейм: {2}\nЄ в чаті: {3}\nЄ адміном: {4}\nРоль: {5}\nНаявна анкета: {6}\nНаявне спонсорство: {7}",
|
||||||
|
"spoiler_started": "Розпочато створення спойлера. Будь ласка, оберіть категорію спойлера за допомогою клавіатури бота.",
|
||||||
|
"spoiler_unfinished": "У вас ще є незавершений спойлер. Надішліть /cancel щоб зупинити його створення",
|
||||||
|
"spoiler_cancel": "Створення спойлера було припинено",
|
||||||
|
"spoiler_described": "Спойлер категорії \"{0}\": {1}",
|
||||||
|
"spoiler_described_named": "Спойлер категорії \"{0}\" від **{1}**: {2}",
|
||||||
|
"spoiler_description_enter": "Добре, введіть бажаний опис спойлера",
|
||||||
|
"spoiler_description_too_long": "Текст занадто довгий. Будь ласка, умісти опис у 1024 символи.",
|
||||||
|
"spoiler_using_description": "Встановлено опис спойлера: {0}\n\nЗалишилось додати вміст самого спойлера. Бот приймає текстове повідомлення, фото, відео, файл а також гіф зображення (1 шт.)",
|
||||||
|
"spoiler_send_description": "Тепер треба надіслати коротенький опис спойлера, щоб люди розуміли що під ним варто очкувати.",
|
||||||
|
"spoiler_ready": "Успіх! Спойлер створено",
|
||||||
|
"spoiler_send": "Користуйтесь кнопкою нижче щоб надіслати його.",
|
||||||
|
"spoiler_incorrect_content": "Бот не підтримує такий контент. Будь ласка, надішли текст, фото, відео, файл або анімацію (гіф).",
|
||||||
|
"spoiler_incorrect_category": "Вказана категорія не є дійсною. Будь ласка, користуйся клавіатурою бота (кнопка біля 📎) для вибору категорії.",
|
||||||
|
"spoiler_in_progress": "❌ **Дія неможлива**\nПерш ніж починати нову дію, треба завершити створення спойлера або перервати його командою /cancel.",
|
||||||
|
"youtube_video": "На каналі [{0}]({1}) нове відео!\n\n**[{2}]({3})**",
|
||||||
|
"not_member": "❌ **Дія неможлива**\nУ тебе немає заповненої та схваленої анкети. Заповни таку за допомогою /reapply та спробуй ще раз після її підтвердження.",
|
||||||
|
"issue": "**Допоможіть боту**\nЗнайшли баг або помилку? Маєте файну ідею для нової функції? Повідомте нас, створивши нову задачу на гіті.\n\nЗа можливості, опишіть свій запит максимально детально. Якщо є змога, також додайте скріншоти або додаткову відому інформацію.",
|
||||||
|
"you_are_banned": "⚠️ **Вас було заблоковано**\nТепер не можна відправити анкету або користуватись командами бота.",
|
||||||
|
"yes": "Так",
|
||||||
|
"no": "Ні",
|
||||||
|
"voice_message": [
|
||||||
|
"why are u gae",
|
||||||
|
"руки відірвало? пиши як людина",
|
||||||
|
"унга-бунга, не маєш клавіатури?"
|
||||||
|
],
|
||||||
"question_titles": {
|
"question_titles": {
|
||||||
"question1": "Ім'я/звертання:",
|
"question1": "Ім'я/звертання:",
|
||||||
"question2": "День народження:",
|
"question2": "День народження:",
|
||||||
@@ -73,6 +148,16 @@
|
|||||||
"question8": "Дивлюсь стріми:",
|
"question8": "Дивлюсь стріми:",
|
||||||
"question9": "Подобаються пісні:",
|
"question9": "Подобаються пісні:",
|
||||||
"question10": "Про себе:"
|
"question10": "Про себе:"
|
||||||
|
},
|
||||||
|
"sponsor_titles": {
|
||||||
|
"question_streamer": "Стрімер:",
|
||||||
|
"question_expires": "Підписка до:",
|
||||||
|
"question_label": "Хоче роль:"
|
||||||
|
},
|
||||||
|
"spoiler_categories": {
|
||||||
|
"nsfw": "NSFW контент",
|
||||||
|
"deanon": "Деанон холо-учасників",
|
||||||
|
"other": "Інше"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"keyboard": {
|
"keyboard": {
|
||||||
@@ -96,6 +181,17 @@
|
|||||||
[
|
[
|
||||||
"Ні, повторно заповнити"
|
"Ні, повторно заповнити"
|
||||||
]
|
]
|
||||||
|
],
|
||||||
|
"spoiler_categories": [
|
||||||
|
[
|
||||||
|
"NSFW контент"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Деанон холо-учасників"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Інше"
|
||||||
|
]
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"force_reply": {
|
"force_reply": {
|
||||||
@@ -108,20 +204,27 @@
|
|||||||
"question7": "П'ять японських холодівчат",
|
"question7": "П'ять японських холодівчат",
|
||||||
"question8": "Так або ні",
|
"question8": "Так або ні",
|
||||||
"question9": "Ім'я дівчини або дівчин",
|
"question9": "Ім'я дівчини або дівчин",
|
||||||
"question10": "Трошки про себе"
|
"question10": "Трошки про себе",
|
||||||
|
"sponsor1": "Ім'я дівчини",
|
||||||
|
"sponsor2": "Дата до якої підписка",
|
||||||
|
"sponsor3": "Фото-підтвердження",
|
||||||
|
"sponsor4": "Бажана роль",
|
||||||
|
"spoiler_content": "Вміст спойлера",
|
||||||
|
"spoiler_description": "Опис спойлера"
|
||||||
},
|
},
|
||||||
"button": {
|
"button": {
|
||||||
"sub_yes": "✅ Прийняти",
|
"sub_yes": "✅ Прийняти",
|
||||||
"sub_no": "❌ Відхилити",
|
"sub_no": "❌ Відхилити",
|
||||||
"sub_no_aggressive": "🤡 Відхилити (Токс)",
|
"sub_russian": "🇷🇺 Відхилити (Русак)",
|
||||||
"sub_no_russian": "🇷🇺 Відхилити (Русак)",
|
"sponsor_yes": "✅ Прийняти",
|
||||||
|
"sponsor_no": "❌ Відхилити",
|
||||||
"accepted": "✅ Прийнято",
|
"accepted": "✅ Прийнято",
|
||||||
"declined": "❌ Відхилено",
|
"declined": "❌ Відхилено",
|
||||||
"join": "Приєднатись",
|
"join": "Приєднатись",
|
||||||
"sus_allow": "✅ Підтвердити дозвіл",
|
"sus_allow": "✅ Підтвердити дозвіл",
|
||||||
"sus_refuse": "❌ Перманентно заблокувати",
|
"sus_reject": "❌ Перманентно заблокувати",
|
||||||
"sus_allowed": "✅ Дозвіл надано",
|
"sus_allowed": "✅ Дозвіл надано",
|
||||||
"sus_refused": "❌ Користувача заблоковано",
|
"sus_rejected": "❌ Користувача заблоковано",
|
||||||
"reapply_yes": "✅ Прийняти",
|
"reapply_yes": "✅ Прийняти",
|
||||||
"reapply_no": "❌ Відхилити",
|
"reapply_no": "❌ Відхилити",
|
||||||
"reapply_old_one": "✅ Надіслати стару",
|
"reapply_old_one": "✅ Надіслати стару",
|
||||||
@@ -131,20 +234,36 @@
|
|||||||
"rules_next": "Далі ➡️",
|
"rules_next": "Далі ➡️",
|
||||||
"rules_prev": "⬅️ Назад",
|
"rules_prev": "⬅️ Назад",
|
||||||
"applying_stop": "🛑 Перервати заповнення",
|
"applying_stop": "🛑 Перервати заповнення",
|
||||||
"done": "✅ Готово"
|
"done": "✅ Готово",
|
||||||
|
"sponsor_apply": "Заповнити форму",
|
||||||
|
"sponsor_started": "Форму розпочато",
|
||||||
|
"spoiler_view": "Переглянути",
|
||||||
|
"spoiler_preview": "Попередній перегляд",
|
||||||
|
"spoiler_send_chat": "Надіслати в холо-чат",
|
||||||
|
"spoiler_send_other": "Надіслати в інший чат",
|
||||||
|
"issue": "🪄 Створити задачу",
|
||||||
|
"ban": "💀 Заблокувати",
|
||||||
|
"banned": "☠️ Заблоковано"
|
||||||
},
|
},
|
||||||
"callback": {
|
"callback": {
|
||||||
"sub_accepted": "✅ Анкету {0} схвалено",
|
"sub_accepted": "✅ Анкету {0} схвалено",
|
||||||
"sub_refused": "❌ Анкету {0} відхилено",
|
"sub_rejected": "❌ Анкету {0} відхилено",
|
||||||
"sub_no_aggressive": "🤡 Анкету {0} відхилено",
|
"sub_russian": "🇷🇺 Анкету {0} відхилено",
|
||||||
"sub_no_russian": "🇷🇺 Анкету {0} відхилено",
|
|
||||||
"sus_allowed": "✅ Доступ {0} дозволено",
|
"sus_allowed": "✅ Доступ {0} дозволено",
|
||||||
"sus_refused": "❌ Доступ {0} заборонено",
|
"sus_rejected": "❌ Доступ {0} заборонено",
|
||||||
|
"sub_banned": "☠️ Користувача заблоковано",
|
||||||
"nothing": "🔔 Дія вже виконана",
|
"nothing": "🔔 Дія вже виконана",
|
||||||
"rules_page": "ℹ️ Показано правило {0}",
|
"rules_page": "ℹ️ Показано правило {0}",
|
||||||
"rules_home": "ℹ️ Показано головну правил",
|
"rules_home": "ℹ️ Показано головну правил",
|
||||||
"rules_additional": "ℹ️ Показано додаткові правила",
|
"rules_additional": "ℹ️ Показано додаткові правила",
|
||||||
"reapply_stopped": "ℹ️ Перервано заповнення анкети"
|
"reapply_stopped": "ℹ️ Перервано заповнення анкети",
|
||||||
|
"sponsor_started": "ℹ️ Заповнення форми розпочато",
|
||||||
|
"sponsor_accepted": "✅ Форму {0} схвалено",
|
||||||
|
"sponsor_rejected": "❌ Форму {0} відхилено",
|
||||||
|
"spoiler_sent": "✅ Повідомлення надіслано в холо-чат",
|
||||||
|
"spoiler_forbidden": "❌ Треба бути учасником чату",
|
||||||
|
"warning_revoked": "✅ Попередження скасовано",
|
||||||
|
"warning_not_found": "❌ Попередження вже скасовано або не існує"
|
||||||
},
|
},
|
||||||
"inline": {
|
"inline": {
|
||||||
"forbidden": {
|
"forbidden": {
|
||||||
@@ -161,19 +280,41 @@
|
|||||||
"title": "",
|
"title": "",
|
||||||
"description": "Переглянути анкету {0} (@{1})",
|
"description": "Переглянути анкету {0} (@{1})",
|
||||||
"message_content": "{0} (@{1})\n\n**Дані анкети:**\n{2}"
|
"message_content": "{0} (@{1})\n\n**Дані анкети:**\n{2}"
|
||||||
|
},
|
||||||
|
"spoiler": {
|
||||||
|
"title": "Відправити",
|
||||||
|
"description": "Надіслати цей спойлер до чату"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"rules_msg": "📢Правила можуть доповнюватись та змінюватись, залежно від потреби. У такому разі, порушення, які були вчинені до введення (змінення) правила, порушеннями вважатися не будуть. Про всі зміни в правилах, ви будете проінформовані за допомогою закріплених повідомлень. Але вони не будуть закріплені на постійній основі, тому, час від часу, перевіряйте актуальність правил у боті.\n\n🔔Якщо ви бачите, як хтось із учасників порушив правила, тегніть одного із адмінів, у відповідь на повідомлення, яке, на вашу думку, є порушенням. У дописі до тегу, вкажіть, по якому пункту ви побачили порушення. Або перешліть повідомлення до будь кого із адміністраторів у особисті повідомлення, та коротко опишіть ситуацію.\nСписок адміністраторів: @Chirkopol @Za_NerZula @Denialvapr\nЗ питань функціонування бота звертайтесь до @Profitroll2281337\n\n❗️Будь-який заборонений контент, може бути відправлений до чату за допомогою бота - https://t.me/spoilerobot з повним описом контенту, що міститься під спойлером. За неправильний або некоректний опис, може бути видане попередження.\n\n‼️Видалені або змінені повідомлення, все ще є повідомленнями від вашого імені, які могли побачити учасники чату, і які можуть бути відстежені через адмінську панель.\n\n🔨 За порушення - ви отримаєте попередження. За наявності 3-х попереджень - мут на добу. За повторні порушення, ви одразу отримаєте покарання, без додаткових попереджень.",
|
"rules_msg": "📢Правила можуть доповнюватись та змінюватись, залежно від потреби. У такому разі, порушення, які були вчинені до введення (змінення) правила, порушеннями вважатися не будуть. Про всі зміни в правилах, ви будете проінформовані за допомогою закріплених повідомлень. Але вони не будуть закріплені на постійній основі, тому, час від часу, перевіряйте актуальність правил у боті.\n\n🔔Якщо ви бачите, як хтось із учасників порушив правила, тегніть одного із адмінів, у відповідь на повідомлення, яке, на вашу думку, є порушенням. У дописі до тегу, вкажіть, по якому пункту ви побачили порушення. Або перешліть повідомлення до будь кого із адміністраторів у особисті повідомлення, та коротко опишіть ситуацію.\nСписок адміністраторів: @Chirkopol @Za_NerZula @Toxinushka\nЗ питань функціонування бота звертайтесь до @Profitroll2281337\n\n❗️Будь-який заборонений контент, може бути відправлений за допомогою команди /spoiler у бота - з повним описом контенту, що міститься під спойлером. За неправильний або некоректний опис, може бути видане попередження.\n\n‼️Видалені або змінені повідомлення, все ще є повідомленнями від вашого імені, які могли побачити учасники чату, і які можуть бути відстежені через адмінську панель.\n\n🔨 За порушення - ви отримаєте попередження. За наявності 3-х попереджень - мут на добу. За повторні порушення, ви одразу отримаєте покарання, без додаткових попереджень.",
|
||||||
"rules": [
|
"rules": [
|
||||||
"1️⃣) \"HoloKyiv Chat\" та \"HoloUA (Hololive Ukraine) Chat\" створені виключно для українців (13+). В них можуть знаходитись тільки люди які: \n- Народились в Україні, та проживають, на данний момент, у ній.\n- Народились за межами України, але проживають у ній.\n- Народились в Україні але, на даний момент, не проживають у ній.\n\"HoloUA (Hololive Ukraine) Chat\" відкритий для усіх українців. Щоб потрапити до нього, заповніть, будь ласка, анкету, та дочекайтесь, поки її схвалять адміни.\nУ \"HoloKyiv Chat\" можна потрапити тільки особисто, якщо ви проживаєте у Київі, або є близьким другом одного із учасників чату. Із приводу додавання до чату пишіть @Chirkopol у приватні повідомлення.\n🔨 Якщо у процесі спілкування виявиться, що ви не українець, вас буде видалено із чату, до моменту, поки ви їм не станете. Без образ. Ми створюємо виключно українське ком'юніті.",
|
"1️⃣) \"HoloKyiv Chat\" та \"HoloUA (Hololive Ukraine) Chat\" створені виключно для українців (13+). В них можуть знаходитись тільки люди які: \n- Народились в Україні, та проживають, на данний момент, у ній.\n- Народились за межами України, але проживають у ній.\n- Народились в Україні але, на даний момент, не проживають у ній.\n\"HoloUA (Hololive Ukraine) Chat\" відкритий для усіх українців. Щоб потрапити до нього, заповніть, будь ласка, анкету, та дочекайтесь, поки її схвалять адміни.\nУ \"HoloKyiv Chat\" можна потрапити тільки особисто, якщо ви проживаєте у Київі, або є близьким другом одного із учасників чату. Із приводу додавання до чату пишіть @Chirkopol у приватні повідомлення.\n🔨 Якщо у процесі спілкування виявиться, що ви не українець, вас буде видалено із чату, до моменту, поки ви їм не станете. Без образ. Ми створюємо виключно українське ком'юніті.",
|
||||||
"2️⃣) Заборонено поширення NSFW-контенту з прямим або частково прихованим порнографічним змістом. На контенті \"еротичного характеру\" повинні бути закриті \"сумнівні\" ділянки тіл. \nЗаборонено поширення шок-контенту з великою наявністю крові та/або фізичних пошкоджень.",
|
"2️⃣) Заборонено поширення артів, на яких зображено:\n2.1 - NSFW-контент з прямим або частково прихованим порнографічним змістом.\n2.2 - Контент \"еротичного характеру\" із неприкритими \"сумнівними\" ділянками тіл (так звані \"private parts\") або їх помітними силуетами крізь одяг.\n2.3 - Фетиш-контент, який спрямований на дуже вузьке коло шанувальників та може порушувати закон. Наприклад: копрофілія, педофілія, зоофілія.\n2.4 - Шок-контент із великою кількістю крові та/або фізичних пошкоджень.\n2.5 - Контент, який порушує будь-яке інше правило.\n❗️Якщо якійсь арт викликає у вас сумніви і ви не впевнені, що він не порушує правила, скористайтесь командою /spoiler у боті. Це точно збереже вас від зайвих проблем. Але не забувайте робити опис спойлеру!",
|
||||||
"3️⃣) Анонімність учасників Хололайв та Холостарз.\nЗаборонено: \n- Фотографії\n- Імена\n- Місце проживання\n- Точний вік (слово \"холохеґз\" не підпадає)\n- Подробиці особистого життя\n- Пости з руммейт акаунтів чи згадка про них з конкретними даними (тобто фраза \"там на ірл каналі Каллі щось вийшло\" - можна, а \"там на *назва ірл каналу* щось вийшло\" - ні)\n- Подробиці з минулого дівчат - лише поверхнево і без конкретики (тобто \"була офісним працівником\" - ок, \"була в *компанія_нейм*\" - ні).\nВиключення - якщо дівчата самі згадували про це на архівних(!) стрімах.\n❗️Це правило не стосується тих, хто вже не знаходиться у Хололайві, або ніколи і не був його частиною. Але, прохання, відноситись до особистого життя інших вітуберів із повагою, та не перебільшувати із деанонами їх особистостей.",
|
"3️⃣) Анонімність учасників Гололайв та Голостарз.\nЗаборонено: \n- Фотографії.\n- Імена.\n- Місце проживання.\n- Точний вік (слово \"холохеґз\" не підпадає).\n- Подробиці особистого життя, які не було розкриті на Гололайв-акаунтах.\n- Пости з руммейт-акаунтів чи згадка про них з конкретними даними. Пояснення: фраза \"там на ірл каналі Каллі щось вийшло\" - можна, а \"там на *назва ірл каналу* щось вийшло\" - ні.\n- Подробиці з минулого дівчат - лише поверхнево і без конкретики (тобто, \"була офісним працівником\" - ок, \"була в *компанія_нейм*\" - ні).\nВиключення - якщо дівчата самі згадували про це на архівних(!) стрімах.\n❗️Це правило не стосується тих, хто вже не знаходиться у Гололайві або ніколи і не був його частиною. Але, прохання, відноситись до особистого життя інших вітуберів із повагою та не перебільшувати із деанонами їх особистостей.",
|
||||||
"4️⃣) Заборонено флуд однотипними повідомленнями, емодзі, смайликами, стікерами, гіфками тощо. Орієнтовна кількість повідомлень, які можуть отримати попередження за це правило - 5. Кожна ситуація може розглядатись окремо, але вкладайте усі свої думки в одне повідомлення.",
|
"4️⃣) Заборонено флуд однотипними текстовими повідомленнями, які не несуть у собі сенсу, емоджі, смайликами, стікерами, ґіфками, великою кількістю артів тощо. Орієнтовна кількість повідомлень, за які можна отримати попередження за це правило - 5. \nЯкщо учасник буде цілеспрямовано відправляти по менше ніж 5 повідомлень, але робити це регулярно, то попередження також може бути видане.\nПояснення: \"Відправлю зараз 4 гіфки, почекаю, поки хтось напише декілька повідомлень, і знову відправлю 4 гіфки\".\n- Попередження про флуд одночасно можуть отримати декілька учасників.\nПояснення: декілька учасників чату, по черзі, відправляють по декілька (менше п'яти) стікерів, але спільними зусиллями, і їх стає дуже багато.\n❗️Кожна ситуація може і буде розглядатись окремо, але намагайтеся вкладати всі свої думки в одне повідомлення.\n❗️Якщо ви масово відправляєте контент зі сторонніх ресурсів, будь то якісь новини у великій кількості (анонси мерчу, концертів тощо) або арти, кліпи та подібне, і ви ніяк не зможете посприяти тому, щоб уся інформація була подана більш компактно, то це правило на вас не розповсюджується, але не зловживайте цим.\n‼️Це правило не стосується організованих івентів та флешмобів, затверджених адміністраторами.",
|
||||||
"5️⃣) Заборонені відео та аудіо-повідомлення, які не несуть цілі передати почуте, або побачене. Якщо ви бажаєте розповісти про те, як пройшов ваш день, але не маєте можливості друкувати повідомлення, використовуйте магічний перетворювач войсів у текст - https://t.me/voicybot",
|
"5️⃣) Заборонені відео- та аудіо-повідомлення, які не несуть цілі передати почуте або побачене. \n❗️Якщо ви бажаєте розповісти про те, як пройшов ваш день, але не маєте можливості друкувати повідомлення, використовуйте магічний перетворювач войсів у текст - https://t.me/voicybot",
|
||||||
"6️⃣) Заборонені образи, погрози, булінг, приниження, тролінг учасників, членів їхніх сімей, друзів та іншого кола, що є наближеними до учасника чату. Повідомлення на кшталт: \"йди на ... \" - також є образами. Ви можете отримати попередження, навіть, якщо це був ваш приятель. Воно буде зняте, якщо приятель підтвердить, що не ображений на вас.\n🔨 Якщо на прохання учасника або адміністратора, ви не зміните темп спілкування і не вибачитесь, то отримаєте попередження. \n⚒ Якщо ваша поведінка спричинить те, що учасник залишив чат, покарання може бути жорсткішим.",
|
"6️⃣) Заборонені образи, погрози, булінг, приниження, тролінг учасників, членів їхніх сімей, друзів та іншого кола, що є наближеними до учасника чату. Повідомлення на кшталт: \"йди на ... \" - також є образами. Ви можете отримати попередження, навіть, якщо це був ваш приятель. Воно буде зняте, якщо приятель підтвердить, що не ображений на вас.\n🔨 Якщо на прохання учасника або адміністратора, ви не зміните темп спілкування і не вибачитесь, то отримаєте попередження. \n⚒ Якщо ваша поведінка спричинить те, що учасник залишив чат, покарання може бути жорсткішим.",
|
||||||
"7️⃣) Заборонено провокування конфліктів та розпалювання ненависті між учасниками чату.",
|
"7️⃣) Правила щодо провокаційних тем у чаті:\n7.1 - У чаті немає заборони на обговорення будь-яких тем, однак, заборонені радикальні висловлювання у бік будь-якої із позицій. Якщо ви на 100% впевнені у своїй правоті і розумієте, що будуть люди, які не поділяють вашу точку зору і ви абсолютно точно не збираєтесь прислухатися до їхньої позиції, а налаштовуєтеся на заперечення будь-якого аргументу - то закрийте чат і займіться своїми справами.\n7.2 - Відносьтесь до позиції співрозмовника із повагою. Пам'ятайте, що всі ми різні і погляди у нас, аналогічно, різні.\n7.3 - Якщо ви розумієте, що обстановка в обговоренні загострюється, то запропонуйте співрозмовнику зупинитися і розійдіться, залишившись кожен при своїй думці та намагайтеся більше на проблемну тему не спілкуватися.\n7.4 - Вкидання спірної інформації, яка може призвести до конфлікту, навіть без прямої участі в ньому, може розцінюватися як провокація.\n7.5 - Навмисні образи когось чи чогось, кому чи чому може симпатизувати хтось із учасників чату, після прохання так більше не робити, розцінюватиметься як провокація.\nПриклад: образи кого-небудь із Голо-дівчат, знаючи про те, що у чаті є ті, кому вона може бути цікава і що людині не сподобаються подібні повідомлення.\n7.6 Адміністрація, на свій розсуд, може попросити згорнути тему, якщо розуміє, що вона може призвести до конфлікту.\n❗️Кожна ситуація може розглядатися адміністрацією окремо. Ми не хочемо, щоб учасники пересварилися один з одним і вирішили залишити чат. Дані правила прописані насамперед для збереження чистоти та дружньої атмосфери. Якщо ви здатні спілкуватися на заборонені теми шляхом адекватного обміну думками та інформацією, ми можемо заплющити очі на порушення. Але це залежить лише від вашого вміння стримувати свій запал і здібностей викладати думки.",
|
||||||
"8️⃣) Заборонені прояви расизму, сексизму, гомофобії та засудження за політичні та (або) релігійні упередження. Дані теми все ще можуть бути частиною діалогу, якщо не несуть у собі прямих засуджень, образ тощо.",
|
"8️⃣) Заборонені прояви расизму, сексизму, гомофобії та засудження за політичні та (або) релігійні упередження. \n❗️Дані теми все ще можуть бути обговорювані в чаті \"з нейтральної точки зору\", якщо ви при цьому не порушуєте розділ правил 7️⃣.",
|
||||||
"9️⃣) Заборонені аватарки, нікнейми, ролі, які порушують інші правила."
|
"9️⃣) Заборонені аватарки, нікнейми, ролі, які порушують інші правила."
|
||||||
],
|
],
|
||||||
"rules_additional": "Додаткові правила, які несуть рекомендаційний характер, та не мають явних покарань за порушення:\n1️⃣) У чаті немає заборони на російську мову. Ми поважаємо кожного українця і не бажаємо розпалювати мовні конфлікти.\n2️⃣) У чаті немає заборони на російський контент. Але, майте на увазі, що учасники, здебільшого, не будуть зацікавлені у тому, щоб обговорювати його і він може бути проігнорованим.\n3️⃣) Не зловживайте матами. Намагайтесь спілкуватись чистою мовою.\n4️⃣) Поважайте авторські права контентмейкерів. Якщо ви знаходите арт, анімацію, музику тощо, на офіційних ресурсах (pixiv, twitter, deviantart тощо), відправляйте на нього посилання.\nЯкщо хтось із учасників відправив арт із не офіційного ресурсу і ви бажаєте дізнатись його автора, відправте у відповідь повідомлення із текстом `/search` на повідомлення із артом."
|
"rules_additional": "Додаткові правила, які несуть рекомендаційний характер та не мають явних покарань за порушення:\n1️⃣) У чаті немає заборони на російську мову. Ми поважаємо кожного українця і не бажаємо розпалювати мовні конфлікти.\n2️⃣) У чаті немає заборони на російський контент. Але майте на увазі, що учасники, здебільшого, не будуть зацікавлені у тому, щоб обговорювати його і він може бути проігнорованим.\n3️⃣) Не зловживайте матами. Намагайтесь спілкуватись чистою мовою.\n4️⃣) Поважайте авторські права контент-мейкерів. Якщо ви знаходите арт, анімацію, музику тощо на офіційних ресурсах (pixiv, twitter, deviantart тощо), відправляйте на нього посилання.\nЯкщо хтось із учасників відправив арт із не офіційного ресурсу і ви бажаєте дізнатись його автора, відправте у відповідь повідомлення із текстом /search на повідомлення із артом.\n5️⃣) В особливо критичних ситуаціях порушник може отримати бан або бути повністю видаленим із чату, без попереджень.\n6️⃣) Якщо з кимось із учасників у вас трапиться якесь непорозуміння і вам неприємно буде перебувати в чаті один з одним (навіть, якщо конфлікт стався з кимось із адміністраторів) - напишіть мені в особисті повідомлення @Chirkopol. Я, як засновник чату та головний адміністратор, найбільше зацікавлений у збереженні цілісності чату та розвитку нашого ком'юніті, і я зроблю все, що в моїх силах, щоб допомогти вирішити вашу ситуацію.",
|
||||||
|
"commands": {
|
||||||
|
"application": "Переглянути анкету користувача",
|
||||||
|
"cancel": "Відмінити актуальну дію",
|
||||||
|
"identify": "Дізнатись дані про користувача за айді",
|
||||||
|
"issue": "Задачі для покращення бота",
|
||||||
|
"label": "Встановити нікнейм користувачу",
|
||||||
|
"message": "Надіслати користувачу повідомлення",
|
||||||
|
"nearby": "Показати користувачів поблизу",
|
||||||
|
"export": "Експортувати дані як CSV та JSON",
|
||||||
|
"reapply": "Повторно заповнити анкету",
|
||||||
|
"reboot": "Перезапустити бота",
|
||||||
|
"resetcommands": "Відреєструвати всі команди",
|
||||||
|
"rules": "Правила спільноти",
|
||||||
|
"spoiler": "Почати створювати спойлер",
|
||||||
|
"sponsorship": "Отримати роль за спонсорство",
|
||||||
|
"warn": "Попередити користувача",
|
||||||
|
"warnings": "Переглянути попередження користувача"
|
||||||
|
}
|
||||||
}
|
}
|
38
modules/callbacks/ban.py
Normal file
38
modules/callbacks/ban.py
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from app import app, isAnAdmin
|
||||||
|
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
|
||||||
|
from pyrogram import filters
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from modules.utils import locale
|
||||||
|
from modules.database import col_bans
|
||||||
|
from modules.logging import logWrite
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_callback_query(filters.regex("ban_[\s\S]*"))
|
||||||
|
async def callback_query_reject(app: Client, clb: CallbackQuery):
|
||||||
|
fullclb = clb.data.split("_")
|
||||||
|
|
||||||
|
if not await isAnAdmin(int(fullclb[1])):
|
||||||
|
col_bans.insert_one(
|
||||||
|
{"user": int(fullclb[1]), "admin": clb.from_user.id, "date": datetime.now()}
|
||||||
|
)
|
||||||
|
|
||||||
|
edited_markup = [
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("banned", "button")), callback_data="nothing"
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
await clb.message.edit(
|
||||||
|
text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)
|
||||||
|
)
|
||||||
|
await clb.answer(text=locale("sub_banned", "callback", locale=clb.from_user))
|
||||||
|
|
||||||
|
logWrite(f"User {fullclb[1]} has been banned by {clb.from_user.id}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
await app.send_message(int(fullclb[1]), locale("you_are_banned", "message"))
|
||||||
|
except Exception as exp:
|
||||||
|
logWrite(f"Could send ban message to {fullclb[1]} due to {exp}")
|
@@ -1,9 +1,10 @@
|
|||||||
from app import app
|
from app import app
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
|
from pyrogram.types import CallbackQuery
|
||||||
|
from pyrogram.client import Client
|
||||||
from modules.utils import locale
|
from modules.utils import locale
|
||||||
|
|
||||||
# Callback empty ===============================================================================================================
|
|
||||||
@app.on_callback_query(filters.regex("nothing"))
|
@app.on_callback_query(filters.regex("nothing"))
|
||||||
async def callback_query_nothing(app, clb):
|
async def callback_query_nothing(app: Client, clb: CallbackQuery):
|
||||||
await clb.answer(text=locale("nothing", "callback"))
|
await clb.answer(text=locale("nothing", "callback", locale=clb.from_user))
|
||||||
# ==============================================================================================================================
|
|
||||||
|
@@ -1,127 +1,286 @@
|
|||||||
from os import sep
|
from datetime import datetime
|
||||||
from time import time
|
|
||||||
from app import app
|
from app import app
|
||||||
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove
|
from pyrogram.types import (
|
||||||
|
InlineKeyboardMarkup,
|
||||||
|
InlineKeyboardButton,
|
||||||
|
ReplyKeyboardRemove,
|
||||||
|
CallbackQuery,
|
||||||
|
)
|
||||||
|
from pyrogram.client import Client
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from modules.utils import configGet, configSet, jsonLoad, jsonSave, locale, logWrite
|
from classes.holo_user import HoloUser
|
||||||
|
from modules.utils import configGet, locale, logWrite
|
||||||
from modules.handlers.confirmation import confirm_yes
|
from modules.handlers.confirmation import confirm_yes
|
||||||
from modules.handlers.welcome import welcome_pass
|
from modules.handlers.welcome import welcome_pass
|
||||||
|
from modules.database import col_tmp, col_applications
|
||||||
|
|
||||||
|
|
||||||
# Callbacks reapply ============================================================================================================
|
|
||||||
@app.on_callback_query(filters.regex("reapply_yes_[\s\S]*"))
|
@app.on_callback_query(filters.regex("reapply_yes_[\s\S]*"))
|
||||||
async def callback_reapply_query_accept(app, clb):
|
async def callback_reapply_query_accept(app: Client, clb: CallbackQuery):
|
||||||
|
|
||||||
fullclb = clb.data.split("_")
|
fullclb = clb.data.split("_")
|
||||||
|
holo_user = HoloUser(int(fullclb[2]))
|
||||||
|
|
||||||
await app.send_message(configGet("admin_group"), locale("approved_by", "message").format(clb.from_user.first_name, fullclb[2]), disable_notification=True)
|
await app.send_message(
|
||||||
logWrite(f"User {fullclb[2]} got their reapplication approved by {clb.from_user.id}")
|
configGet("admin", "groups"),
|
||||||
|
locale("approved_by", "message").format(clb.from_user.first_name, holo_user.id),
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
logWrite(
|
||||||
|
f"User {holo_user.id} got their reapplication approved by {clb.from_user.id}"
|
||||||
|
)
|
||||||
|
|
||||||
await app.send_message(int(fullclb[2]), locale("approved_joined", "message"))
|
await app.send_message(
|
||||||
|
holo_user.id, locale("approved_joined", "message", locale=holo_user)
|
||||||
|
)
|
||||||
|
|
||||||
configSet(["approved"], True, file=fullclb[2])
|
applications = col_applications.find({"user": holo_user.id})
|
||||||
configSet(["sent"], False, file=fullclb[2])
|
|
||||||
|
|
||||||
application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")
|
if len(list(applications)) > 1:
|
||||||
application[fullclb[2]]["approved"] = True
|
col_applications.delete_many({"user": holo_user.id})
|
||||||
application[fullclb[2]]["approved_by"] = clb.from_user.id
|
col_applications.insert_one(
|
||||||
application[fullclb[2]]["approval_date"] = int(time())
|
{
|
||||||
jsonSave(application, f"{configGet('data', 'locations')}{sep}applications.json")
|
"user": holo_user.id,
|
||||||
|
"date": datetime.now(),
|
||||||
|
"admin": clb.from_user.id,
|
||||||
|
"application": col_tmp.find_one(
|
||||||
|
{"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}
|
||||||
|
)["application"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif applications == 1:
|
||||||
|
col_applications.find_one_and_replace(
|
||||||
|
{"user": holo_user.id},
|
||||||
|
{
|
||||||
|
"user": holo_user.id,
|
||||||
|
"date": datetime.now(),
|
||||||
|
"admin": clb.from_user.id,
|
||||||
|
"application": col_tmp.find_one(
|
||||||
|
{"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}
|
||||||
|
)["application"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
col_applications.insert_one(
|
||||||
|
{
|
||||||
|
"user": holo_user.id,
|
||||||
|
"date": datetime.now(),
|
||||||
|
"admin": clb.from_user.id,
|
||||||
|
"application": col_tmp.find_one(
|
||||||
|
{"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}
|
||||||
|
)["application"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
col_tmp.update_one(
|
||||||
|
{"user": holo_user.id, "type": "application"},
|
||||||
|
{"$set": {"state": "approved", "sent": False}},
|
||||||
|
)
|
||||||
|
|
||||||
edited_markup = [[InlineKeyboardButton(text=str(locale("accepted", "button")), callback_data="nothing")]]
|
edited_markup = [
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("accepted", "button")), callback_data="nothing"
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup))
|
await clb.message.edit(
|
||||||
await clb.answer(text=locale("sub_accepted", "callback").format(fullclb[2]), show_alert=True)
|
text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)
|
||||||
|
)
|
||||||
|
await clb.answer(
|
||||||
|
text=locale("sub_accepted", "callback", locale=clb.from_user).format(
|
||||||
|
holo_user.id
|
||||||
|
),
|
||||||
|
show_alert=True,
|
||||||
|
)
|
||||||
|
|
||||||
need_link = True
|
need_link = True
|
||||||
|
|
||||||
async for member in app.get_chat_members(configGet("destination_group")):
|
async for member in app.get_chat_members(configGet("users", "groups")):
|
||||||
if member.user.id == int(fullclb[2]):
|
if member.user.id == holo_user.id:
|
||||||
need_link = False
|
need_link = False
|
||||||
|
|
||||||
if need_link:
|
if need_link:
|
||||||
link = await app.create_chat_invite_link(configGet("destination_group"), name=f"Invite for {fullclb[2]}", member_limit=1) #, expire_date=datetime.now()+timedelta(days=1))
|
link = await app.create_chat_invite_link(
|
||||||
|
configGet("users", "groups"),
|
||||||
|
name=f"Invite for {holo_user.id}",
|
||||||
|
member_limit=1,
|
||||||
|
) # , expire_date=datetime.now()+timedelta(days=1))
|
||||||
|
|
||||||
await app.send_message(int(fullclb[2]), locale("read_rules", "message"))
|
await app.send_message(
|
||||||
|
holo_user.id, locale("read_rules", "message", locale=holo_user)
|
||||||
|
)
|
||||||
|
|
||||||
for rule_msg in locale("rules"):
|
for rule_msg in locale("rules", locale=holo_user):
|
||||||
await app.send_message(int(fullclb[2]), rule_msg)
|
await app.send_message(holo_user.id, rule_msg)
|
||||||
|
|
||||||
await app.send_message(int(fullclb[2]), locale("approved", "message"), reply_markup=InlineKeyboardMarkup(
|
await app.send_message(
|
||||||
[[
|
holo_user.id,
|
||||||
InlineKeyboardButton(str(locale("join", "button")), url=link.invite_link)
|
locale("approved", "message"),
|
||||||
]]
|
reply_markup=InlineKeyboardMarkup(
|
||||||
))
|
[
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
str(locale("join", "button", locale=holo_user)),
|
||||||
|
url=link.invite_link,
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
configSet(["link"], link.invite_link, file=fullclb[2])
|
holo_user.set("link", link.invite_link)
|
||||||
logWrite(f"User {fullclb[2]} got an invite link {link.invite_link}")
|
logWrite(f"User {holo_user.id} got an invite link {link.invite_link}")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
await app.send_message(int(fullclb[2]), locale("approved_joined", "message"))
|
await app.send_message(
|
||||||
|
holo_user.id, locale("approved_joined", "message", locale=holo_user)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.on_callback_query(filters.regex("reapply_no_[\s\S]*"))
|
@app.on_callback_query(filters.regex("reapply_no_[\s\S]*"))
|
||||||
async def callback_query_reapply_refuse(app, clb):
|
async def callback_query_reapply_reject(app: Client, clb: CallbackQuery):
|
||||||
|
|
||||||
fullclb = clb.data.split("_")
|
fullclb = clb.data.split("_")
|
||||||
|
holo_user = HoloUser(int(fullclb[2]))
|
||||||
|
|
||||||
await app.send_message(configGet("admin_group"), locale("refused_by", "message").format(clb.from_user.first_name, fullclb[2]), disable_notification=True)
|
await app.send_message(
|
||||||
await app.send_message(int(fullclb[2]), locale("refused", "message"))
|
configGet("admin", "groups"),
|
||||||
logWrite(f"User {fullclb[2]} got their reapplication refused by {clb.from_user.id}")
|
locale("rejected_by", "message").format(clb.from_user.first_name, fullclb[2]),
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
await app.send_message(
|
||||||
|
holo_user.id, locale("rejected", "message", locale=holo_user)
|
||||||
|
)
|
||||||
|
logWrite(
|
||||||
|
f"User {fullclb[2]} got their reapplication rejected by {clb.from_user.id}"
|
||||||
|
)
|
||||||
|
|
||||||
configSet(["refused"], True, file=fullclb[2])
|
col_tmp.update_one(
|
||||||
configSet(["sent"], False, file=fullclb[2])
|
{"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}},
|
||||||
|
{"$set": {"state": "rejected", "sent": False}},
|
||||||
|
)
|
||||||
|
|
||||||
application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")
|
edited_markup = [
|
||||||
application[fullclb[2]]["refused"] = True
|
[
|
||||||
application[fullclb[2]]["refused_by"] = clb.from_user.id
|
InlineKeyboardButton(
|
||||||
application[fullclb[2]]["refusal_date"] = int(time())
|
text=str(locale("declined", "button")), callback_data="nothing"
|
||||||
jsonSave(application, f"{configGet('data', 'locations')}{sep}applications.json")
|
)
|
||||||
|
],
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("ban", "button")), callback_data=f"ban_{fullclb[2]}"
|
||||||
|
)
|
||||||
|
],
|
||||||
|
]
|
||||||
|
|
||||||
edited_markup = [[InlineKeyboardButton(text=str(locale("declined", "button")), callback_data="nothing")]]
|
await clb.message.edit(
|
||||||
|
text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)
|
||||||
|
)
|
||||||
|
await clb.answer(
|
||||||
|
text=locale("sub_rejected", "callback", locale=clb.from_user).format(
|
||||||
|
fullclb[2]
|
||||||
|
),
|
||||||
|
show_alert=True,
|
||||||
|
)
|
||||||
|
|
||||||
await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup))
|
|
||||||
await clb.answer(text=locale("sub_refused", "callback").format(fullclb[2]), show_alert=True)
|
|
||||||
|
|
||||||
# Use old application when user reapplies after leaving the chat
|
# Use old application when user reapplies after leaving the chat
|
||||||
@app.on_callback_query(filters.regex("reapply_old_[\s\S]*"))
|
@app.on_callback_query(filters.regex("reapply_old_[\s\S]*"))
|
||||||
async def callback_query_reapply_old(app, clb):
|
async def callback_query_reapply_old(app: Client, clb: CallbackQuery):
|
||||||
fullclb = clb.data.split("_")
|
fullclb = clb.data.split("_")
|
||||||
|
holo_user = HoloUser(clb.from_user)
|
||||||
|
|
||||||
|
if holo_user.sponsorship_state()[0] == "fill":
|
||||||
|
await clb.message.reply_text(
|
||||||
|
locale("finish_sponsorship", "message"), quote=False
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
message = await app.get_messages(clb.from_user.id, int(fullclb[2]))
|
message = await app.get_messages(clb.from_user.id, int(fullclb[2]))
|
||||||
configSet(["approved"], False, file=str(clb.from_user.id))
|
|
||||||
configSet(["refused"], False, file=str(clb.from_user.id))
|
if (
|
||||||
await confirm_yes(app, message)
|
col_tmp.find_one({"user": holo_user.id, "type": "application"}) is None
|
||||||
await clb.message.edit(clb.message.text, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("done", "button"), "nothing")]]))
|
and col_applications.find_one({"user": holo_user.id}) is not None
|
||||||
|
):
|
||||||
|
col_tmp.insert_one(
|
||||||
|
{
|
||||||
|
"user": holo_user.id,
|
||||||
|
"type": "application",
|
||||||
|
"complete": True,
|
||||||
|
"sent": False,
|
||||||
|
"state": "fill",
|
||||||
|
"reapply": True,
|
||||||
|
"stage": 10,
|
||||||
|
"application": col_applications.find_one({"user": holo_user.id})[
|
||||||
|
"application"
|
||||||
|
],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
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
|
# Start a new application when user reapplies after leaving the chat
|
||||||
@app.on_callback_query(filters.regex("reapply_new_[\s\S]*"))
|
@app.on_callback_query(filters.regex("reapply_new_[\s\S]*"))
|
||||||
async def callback_query_reapply_new(app, clb):
|
async def callback_query_reapply_new(app: Client, clb: CallbackQuery):
|
||||||
|
|
||||||
fullclb = clb.data.split("_")
|
fullclb = clb.data.split("_")
|
||||||
|
|
||||||
jsonSave(jsonLoad(f"{configGet('data', 'locations')}{sep}user_default.json"), f"{configGet('data', 'locations')}{sep}users{sep}{clb.from_user.id}.json")
|
holo_user = HoloUser(clb.from_user)
|
||||||
configSet(["telegram_id"], str(clb.from_user.username), file=str(clb.from_user.id))
|
|
||||||
configSet(["telegram_name"], f"{clb.from_user.first_name} {clb.from_user.last_name}", file=str(clb.from_user.id))
|
if holo_user.sponsorship_state()[0] == "fill":
|
||||||
configSet(["telegram_phone"], str(clb.from_user.phone_number), file=str(clb.from_user.id))
|
await clb.message.reply_text(
|
||||||
configSet(["telegram_locale"], str(clb.from_user.language_code), file=str(clb.from_user.id))
|
locale("finish_sponsorship", "message"), quote=False
|
||||||
await clb.answer(locale("reapply_stopped", "callback"))
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
await clb.answer(locale("reapply_stopped", "callback", locale=clb.from_user))
|
||||||
message = await app.get_messages(clb.from_user.id, int(fullclb[2]))
|
message = await app.get_messages(clb.from_user.id, int(fullclb[2]))
|
||||||
|
col_tmp.update_one(
|
||||||
|
{"user": clb.from_user.id, "type": "application"},
|
||||||
|
{"$set": {"state": "fill", "completed": False, "stage": 1}},
|
||||||
|
)
|
||||||
|
holo_user.application_restart(reapply=True)
|
||||||
await welcome_pass(app, message, once_again=True)
|
await welcome_pass(app, message, once_again=True)
|
||||||
logWrite(f"User {clb.from_user.id} restarted the application after leaving the chat earlier")
|
logWrite(
|
||||||
await clb.message.edit(clb.message.text, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("done", "button"), "nothing")]]))
|
f"User {clb.from_user.id} restarted the application after leaving the chat earlier"
|
||||||
|
)
|
||||||
|
await clb.message.edit(
|
||||||
|
clb.message.text,
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
|
[
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale("done", "button", locale=clb.from_user), "nothing"
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# Abort application fill in progress and restart it
|
# Abort application fill in progress and restart it
|
||||||
@app.on_callback_query(filters.regex("reapply_stop_[\s\S]*"))
|
@app.on_callback_query(filters.regex("reapply_stop_[\s\S]*"))
|
||||||
async def callback_query_reapply_stop(app, clb):
|
async def callback_query_reapply_stop(app: Client, clb: CallbackQuery):
|
||||||
|
|
||||||
fullclb = clb.data.split("_")
|
fullclb = clb.data.split("_")
|
||||||
|
holo_user = HoloUser(clb.from_user)
|
||||||
|
|
||||||
jsonSave(jsonLoad(f"{configGet('data', 'locations')}{sep}user_default.json"), f"{configGet('data', 'locations')}{sep}users{sep}{clb.from_user.id}.json")
|
holo_user.application_restart()
|
||||||
configSet(["telegram_id"], str(clb.from_user.username), file=str(clb.from_user.id))
|
await clb.answer(locale("reapply_stopped", "callback", locale=holo_user))
|
||||||
configSet(["telegram_name"], f"{clb.from_user.first_name} {clb.from_user.last_name}", file=str(clb.from_user.id))
|
|
||||||
configSet(["telegram_phone"], str(clb.from_user.phone_number), file=str(clb.from_user.id))
|
|
||||||
configSet(["telegram_locale"], str(clb.from_user.language_code), file=str(clb.from_user.id))
|
|
||||||
await clb.answer(locale("reapply_stopped", "callback"))
|
|
||||||
message = await app.get_messages(clb.from_user.id, int(fullclb[2]))
|
message = await app.get_messages(clb.from_user.id, int(fullclb[2]))
|
||||||
await welcome_pass(app, message, once_again=True)
|
await welcome_pass(app, message, once_again=True)
|
||||||
logWrite(f"User {clb.from_user.id} restarted the application due to typo in it")
|
logWrite(f"User {clb.from_user.id} restarted the application due to typo in it")
|
||||||
await clb.message.edit(locale("reapply_restarted", "message"), reply_markup=ReplyKeyboardRemove())
|
await clb.message.edit(
|
||||||
# ==============================================================================================================================
|
locale("reapply_restarted", "message", locale=holo_user),
|
||||||
|
reply_markup=ReplyKeyboardRemove(),
|
||||||
|
)
|
||||||
|
@@ -1,14 +1,14 @@
|
|||||||
from app import app
|
from app import app
|
||||||
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
|
||||||
|
from pyrogram.client import Client
|
||||||
from pyrogram.errors import bad_request_400
|
from pyrogram.errors import bad_request_400
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from modules.utils import locale, logWrite
|
from modules.utils import locale, logWrite
|
||||||
from modules.commands.rules import default_rules_markup
|
from modules.commands.rules import DefaultRulesMarkup
|
||||||
|
|
||||||
|
|
||||||
# Callback rule ================================================================================================================
|
|
||||||
@app.on_callback_query(filters.regex("rule_[\s\S]*"))
|
@app.on_callback_query(filters.regex("rule_[\s\S]*"))
|
||||||
async def callback_query_rule(app, clb):
|
async def callback_query_rule(app: Client, clb: CallbackQuery):
|
||||||
|
|
||||||
fullclb = clb.data.split("_")
|
fullclb = clb.data.split("_")
|
||||||
|
|
||||||
logWrite(f"User {clb.from_user.id} requested to check out rule {fullclb[1]}")
|
logWrite(f"User {clb.from_user.id} requested to check out rule {fullclb[1]}")
|
||||||
@@ -17,55 +17,85 @@ async def callback_query_rule(app, clb):
|
|||||||
|
|
||||||
if rule_num == len(locale("rules")):
|
if rule_num == len(locale("rules")):
|
||||||
lower_buttons = [
|
lower_buttons = [
|
||||||
InlineKeyboardButton(locale("rules_prev", "button"), callback_data=f"rule_{rule_num-1}")
|
InlineKeyboardButton(
|
||||||
|
locale("rules_prev", "button", locale=clb.from_user),
|
||||||
|
callback_data=f"rule_{rule_num-1}",
|
||||||
|
)
|
||||||
]
|
]
|
||||||
elif rule_num == 1:
|
elif rule_num == 1:
|
||||||
lower_buttons = [
|
lower_buttons = [
|
||||||
InlineKeyboardButton(locale("rules_next", "button"), callback_data=f"rule_{rule_num+1}")
|
InlineKeyboardButton(
|
||||||
|
locale("rules_next", "button", locale=clb.from_user),
|
||||||
|
callback_data=f"rule_{rule_num+1}",
|
||||||
|
)
|
||||||
]
|
]
|
||||||
else:
|
else:
|
||||||
lower_buttons = [
|
lower_buttons = [
|
||||||
InlineKeyboardButton(locale("rules_prev", "button"), callback_data=f"rule_{rule_num-1}"),
|
InlineKeyboardButton(
|
||||||
InlineKeyboardButton(locale("rules_next", "button"), callback_data=f"rule_{rule_num+1}")
|
locale("rules_prev", "button", locale=clb.from_user),
|
||||||
|
callback_data=f"rule_{rule_num-1}",
|
||||||
|
),
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale("rules_next", "button", locale=clb.from_user),
|
||||||
|
callback_data=f"rule_{rule_num+1}",
|
||||||
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await clb.message.edit(text=locale("rules")[rule_num-1], disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup(
|
await clb.message.edit(
|
||||||
|
text=locale("rules", locale=clb.from_user)[rule_num - 1],
|
||||||
|
disable_web_page_preview=True,
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
[
|
[
|
||||||
[
|
[
|
||||||
InlineKeyboardButton(locale("rules_home", "button"), callback_data="rules_home"),
|
InlineKeyboardButton(
|
||||||
InlineKeyboardButton(locale("rules_additional", "button"), callback_data="rules_additional")
|
locale("rules_home", "button", locale=clb.from_user),
|
||||||
|
callback_data="rules_home",
|
||||||
|
),
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale("rules_additional", "button", locale=clb.from_user),
|
||||||
|
callback_data="rules_additional",
|
||||||
|
),
|
||||||
],
|
],
|
||||||
lower_buttons
|
lower_buttons,
|
||||||
]
|
]
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
except bad_request_400.MessageNotModified:
|
except bad_request_400.MessageNotModified:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
await clb.answer(text=locale("rules_page", "callback").format(fullclb[1]))
|
await clb.answer(
|
||||||
|
text=locale("rules_page", "callback", locale=clb.from_user).format(fullclb[1])
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.on_callback_query(filters.regex("rules_home"))
|
@app.on_callback_query(filters.regex("rules_home"))
|
||||||
async def callback_query_rules_home(app, clb):
|
async def callback_query_rules_home(app: Client, clb: CallbackQuery):
|
||||||
|
|
||||||
logWrite(f"User {clb.from_user.id} requested to check out homepage rules")
|
logWrite(f"User {clb.from_user.id} requested to check out homepage rules")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await clb.message.edit(text=locale("rules_msg"), disable_web_page_preview=True, reply_markup=default_rules_markup)
|
await clb.message.edit(
|
||||||
|
text=locale("rules_msg", locale=clb.from_user),
|
||||||
|
disable_web_page_preview=True,
|
||||||
|
reply_markup=DefaultRulesMarkup(clb.from_user).keyboard,
|
||||||
|
)
|
||||||
except bad_request_400.MessageNotModified:
|
except bad_request_400.MessageNotModified:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
await clb.answer(text=locale("rules_home", "callback"))
|
await clb.answer(text=locale("rules_home", "callback", locale=clb.from_user))
|
||||||
|
|
||||||
|
|
||||||
@app.on_callback_query(filters.regex("rules_additional"))
|
@app.on_callback_query(filters.regex("rules_additional"))
|
||||||
async def callback_query_rules_additional(app, clb):
|
async def callback_query_rules_additional(app: Client, clb: CallbackQuery):
|
||||||
|
|
||||||
logWrite(f"User {clb.from_user.id} requested to check out additional rules")
|
logWrite(f"User {clb.from_user.id} requested to check out additional rules")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await clb.message.edit(text=locale("rules_additional"), disable_web_page_preview=True, reply_markup=default_rules_markup)
|
await clb.message.edit(
|
||||||
|
text=locale("rules_additional", locale=clb.from_user),
|
||||||
|
disable_web_page_preview=True,
|
||||||
|
reply_markup=DefaultRulesMarkup(clb.from_user).keyboard,
|
||||||
|
)
|
||||||
except bad_request_400.MessageNotModified:
|
except bad_request_400.MessageNotModified:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
await clb.answer(text=locale("rules_additional", "callback"))
|
await clb.answer(text=locale("rules_additional", "callback", locale=clb.from_user))
|
||||||
# ==============================================================================================================================
|
|
||||||
|
71
modules/callbacks/spoiler.py
Normal file
71
modules/callbacks/spoiler.py
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
from os import path
|
||||||
|
from app import app
|
||||||
|
from pyrogram.types import CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from pyrogram import filters
|
||||||
|
from modules.database import col_spoilers
|
||||||
|
from bson.objectid import ObjectId
|
||||||
|
|
||||||
|
from modules.utils import configGet, jsonLoad, locale
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_callback_query(filters.regex("sid_[\s\S]*"))
|
||||||
|
async def callback_query_sid(app: Client, clb: CallbackQuery):
|
||||||
|
await clb.answer(
|
||||||
|
url=f'https://t.me/{(await app.get_me()).username}?start={clb.data.split("_")[1]}'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_callback_query(filters.regex("shc_[\s\S]*"))
|
||||||
|
async def callback_query_shc(app: Client, clb: CallbackQuery):
|
||||||
|
if clb.from_user.id not in jsonLoad(
|
||||||
|
path.join(configGet("cache", "locations"), "group_members")
|
||||||
|
):
|
||||||
|
await clb.answer(
|
||||||
|
locale("spoiler_forbidden", "callback", locale=clb.from_user),
|
||||||
|
show_alert=True,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
spoil = col_spoilers.find_one({"_id": ObjectId(clb.data.split("_")[1])})
|
||||||
|
|
||||||
|
desc = locale(
|
||||||
|
"spoiler_described_named", "message", locale=clb.from_user
|
||||||
|
).format(
|
||||||
|
locale(spoil["category"], "message", "spoiler_categories"),
|
||||||
|
clb.from_user.first_name,
|
||||||
|
spoil["description"],
|
||||||
|
)
|
||||||
|
|
||||||
|
await app.send_message(
|
||||||
|
configGet("users", "groups"),
|
||||||
|
desc,
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
|
[
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale("spoiler_view", "button", locale=clb.from_user),
|
||||||
|
callback_data=f'sid_{clb.data.split("_")[1]}',
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
await app.send_message(
|
||||||
|
configGet("admin", "groups"),
|
||||||
|
desc,
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
|
[
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale("spoiler_view", "button", locale=clb.from_user),
|
||||||
|
callback_data=f'sid_{clb.data.split("_")[1]}',
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
await clb.answer(
|
||||||
|
locale("spoiler_sent", "callback", locale=clb.from_user), show_alert=True
|
||||||
|
)
|
175
modules/callbacks/sponsorship.py
Normal file
175
modules/callbacks/sponsorship.py
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from app import app
|
||||||
|
from pyrogram.types import (
|
||||||
|
InlineKeyboardMarkup,
|
||||||
|
InlineKeyboardButton,
|
||||||
|
ForceReply,
|
||||||
|
CallbackQuery,
|
||||||
|
)
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from pyrogram import filters
|
||||||
|
from classes.errors.holo_user import LabelSettingError
|
||||||
|
from classes.holo_user import HoloUser
|
||||||
|
from modules.utils import configGet, locale, logWrite, should_quote
|
||||||
|
from modules.database import col_tmp, col_sponsorships
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_callback_query(filters.regex("sponsor_apply_[\s\S]*"))
|
||||||
|
async def callback_query_sponsor_apply(app: Client, clb: CallbackQuery):
|
||||||
|
fullclb = clb.data.split("_")
|
||||||
|
holo_user = HoloUser(int(fullclb[2]))
|
||||||
|
|
||||||
|
if holo_user.application_state()[0] == "fill":
|
||||||
|
await clb.message.reply_text(
|
||||||
|
locale("finish_application", "message"), quote=should_quote(clb.message)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
logWrite(f"User {holo_user.id} applied for sponsorship")
|
||||||
|
|
||||||
|
holo_user.sponsorship_restart()
|
||||||
|
|
||||||
|
edited_markup = [
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("sponsor_started", "button")), callback_data="nothing"
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
await clb.message.edit(
|
||||||
|
text=locale("sponsorship_applying", "message", locale=holo_user),
|
||||||
|
reply_markup=InlineKeyboardMarkup(edited_markup),
|
||||||
|
)
|
||||||
|
await app.send_message(
|
||||||
|
holo_user.id,
|
||||||
|
locale(f"sponsor1", "message", locale=holo_user),
|
||||||
|
reply_markup=ForceReply(
|
||||||
|
placeholder=str(locale(f"sponsor1", "force_reply", locale=holo_user.locale))
|
||||||
|
),
|
||||||
|
)
|
||||||
|
await clb.answer(
|
||||||
|
text=locale("sponsor_started", "callback", locale=holo_user).format(
|
||||||
|
holo_user.id
|
||||||
|
),
|
||||||
|
show_alert=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_callback_query(filters.regex("sponsor_yes_[\s\S]*"))
|
||||||
|
async def callback_query_sponsor_yes(app: Client, clb: CallbackQuery):
|
||||||
|
fullclb = clb.data.split("_")
|
||||||
|
holo_user = HoloUser(int(fullclb[2]))
|
||||||
|
|
||||||
|
await app.send_message(
|
||||||
|
configGet("admin", "groups"),
|
||||||
|
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 sponsorship approved by {clb.from_user.id}")
|
||||||
|
|
||||||
|
if col_sponsorships.find_one({"user": holo_user.id}) is not None:
|
||||||
|
col_sponsorships.update_one(
|
||||||
|
{"user": holo_user.id},
|
||||||
|
{
|
||||||
|
"$set": {
|
||||||
|
"date": datetime.now(),
|
||||||
|
"admin": clb.from_user.id,
|
||||||
|
"sponsorship": col_tmp.find_one(
|
||||||
|
{"user": holo_user.id, "type": "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": holo_user.id, "type": "sponsorship"}
|
||||||
|
)["sponsorship"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
col_tmp.update_one(
|
||||||
|
{"user": holo_user.id, "type": "sponsorship"},
|
||||||
|
{"$set": {"state": "approved", "sent": False}},
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
await holo_user.label_set(
|
||||||
|
configGet("users", "groups"),
|
||||||
|
col_tmp.find_one(
|
||||||
|
{"user": {"$eq": holo_user.id}, "type": {"$eq": "sponsorship"}}
|
||||||
|
)["sponsorship"]["label"],
|
||||||
|
)
|
||||||
|
except LabelSettingError as exp:
|
||||||
|
await app.send_message(
|
||||||
|
configGet("admin", "groups"), exp.__str__(), disable_notification=True
|
||||||
|
)
|
||||||
|
|
||||||
|
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=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: Client, clb: CallbackQuery):
|
||||||
|
fullclb = clb.data.split("_")
|
||||||
|
holo_user = HoloUser(int(fullclb[2]))
|
||||||
|
|
||||||
|
await app.send_message(
|
||||||
|
configGet("admin", "groups"),
|
||||||
|
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 sponsorship rejected by {clb.from_user.id}")
|
||||||
|
|
||||||
|
col_tmp.update_one(
|
||||||
|
{"user": holo_user.id, "type": "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=locale("sponsor_rejected", "callback").format(fullclb[2]), show_alert=False
|
||||||
|
)
|
@@ -1,126 +1,189 @@
|
|||||||
from os import sep
|
from datetime import datetime
|
||||||
from time import time
|
|
||||||
from app import app
|
from app import app
|
||||||
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from modules.utils import configGet, configSet, jsonLoad, jsonSave, locale, logWrite
|
from pyrogram.client import Client
|
||||||
|
from classes.holo_user import HoloUser
|
||||||
|
from modules.utils import configGet, locale, logWrite
|
||||||
|
from modules.database import col_tmp, col_applications
|
||||||
|
from modules.commands.rules import DefaultRulesMarkup
|
||||||
|
|
||||||
|
|
||||||
# Callbacks application ========================================================================================================
|
|
||||||
@app.on_callback_query(filters.regex("sub_yes_[\s\S]*"))
|
@app.on_callback_query(filters.regex("sub_yes_[\s\S]*"))
|
||||||
async def callback_query_accept(app, clb):
|
async def callback_query_accept(app: Client, clb: CallbackQuery):
|
||||||
|
|
||||||
fullclb = clb.data.split("_")
|
fullclb = clb.data.split("_")
|
||||||
|
holo_user = HoloUser(int(fullclb[2]))
|
||||||
|
|
||||||
await app.send_message(configGet("admin_group"), locale("approved_by", "message").format(clb.from_user.first_name, fullclb[2]), disable_notification=True)
|
await app.send_message(
|
||||||
logWrite(f"User {fullclb[2]} got approved by {clb.from_user.id}")
|
configGet("admin", "groups"),
|
||||||
|
locale("approved_by", "message").format(clb.from_user.first_name, holo_user.id),
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
logWrite(f"User {holo_user.id} got approved by {clb.from_user.id}")
|
||||||
|
|
||||||
need_link = True
|
need_link = True
|
||||||
|
|
||||||
async for member in app.get_chat_members(configGet("destination_group")):
|
async for member in app.get_chat_members(configGet("users", "groups")):
|
||||||
if member.user.id == int(fullclb[2]):
|
if member.user.id == holo_user.id:
|
||||||
need_link = False
|
need_link = False
|
||||||
|
|
||||||
if need_link:
|
if need_link:
|
||||||
link = await app.create_chat_invite_link(configGet("destination_group"), name=f"Invite for {fullclb[2]}", member_limit=1) #, expire_date=datetime.now()+timedelta(days=1))
|
link = await app.create_chat_invite_link(
|
||||||
|
configGet("users", "groups"),
|
||||||
|
name=f"Invite for {holo_user.id}",
|
||||||
|
member_limit=1,
|
||||||
|
) # , expire_date=datetime.now()+timedelta(days=1))
|
||||||
|
|
||||||
await app.send_message(int(fullclb[2]), locale("read_rules", "message"))
|
await app.send_message(
|
||||||
|
holo_user.id, locale("read_rules", "message", locale=holo_user)
|
||||||
|
)
|
||||||
|
|
||||||
for rule_msg in locale("rules"):
|
await app.send_message(
|
||||||
await app.send_message(int(fullclb[2]), rule_msg)
|
holo_user.id,
|
||||||
|
locale("rules_msg", locale=holo_user),
|
||||||
|
disable_web_page_preview=True,
|
||||||
|
reply_markup=DefaultRulesMarkup(holo_user).keyboard,
|
||||||
|
)
|
||||||
|
|
||||||
await app.send_message(int(fullclb[2]), locale("approved", "message"), reply_markup=InlineKeyboardMarkup(
|
await app.send_message(
|
||||||
[[
|
holo_user.id,
|
||||||
InlineKeyboardButton(str(locale("join", "button")), url=link.invite_link)
|
locale("approved", "message", locale=holo_user),
|
||||||
]]
|
reply_markup=InlineKeyboardMarkup(
|
||||||
))
|
[
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
str(locale("join", "button", locale=holo_user)),
|
||||||
|
url=link.invite_link,
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
configSet(["link"], link.invite_link, file=fullclb[2])
|
holo_user.set("link", link.invite_link)
|
||||||
logWrite(f"User {fullclb[2]} got an invite link {link.invite_link}")
|
logWrite(f"User {holo_user.id} got an invite link {link.invite_link}")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
await app.send_message(int(fullclb[2]), locale("approved_joined", "message"))
|
await app.send_message(
|
||||||
|
holo_user.id, locale("approved_joined", "message", locale=holo_user)
|
||||||
|
)
|
||||||
|
|
||||||
configSet(["approved"], True, file=fullclb[2])
|
col_applications.insert_one(
|
||||||
configSet(["sent"], False, file=fullclb[2])
|
{
|
||||||
|
"user": holo_user.id,
|
||||||
|
"date": datetime.now(),
|
||||||
|
"admin": clb.from_user.id,
|
||||||
|
"application": col_tmp.find_one(
|
||||||
|
{"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}
|
||||||
|
)["application"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
col_tmp.update_one(
|
||||||
|
{"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}},
|
||||||
|
{"$set": {"state": "approved", "sent": False}},
|
||||||
|
)
|
||||||
|
|
||||||
application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")
|
edited_markup = [
|
||||||
application[fullclb[2]]["approved"] = True
|
[
|
||||||
application[fullclb[2]]["approved_by"] = clb.from_user.id
|
InlineKeyboardButton(
|
||||||
application[fullclb[2]]["approval_date"] = int(time())
|
text=str(locale("accepted", "button")), callback_data="nothing"
|
||||||
jsonSave(application, f"{configGet('data', 'locations')}{sep}applications.json")
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
edited_markup = [[InlineKeyboardButton(text=str(locale("accepted", "button")), callback_data="nothing")]]
|
await clb.message.edit(
|
||||||
|
text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)
|
||||||
|
)
|
||||||
|
await clb.answer(
|
||||||
|
text=locale("sub_accepted", "callback", locale=clb.from_user).format(
|
||||||
|
holo_user.id
|
||||||
|
),
|
||||||
|
show_alert=True,
|
||||||
|
)
|
||||||
|
|
||||||
await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup))
|
|
||||||
await clb.answer(text=locale("sub_accepted", "callback").format(fullclb[2]), show_alert=True)
|
|
||||||
|
|
||||||
@app.on_callback_query(filters.regex("sub_no_aggressive_[\s\S]*"))
|
|
||||||
async def callback_query_refuse_aggressive(app, clb):
|
|
||||||
|
|
||||||
fullclb = clb.data.split("_")
|
|
||||||
|
|
||||||
await app.send_message(configGet("admin_group"), locale("refused_by_agr", "message").format(clb.from_user.first_name, fullclb[3]), disable_notification=True)
|
|
||||||
await app.send_message(int(fullclb[3]), locale("refused", "message"))
|
|
||||||
logWrite(f"User {fullclb[3]} got refused by {clb.from_user.id} due to being aggressive")
|
|
||||||
|
|
||||||
configSet(["refused"], True, file=fullclb[3])
|
|
||||||
configSet(["sent"], False, file=fullclb[3])
|
|
||||||
|
|
||||||
application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")
|
|
||||||
application[fullclb[3]]["refused"] = True
|
|
||||||
application[fullclb[3]]["refused_by"] = clb.from_user.id
|
|
||||||
application[fullclb[3]]["refusal_date"] = int(time())
|
|
||||||
jsonSave(application, f"{configGet('data', 'locations')}{sep}applications.json")
|
|
||||||
|
|
||||||
edited_markup = [[InlineKeyboardButton(text=str(locale("declined", "button")), callback_data="nothing")]]
|
|
||||||
|
|
||||||
await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup))
|
|
||||||
await clb.answer(text=locale("sub_no_aggressive", "callback").format(fullclb[3]), show_alert=True)
|
|
||||||
|
|
||||||
@app.on_callback_query(filters.regex("sub_no_russian_[\s\S]*"))
|
|
||||||
async def callback_query_refuse_russian(app, clb):
|
|
||||||
|
|
||||||
fullclb = clb.data.split("_")
|
|
||||||
|
|
||||||
await app.send_message(configGet("admin_group"), locale("refused_by_rus", "message").format(clb.from_user.first_name, fullclb[3]), disable_notification=True)
|
|
||||||
await app.send_message(int(fullclb[3]), locale("refused", "message"))
|
|
||||||
await app.send_message(int(fullclb[3]), locale("refused_russian", "message"))
|
|
||||||
logWrite(f"User {fullclb[3]} got refused by {clb.from_user.id} due to being russian")
|
|
||||||
|
|
||||||
configSet(["refused"], True, file=fullclb[3])
|
|
||||||
configSet(["sent"], False, file=fullclb[3])
|
|
||||||
|
|
||||||
application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")
|
|
||||||
application[fullclb[3]]["refused"] = True
|
|
||||||
application[fullclb[3]]["refused_by"] = clb.from_user.id
|
|
||||||
application[fullclb[3]]["refusal_date"] = int(time())
|
|
||||||
jsonSave(application, f"{configGet('data', 'locations')}{sep}applications.json")
|
|
||||||
|
|
||||||
edited_markup = [[InlineKeyboardButton(text=str(locale("declined", "button")), callback_data="nothing")]]
|
|
||||||
|
|
||||||
await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup))
|
|
||||||
await clb.answer(text=locale("sub_no_russian", "callback").format(fullclb[3]), show_alert=True)
|
|
||||||
|
|
||||||
@app.on_callback_query(filters.regex("sub_no_[\s\S]*"))
|
@app.on_callback_query(filters.regex("sub_no_[\s\S]*"))
|
||||||
async def callback_query_refuse(app, clb):
|
async def callback_query_reject(app: Client, clb: CallbackQuery):
|
||||||
|
|
||||||
fullclb = clb.data.split("_")
|
fullclb = clb.data.split("_")
|
||||||
|
holo_user = HoloUser(int(fullclb[2]))
|
||||||
|
|
||||||
await app.send_message(configGet("admin_group"), locale("refused_by", "message").format(clb.from_user.first_name, fullclb[2]), disable_notification=True)
|
await app.send_message(
|
||||||
await app.send_message(int(fullclb[2]), locale("refused", "message"))
|
configGet("admin", "groups"),
|
||||||
logWrite(f"User {fullclb[2]} got refused by {clb.from_user.id}")
|
locale("rejected_by", "message").format(clb.from_user.first_name, holo_user.id),
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
await app.send_message(
|
||||||
|
holo_user.id, locale("rejected", "message", locale=holo_user)
|
||||||
|
)
|
||||||
|
logWrite(f"User {holo_user.id} got rejected by {clb.from_user.id}")
|
||||||
|
|
||||||
configSet(["refused"], True, file=fullclb[2])
|
col_tmp.update_one(
|
||||||
configSet(["sent"], False, file=fullclb[2])
|
{"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}},
|
||||||
|
{"$set": {"state": "rejected", "sent": False}},
|
||||||
|
)
|
||||||
|
|
||||||
application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")
|
edited_markup = [
|
||||||
application[fullclb[2]]["refused"] = True
|
[
|
||||||
application[fullclb[2]]["refused_by"] = clb.from_user.id
|
InlineKeyboardButton(
|
||||||
application[fullclb[2]]["refusal_date"] = int(time())
|
text=str(locale("declined", "button")), callback_data="nothing"
|
||||||
jsonSave(application, f"{configGet('data', 'locations')}{sep}applications.json")
|
)
|
||||||
|
],
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("ban", "button")), callback_data=f"ban_{fullclb[2]}"
|
||||||
|
)
|
||||||
|
],
|
||||||
|
]
|
||||||
|
|
||||||
edited_markup = [[InlineKeyboardButton(text=str(locale("declined", "button")), callback_data="nothing")]]
|
await clb.message.edit(
|
||||||
|
text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)
|
||||||
|
)
|
||||||
|
await clb.answer(
|
||||||
|
text=locale("sub_rejected", "callback", locale=clb.from_user).format(
|
||||||
|
holo_user.id
|
||||||
|
),
|
||||||
|
show_alert=True,
|
||||||
|
)
|
||||||
|
|
||||||
await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup))
|
|
||||||
await clb.answer(text=locale("sub_refused", "callback").format(fullclb[2]), show_alert=True)
|
@app.on_callback_query(filters.regex("sub_russian_[\s\S]*"))
|
||||||
# ==============================================================================================================================
|
async def callback_query_reject_russian(app: Client, clb: CallbackQuery):
|
||||||
|
fullclb = clb.data.split("_")
|
||||||
|
holo_user = HoloUser(int(fullclb[2]))
|
||||||
|
|
||||||
|
await app.send_message(
|
||||||
|
configGet("admin", "groups"),
|
||||||
|
locale("rejected_by_rus", "message").format(
|
||||||
|
clb.from_user.first_name, holo_user.id
|
||||||
|
),
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
await app.send_message(
|
||||||
|
holo_user.id, locale("rejected_russian", "message", locale=holo_user)
|
||||||
|
)
|
||||||
|
logWrite(
|
||||||
|
f"User {holo_user.id} got rejected by {clb.from_user.id} due to being russian"
|
||||||
|
)
|
||||||
|
|
||||||
|
col_tmp.update_one(
|
||||||
|
{"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}},
|
||||||
|
{"$set": {"state": "rejected", "sent": False}},
|
||||||
|
)
|
||||||
|
|
||||||
|
edited_markup = [
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("declined", "button")), callback_data="nothing"
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
await clb.message.edit(
|
||||||
|
text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)
|
||||||
|
)
|
||||||
|
await clb.answer(
|
||||||
|
text=locale("sub_russian", "callback", locale=clb.from_user).format(
|
||||||
|
holo_user.id
|
||||||
|
),
|
||||||
|
show_alert=True,
|
||||||
|
)
|
||||||
|
@@ -1,48 +1,100 @@
|
|||||||
from os import sep
|
|
||||||
from app import app
|
from app import app
|
||||||
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ChatPermissions
|
from pyrogram.types import (
|
||||||
|
InlineKeyboardMarkup,
|
||||||
|
InlineKeyboardButton,
|
||||||
|
ChatPermissions,
|
||||||
|
CallbackQuery,
|
||||||
|
)
|
||||||
|
from pyrogram.client import Client
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from modules.utils import configGet, configSet, jsonLoad, jsonSave, locale, logWrite
|
from classes.holo_user import HoloUser
|
||||||
|
from modules.utils import configGet, locale, logWrite
|
||||||
|
from modules.database import col_tmp
|
||||||
|
|
||||||
|
|
||||||
# Callbacks sus users ==========================================================================================================
|
|
||||||
@app.on_callback_query(filters.regex("sus_allow_[\s\S]*"))
|
@app.on_callback_query(filters.regex("sus_allow_[\s\S]*"))
|
||||||
async def callback_query_sus_allow(app, clb):
|
async def callback_query_sus_allow(app: Client, clb: CallbackQuery):
|
||||||
|
|
||||||
fullclb = clb.data.split("_")
|
fullclb = clb.data.split("_")
|
||||||
|
holo_user = HoloUser(int(fullclb[2]))
|
||||||
|
|
||||||
await app.send_message(configGet("admin_group"), locale("sus_allowed_by", "message").format(clb.from_user.first_name, fullclb[2]), disable_notification=True)
|
await app.send_message(
|
||||||
logWrite(f"User {fullclb[2]} was allowed to join with another link by {clb.from_user.id}")
|
configGet("admin", "groups"),
|
||||||
|
locale("sus_allowed_by", "message").format(
|
||||||
|
clb.from_user.first_name, holo_user.id
|
||||||
|
),
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
logWrite(
|
||||||
|
f"User {holo_user.id} was allowed to join with another link by {clb.from_user.id}"
|
||||||
|
)
|
||||||
|
|
||||||
edited_markup = [[InlineKeyboardButton(text=str(locale("sus_allowed", "button")), callback_data="nothing")]]
|
edited_markup = [
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("sus_allowed", "button")), callback_data="nothing"
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup))
|
await clb.message.edit(
|
||||||
await clb.answer(text=locale("sus_allowed", "callback").format(fullclb[2]), show_alert=True)
|
text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)
|
||||||
|
)
|
||||||
|
await clb.answer(
|
||||||
|
text=locale("sus_allowed", "callback", locale=clb.from_user).format(
|
||||||
|
holo_user.id
|
||||||
|
),
|
||||||
|
show_alert=True,
|
||||||
|
)
|
||||||
|
|
||||||
await app.restrict_chat_member(configGet("destination_group"), int(fullclb[2]), permissions=ChatPermissions(
|
await app.restrict_chat_member(
|
||||||
|
configGet("users", "groups"),
|
||||||
|
holo_user.id,
|
||||||
|
permissions=ChatPermissions(
|
||||||
can_send_messages=True,
|
can_send_messages=True,
|
||||||
can_send_media_messages=True,
|
can_send_media_messages=True,
|
||||||
can_send_other_messages=True,
|
can_send_other_messages=True,
|
||||||
can_send_polls=True
|
can_send_polls=True,
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@app.on_callback_query(filters.regex("sus_refuse_[\s\S]*"))
|
|
||||||
async def callback_query_sus_refuse(app, clb):
|
|
||||||
|
|
||||||
|
@app.on_callback_query(filters.regex("sus_reject_[\s\S]*"))
|
||||||
|
async def callback_query_sus_reject(app: Client, clb: CallbackQuery):
|
||||||
fullclb = clb.data.split("_")
|
fullclb = clb.data.split("_")
|
||||||
|
holo_user = HoloUser(int(fullclb[2]))
|
||||||
|
|
||||||
await app.send_message(configGet("admin_group"), locale("sus_refused_by", "message").format(clb.from_user.first_name, fullclb[2]), disable_notification=True)
|
await app.send_message(
|
||||||
logWrite(f"User {fullclb[2]} was refused to join with another link by {clb.from_user.id}")
|
configGet("admin", "groups"),
|
||||||
|
locale("sus_rejected_by", "message").format(
|
||||||
|
clb.from_user.first_name, holo_user.id
|
||||||
|
),
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
logWrite(
|
||||||
|
f"User {holo_user.id} was rejected to join with another link by {clb.from_user.id}"
|
||||||
|
)
|
||||||
|
|
||||||
edited_markup = [[InlineKeyboardButton(text=str(locale("sus_refused", "button")), callback_data="nothing")]]
|
edited_markup = [
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("sus_rejected", "button")), callback_data="nothing"
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup))
|
await clb.message.edit(
|
||||||
await clb.answer(text=locale("sus_refused", "callback").format(fullclb[2]), show_alert=True)
|
text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)
|
||||||
|
)
|
||||||
|
await clb.answer(
|
||||||
|
text=locale("sus_rejected", "callback", locale=clb.from_user).format(
|
||||||
|
holo_user.id
|
||||||
|
),
|
||||||
|
show_alert=True,
|
||||||
|
)
|
||||||
|
|
||||||
await app.ban_chat_member(configGet("destination_group"), int(fullclb[2]))
|
await app.ban_chat_member(configGet("users", "groups"), holo_user.id)
|
||||||
|
|
||||||
jsonSave(jsonLoad(f"{configGet('data', 'locations')}{sep}user_default.json"), f"{configGet('data', 'locations')}{sep}users{sep}{fullclb[2]}.json")
|
col_tmp.update_one(
|
||||||
configSet(["stage"], 10, file=fullclb[2])
|
{"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}},
|
||||||
configSet(["refused"], True, file=fullclb[2])
|
{"$set": {"state": "rejected", "sent": False}},
|
||||||
configSet(["refused_by"], clb.from_user.id, file=fullclb[2])
|
)
|
||||||
# ==============================================================================================================================
|
|
||||||
|
27
modules/callbacks/warnings.py
Normal file
27
modules/callbacks/warnings.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from app import app
|
||||||
|
from pyrogram import filters
|
||||||
|
from pyrogram.types import CallbackQuery
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from modules.utils import locale
|
||||||
|
from modules.database import col_warnings
|
||||||
|
from bson import ObjectId
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_callback_query(filters.regex("w_rev_[\s\S]*"))
|
||||||
|
async def callback_query_warning_revoke(app: Client, clb: CallbackQuery):
|
||||||
|
warning = col_warnings.find_one({"_id": ObjectId(str(clb.data).split("_")[2])})
|
||||||
|
if warning is None:
|
||||||
|
await clb.answer(
|
||||||
|
text=locale("warning_not_found", "callback", locale=clb.from_user),
|
||||||
|
show_alert=True,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
col_warnings.update_one(
|
||||||
|
{"_id": warning["_id"]},
|
||||||
|
{"$set": {"active": False, "revoke_date": datetime.now()}},
|
||||||
|
)
|
||||||
|
await clb.answer(
|
||||||
|
text=locale("warning_revoked", "callback", locale=clb.from_user).format(),
|
||||||
|
show_alert=True,
|
||||||
|
)
|
@@ -1,56 +1,99 @@
|
|||||||
from os import sep, path
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from app import app, isAnAdmin
|
from app import app
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from pyrogram.enums.chat_members_filter import ChatMembersFilter
|
from pyrogram.enums.parse_mode import ParseMode
|
||||||
from modules.utils import configGet, jsonLoad, logWrite, locale, should_quote
|
from pyrogram.types import Message
|
||||||
|
from pyrogram.errors import bad_request_400
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from classes.errors.holo_user import UserNotFoundError
|
||||||
|
from classes.holo_user import HoloUser
|
||||||
|
from modules.utils import logWrite, locale, should_quote
|
||||||
from dateutil.relativedelta import relativedelta
|
from dateutil.relativedelta import relativedelta
|
||||||
|
from modules.database import col_applications
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
# Applications command =========================================================================================================
|
|
||||||
@app.on_message(~ filters.scheduled & filters.command(["application"], prefixes=["/"]))
|
|
||||||
async def cmd_application(app, msg):
|
|
||||||
|
|
||||||
if (await isAnAdmin(msg.from_user.id)) or (msg.chat.id == configGet("admin_group")):
|
@app.on_message(
|
||||||
|
custom_filters.enabled_applications
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.command(["application"], prefixes=["/"])
|
||||||
|
& custom_filters.admin
|
||||||
|
)
|
||||||
|
async def cmd_application(app: Client, msg: Message):
|
||||||
try:
|
try:
|
||||||
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("destination_group"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]):
|
|
||||||
list_of_users.append(m)
|
|
||||||
user_id = list_of_users[0].user.id
|
|
||||||
try:
|
try:
|
||||||
user_data = jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{user_id}.json")
|
holo_user = HoloUser(int(msg.command[1]))
|
||||||
application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")[str(user_id)]
|
except (ValueError, UserNotFoundError):
|
||||||
|
try:
|
||||||
|
holo_user = HoloUser((await app.get_users(msg.command[1])).id)
|
||||||
|
except (
|
||||||
|
bad_request_400.UsernameInvalid,
|
||||||
|
bad_request_400.PeerIdInvalid,
|
||||||
|
bad_request_400.UsernameNotOccupied,
|
||||||
|
):
|
||||||
|
await msg.reply_text(
|
||||||
|
locale(
|
||||||
|
"no_user_application", "message", locale=msg.from_user
|
||||||
|
).format(msg.command[1]),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
application = col_applications.find_one({"user": holo_user.id})
|
||||||
|
|
||||||
|
if application is None:
|
||||||
|
logWrite(
|
||||||
|
f"User {msg.from_user.id} requested application of {holo_user.id} but user does not exists"
|
||||||
|
)
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("user_invalid", "message", locale=msg.from_user),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
application_content = []
|
application_content = []
|
||||||
i = 1
|
i = 1
|
||||||
for question in configGet("application", file=str(msg.from_user.id)):
|
|
||||||
|
for question in application["application"]:
|
||||||
if i == 2:
|
if i == 2:
|
||||||
age = relativedelta(datetime.now(), datetime.strptime(application['application']['2'], '%d.%m.%Y'))
|
age = relativedelta(datetime.now(), application["application"]["2"])
|
||||||
application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {application['application']['2']} ({age.years} р.)")
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)"
|
||||||
|
)
|
||||||
|
elif i == 3:
|
||||||
|
if application["application"]["3"]["countryCode"] == "UA":
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application']['3']['name']}"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {application['application'][question]}")
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application'][question]}"
|
||||||
|
)
|
||||||
|
|
||||||
i += 1
|
i += 1
|
||||||
if user_data["sent"]:
|
|
||||||
if user_data["approved"]:
|
application_status = locale(
|
||||||
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"))
|
"application_status_accepted", "message", locale=msg.from_user
|
||||||
elif application["refused"]:
|
).format(
|
||||||
application_status = locale("application_status_refused", "message").format((await app.get_users(application["refused_by"])).first_name, datetime.fromtimestamp(application["refusal_date"]).strftime("%d.%m.%Y, %H:%M"))
|
(await app.get_users(application["admin"])).first_name,
|
||||||
else:
|
application["date"].strftime("%d.%m.%Y, %H:%M"),
|
||||||
application_status = locale("application_status_on_hold", "message")
|
)
|
||||||
else:
|
|
||||||
if user_data["approved"]:
|
logWrite(f"User {msg.from_user.id} requested application of {holo_user.id}")
|
||||||
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"))
|
await msg.reply_text(
|
||||||
elif application["refused"]:
|
locale("contact", "message", locale=msg.from_user).format(
|
||||||
application_status = locale("application_status_refused", "message").format((await app.get_users(application["refused_by"])).first_name, datetime.fromtimestamp(application["refusal_date"]).strftime("%d.%m.%Y, %H:%M"))
|
holo_user.id, "\n".join(application_content), application_status
|
||||||
else:
|
),
|
||||||
application_status = locale("application_status_not_send", "message")
|
parse_mode=ParseMode.MARKDOWN,
|
||||||
logWrite(f"User {msg.from_user.id} requested application of {user_id}")
|
quote=should_quote(msg),
|
||||||
await msg.reply_text(locale("contact", "message").format(str(user_id), "\n".join(application_content), application_status), quote=should_quote(msg))
|
)
|
||||||
except FileNotFoundError:
|
|
||||||
logWrite(f"User {msg.from_user.id} requested application of {user_id} but user does not exists")
|
|
||||||
await msg.reply_text(locale("contact_invalid", "message"), quote=should_quote(msg))
|
|
||||||
|
|
||||||
except IndexError:
|
except IndexError:
|
||||||
await msg.reply_text(locale("application_invalid_syntax", "message"), quote=should_quote(msg))
|
await msg.reply_text(
|
||||||
# ==============================================================================================================================
|
locale("application_invalid_syntax", "message", locale=msg.from_user),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
@@ -1,23 +0,0 @@
|
|||||||
from os import sep, makedirs, remove
|
|
||||||
from uuid import uuid1
|
|
||||||
from app import app, isAnAdmin
|
|
||||||
from pyrogram import filters
|
|
||||||
from pyrogram.enums.chat_action import ChatAction
|
|
||||||
from modules.utils import configGet, should_quote, jsonSave
|
|
||||||
from modules.database import col_applications
|
|
||||||
|
|
||||||
# Applications command =========================================================================================================
|
|
||||||
@app.on_message(~ filters.scheduled & filters.command(["applications"], prefixes=["/"]))
|
|
||||||
async def cmd_applications(app, msg):
|
|
||||||
|
|
||||||
if (await isAnAdmin(msg.from_user.id)) or (msg.chat.id == configGet("admin_group")):
|
|
||||||
await app.send_chat_action(msg.chat.id, ChatAction.UPLOAD_DOCUMENT)
|
|
||||||
filename = uuid1()
|
|
||||||
output = []
|
|
||||||
for entry in col_applications.find():
|
|
||||||
output.append(entry)
|
|
||||||
makedirs("tmp", exist_ok=True)
|
|
||||||
jsonSave(output, f"tmp{sep}{filename}.json")
|
|
||||||
await msg.reply_document(document=f"tmp{sep}{filename}.json", file_name="applications", quote=should_quote(msg))
|
|
||||||
remove(f"tmp{sep}{filename}.json")
|
|
||||||
# ==============================================================================================================================
|
|
35
modules/commands/cancel.py
Normal file
35
modules/commands/cancel.py
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
from app import app
|
||||||
|
from pyrogram import filters
|
||||||
|
from pyrogram.types import Message, ReplyKeyboardRemove
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from modules.utils import should_quote, logWrite, locale
|
||||||
|
from modules.database import col_tmp, col_spoilers, col_applications
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
(custom_filters.enabled_applications | custom_filters.enabled_sponsorships)
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.command("cancel", prefixes=["/"])
|
||||||
|
& ~custom_filters.banned
|
||||||
|
)
|
||||||
|
async def command_cancel(app: Client, msg: Message):
|
||||||
|
col_tmp.delete_many({"user": msg.from_user.id, "sent": False})
|
||||||
|
col_spoilers.delete_many({"user": msg.from_user.id, "completed": False})
|
||||||
|
try:
|
||||||
|
await app.listen.Cancel(filters.user(msg.from_user.id))
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
if col_applications.find_one({"user": msg.from_user.id}) is None:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("cancel_reapply", "message", locale=msg.from_user),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
reply_markup=ReplyKeyboardRemove(),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("cancel", "message", locale=msg.from_user),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
reply_markup=ReplyKeyboardRemove(),
|
||||||
|
)
|
||||||
|
logWrite(f"Cancelling all ongoing tmp operations for {msg.from_user.id}")
|
182
modules/commands/export.py
Normal file
182
modules/commands/export.py
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
from csv import QUOTE_ALL
|
||||||
|
from os import makedirs, path, remove
|
||||||
|
from uuid import uuid1
|
||||||
|
|
||||||
|
import aiofiles
|
||||||
|
from aiocsv.writers import AsyncDictWriter
|
||||||
|
from pyrogram import filters
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from pyrogram.enums.chat_action import ChatAction
|
||||||
|
from pyrogram.types import Message
|
||||||
|
from ujson import dumps
|
||||||
|
|
||||||
|
from app import app
|
||||||
|
from modules import custom_filters
|
||||||
|
from modules.database import col_applications, col_sponsorships, col_warnings
|
||||||
|
from modules.logging import logWrite
|
||||||
|
from modules.utils import locale, should_quote
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
custom_filters.enabled_general
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.command(["export"], prefixes=["/"])
|
||||||
|
& custom_filters.admin
|
||||||
|
)
|
||||||
|
async def cmd_export(app: Client, msg: Message):
|
||||||
|
if len(msg.command) <= 1:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("syntax_export", "message", locale=msg.from_user),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
selection = msg.command[1].lower()
|
||||||
|
|
||||||
|
if selection not in ["applications", "warnings", "sponsorships", "bans"]:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("syntax_export", "message", locale=msg.from_user),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
logWrite(f"Admin {msg.from_user.id} requested export of {selection}")
|
||||||
|
|
||||||
|
makedirs("tmp", exist_ok=True)
|
||||||
|
temp_file = path.join("tmp", str(uuid1()))
|
||||||
|
|
||||||
|
await app.send_chat_action(msg.chat.id, ChatAction.TYPING)
|
||||||
|
|
||||||
|
output_csv = []
|
||||||
|
output_json = []
|
||||||
|
|
||||||
|
if selection == "applications":
|
||||||
|
header_csv = [
|
||||||
|
"user",
|
||||||
|
"date",
|
||||||
|
"admin",
|
||||||
|
"question_1",
|
||||||
|
"question_2",
|
||||||
|
"question_3",
|
||||||
|
"question_4",
|
||||||
|
"question_5",
|
||||||
|
"question_6",
|
||||||
|
"question_7",
|
||||||
|
"question_8",
|
||||||
|
"question_9",
|
||||||
|
"question_10",
|
||||||
|
]
|
||||||
|
|
||||||
|
for entry in list(col_applications.find()):
|
||||||
|
del entry["_id"]
|
||||||
|
entry["date"] = entry["date"].isoformat()
|
||||||
|
entry["application"]["2"] = entry["application"]["2"].isoformat()
|
||||||
|
output_json.append(entry)
|
||||||
|
|
||||||
|
for entry in list(col_applications.find()):
|
||||||
|
del entry["_id"]
|
||||||
|
entry["date"] = entry["date"].isoformat()
|
||||||
|
entry["application"]["2"] = entry["application"]["2"].isoformat()
|
||||||
|
for index, value in enumerate(entry["application"]):
|
||||||
|
entry[f"question_{index+1}"] = entry["application"][value]
|
||||||
|
entry[
|
||||||
|
"question_3"
|
||||||
|
] = f"{entry['application']['3']['name']} ({entry['application']['3']['adminName1']}, {entry['application']['3']['countryName']})"
|
||||||
|
del entry["application"]
|
||||||
|
output_csv.append(entry)
|
||||||
|
|
||||||
|
elif selection == "warnings":
|
||||||
|
header_csv = [
|
||||||
|
"id",
|
||||||
|
"user",
|
||||||
|
"admin",
|
||||||
|
"date",
|
||||||
|
"reason",
|
||||||
|
"active",
|
||||||
|
"revoke_date",
|
||||||
|
]
|
||||||
|
|
||||||
|
for entry in list(col_warnings.find()):
|
||||||
|
for k, v in list(entry.items()):
|
||||||
|
entry[{"_id": "id"}.get(k, k)] = entry.pop(k)
|
||||||
|
entry["id"] = str(entry["id"])
|
||||||
|
entry["date"] = entry["date"].isoformat()
|
||||||
|
if entry["revoke_date"] is not None:
|
||||||
|
entry["revoke_date"] = entry["revoke_date"].isoformat()
|
||||||
|
output_json.append(entry)
|
||||||
|
output_csv.append(entry)
|
||||||
|
|
||||||
|
elif selection == "sponsorships":
|
||||||
|
header_csv = [
|
||||||
|
"user",
|
||||||
|
"date",
|
||||||
|
"admin",
|
||||||
|
"streamer",
|
||||||
|
"expires",
|
||||||
|
"proof",
|
||||||
|
"label",
|
||||||
|
]
|
||||||
|
|
||||||
|
for entry in list(col_sponsorships.find()):
|
||||||
|
del entry["_id"]
|
||||||
|
entry["date"] = entry["date"].isoformat()
|
||||||
|
entry["sponsorship"]["expires"] = entry["sponsorship"][
|
||||||
|
"expires"
|
||||||
|
].isoformat()
|
||||||
|
output_json.append(entry)
|
||||||
|
|
||||||
|
for entry in list(col_sponsorships.find()):
|
||||||
|
del entry["_id"]
|
||||||
|
entry["date"] = entry["date"].isoformat()
|
||||||
|
entry["sponsorship"]["expires"] = entry["sponsorship"][
|
||||||
|
"expires"
|
||||||
|
].isoformat()
|
||||||
|
for index, value in enumerate(entry["sponsorship"]):
|
||||||
|
entry[value] = entry["sponsorship"][value]
|
||||||
|
del entry["sponsorship"]
|
||||||
|
output_csv.append(entry)
|
||||||
|
|
||||||
|
elif selection == "bans":
|
||||||
|
header_csv = ["user", "admin", "date"]
|
||||||
|
|
||||||
|
for entry in list(col_warnings.find()):
|
||||||
|
del entry["id"]
|
||||||
|
entry["date"] = entry["date"].isoformat()
|
||||||
|
output_json.append(entry)
|
||||||
|
output_csv.append(entry)
|
||||||
|
|
||||||
|
# Saving CSV
|
||||||
|
async with aiofiles.open(temp_file + ".csv", mode="w", encoding="utf-8") as file:
|
||||||
|
writer = AsyncDictWriter(file, header_csv, restval="NULL", quoting=QUOTE_ALL)
|
||||||
|
await writer.writeheader()
|
||||||
|
await writer.writerows(output_csv)
|
||||||
|
|
||||||
|
# Saving JSON
|
||||||
|
async with aiofiles.open(temp_file + ".json", mode="w", encoding="utf-8") as file:
|
||||||
|
await file.write(
|
||||||
|
dumps(
|
||||||
|
output_json, ensure_ascii=False, escape_forward_slashes=False, indent=4
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Sending CSV
|
||||||
|
await app.send_chat_action(msg.chat.id, ChatAction.UPLOAD_DOCUMENT)
|
||||||
|
await msg.reply_document(
|
||||||
|
document=temp_file + ".csv",
|
||||||
|
file_name=f"{selection}.csv",
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Sending JSON
|
||||||
|
await app.send_chat_action(msg.chat.id, ChatAction.UPLOAD_DOCUMENT)
|
||||||
|
await msg.reply_document(
|
||||||
|
document=temp_file + ".json",
|
||||||
|
file_name=f"{selection}.json",
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
|
||||||
|
del output_csv, output_json
|
||||||
|
|
||||||
|
# Removing temp files
|
||||||
|
remove(temp_file + ".csv")
|
||||||
|
remove(temp_file + ".json")
|
105
modules/commands/identify.py
Normal file
105
modules/commands/identify.py
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
from os import path
|
||||||
|
from app import app, isAnAdmin
|
||||||
|
from pyrogram import filters
|
||||||
|
from pyrogram.types import Message
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from pyrogram.errors import bad_request_400
|
||||||
|
from pyrogram.enums.chat_action import ChatAction
|
||||||
|
from classes.errors.holo_user import UserNotFoundError, UserInvalidError
|
||||||
|
from classes.holo_user import HoloUser
|
||||||
|
from modules.utils import (
|
||||||
|
jsonLoad,
|
||||||
|
should_quote,
|
||||||
|
logWrite,
|
||||||
|
locale,
|
||||||
|
download_tmp,
|
||||||
|
create_tmp,
|
||||||
|
find_user,
|
||||||
|
)
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
(custom_filters.enabled_applications | custom_filters.enabled_sponsorships)
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.command("identify", prefixes=["/"])
|
||||||
|
& custom_filters.admin
|
||||||
|
)
|
||||||
|
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)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
holo_user = HoloUser(int(msg.command[1]))
|
||||||
|
except ValueError:
|
||||||
|
holo_user = HoloUser(await find_user(app, msg.command[1]))
|
||||||
|
except (
|
||||||
|
UserInvalidError,
|
||||||
|
UserNotFoundError,
|
||||||
|
bad_request_400.UsernameInvalid,
|
||||||
|
bad_request_400.PeerIdInvalid,
|
||||||
|
bad_request_400.UsernameNotOccupied,
|
||||||
|
TypeError,
|
||||||
|
):
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("identify_not_found", "message", locale=msg.from_user).format(
|
||||||
|
msg.command[1]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
role = holo_user.label
|
||||||
|
has_application = (
|
||||||
|
locale("yes", "message", locale=msg.from_user)
|
||||||
|
if holo_user.application_approved() is True
|
||||||
|
else locale("no", "message", locale=msg.from_user)
|
||||||
|
)
|
||||||
|
has_sponsorship = (
|
||||||
|
locale("yes", "message", locale=msg.from_user)
|
||||||
|
if holo_user.sponsorship_valid() is True
|
||||||
|
else locale("no", "message", locale=msg.from_user)
|
||||||
|
)
|
||||||
|
|
||||||
|
username = holo_user.username if holo_user.username is not None else "N/A"
|
||||||
|
in_chat = (
|
||||||
|
locale("yes", "message", locale=msg.from_user)
|
||||||
|
if (holo_user.id in jsonLoad(path.join("cache", "group_members")))
|
||||||
|
else locale("no", "message", locale=msg.from_user)
|
||||||
|
)
|
||||||
|
is_admin = (
|
||||||
|
locale("yes", "message", locale=msg.from_user)
|
||||||
|
if (await isAnAdmin(holo_user.id))
|
||||||
|
else locale("no", "message", locale=msg.from_user)
|
||||||
|
)
|
||||||
|
|
||||||
|
output = locale("identify_success", "message", locale=msg.from_user).format(
|
||||||
|
holo_user.id,
|
||||||
|
holo_user.name,
|
||||||
|
username,
|
||||||
|
in_chat,
|
||||||
|
is_admin,
|
||||||
|
role,
|
||||||
|
has_application,
|
||||||
|
has_sponsorship,
|
||||||
|
)
|
||||||
|
|
||||||
|
user = await app.get_users(holo_user.id)
|
||||||
|
|
||||||
|
if user.photo is not None:
|
||||||
|
await app.send_chat_action(msg.chat.id, action=ChatAction.UPLOAD_PHOTO)
|
||||||
|
await msg.reply_photo(
|
||||||
|
create_tmp(
|
||||||
|
(await download_tmp(app, user.photo.big_file_id))[1], kind="image"
|
||||||
|
),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
caption=output,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
await app.send_chat_action(msg.chat.id, action=ChatAction.TYPING)
|
||||||
|
await msg.reply_text(output, quote=should_quote(msg))
|
||||||
|
|
||||||
|
logWrite(f"User {msg.from_user.id} identified user {holo_user.id}")
|
30
modules/commands/issue.py
Normal file
30
modules/commands/issue.py
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
from app import app
|
||||||
|
from pyrogram import filters
|
||||||
|
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from modules.utils import configGet, locale
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
custom_filters.enabled_general
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.private
|
||||||
|
& filters.command(["issue"], prefixes=["/"])
|
||||||
|
& ~custom_filters.banned
|
||||||
|
)
|
||||||
|
async def cmd_issue(app: Client, msg: Message):
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("issue", "message", locale=msg.from_user),
|
||||||
|
disable_web_page_preview=True,
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
|
[
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale("issue", "button", locale=msg.from_user),
|
||||||
|
url=configGet("issues"),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
@@ -1,14 +1,20 @@
|
|||||||
from app import app, isAnAdmin
|
from app import app
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from pyrogram.types import ChatPrivileges
|
from pyrogram.types import Message
|
||||||
from modules.utils import should_quote, find_user, configGet
|
from pyrogram.client import Client
|
||||||
|
from modules.utils import configGet, locale, should_quote, find_user
|
||||||
|
from classes.errors.holo_user import LabelTooLongError, LabelSettingError
|
||||||
from classes.holo_user import HoloUser
|
from classes.holo_user import HoloUser
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
@app.on_message(~ filters.scheduled & filters.private & filters.command(["label"], prefixes=["/"]))
|
|
||||||
async def cmd_label(app, msg):
|
|
||||||
|
|
||||||
if msg.chat.id == configGet("admin_group") or await isAnAdmin(msg.from_user.id):
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
custom_filters.enabled_applications
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.command(["label"], prefixes=["/"])
|
||||||
|
& custom_filters.admin
|
||||||
|
)
|
||||||
|
async def cmd_label(app: Client, msg: Message):
|
||||||
if len(msg.command) < 3:
|
if len(msg.command) < 3:
|
||||||
await msg.reply_text("Invalid syntax:\n`/label USER LABEL`")
|
await msg.reply_text("Invalid syntax:\n`/label USER LABEL`")
|
||||||
return
|
return
|
||||||
@@ -16,18 +22,33 @@ async def cmd_label(app, msg):
|
|||||||
target = await find_user(app, msg.command[1])
|
target = await find_user(app, msg.command[1])
|
||||||
|
|
||||||
if target is not None:
|
if target is not None:
|
||||||
|
|
||||||
target = HoloUser(target)
|
target = HoloUser(target)
|
||||||
|
|
||||||
label = " ".join(msg.command[2:])
|
label = " ".join(msg.command[2:])
|
||||||
|
|
||||||
if label.lower() == "reset":
|
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))
|
await msg.reply_text(
|
||||||
|
f"Resetting **{target.id}**'s label...", quote=should_quote(msg)
|
||||||
|
)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
await target.set_label(msg.chat, label)
|
try:
|
||||||
await msg.reply_text(f"Setting **{target.id}**'s label to **{label}**...", quote=should_quote(msg))
|
await target.label_set(msg.chat, label)
|
||||||
|
except LabelTooLongError:
|
||||||
|
await msg.reply_text(locale("label_too_long", "message"))
|
||||||
|
return
|
||||||
|
except LabelSettingError as exp:
|
||||||
|
await app.send_message(
|
||||||
|
configGet("admin", "groups"),
|
||||||
|
exp.__str__(),
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
await msg.reply_text(
|
||||||
|
f"Setting **{target.id}**'s label to **{label}**...",
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
await msg.reply_text(f"User not found")
|
await msg.reply_text(f"User not found")
|
@@ -1,35 +1,93 @@
|
|||||||
from os import sep
|
|
||||||
from app import app, isAnAdmin
|
from app import app, isAnAdmin
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from pyrogram.errors import bad_request_400
|
from pyrogram.types import Message
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from convopyro import listen_message
|
||||||
|
from classes.errors.holo_user import UserInvalidError
|
||||||
from classes.holo_user import HoloUser
|
from classes.holo_user import HoloUser
|
||||||
from modules.utils import jsonLoad, jsonSave, logWrite, locale, configGet, should_quote
|
from modules.utils import configGet, logWrite, locale, should_quote, find_user
|
||||||
|
from modules import custom_filters
|
||||||
from modules.database import col_messages
|
from modules.database import col_messages
|
||||||
|
|
||||||
# Message command ==============================================================================================================
|
|
||||||
@app.on_message(~ filters.scheduled & filters.command(["message"], prefixes=["/"]))
|
|
||||||
async def cmd_message(app, msg):
|
|
||||||
|
|
||||||
if msg.chat.id == configGet("admin_group") or await isAnAdmin(msg.from_user.id):
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
custom_filters.enabled_general
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.command(["message"], prefixes=["/"])
|
||||||
|
# & custom_filters.admin
|
||||||
|
)
|
||||||
|
async def cmd_message(app: Client, msg: Message):
|
||||||
try:
|
try:
|
||||||
|
if await isAnAdmin(msg.from_user.id):
|
||||||
try:
|
try:
|
||||||
destination = HoloUser(int(msg.command[1]))
|
destination = HoloUser(int(msg.command[1]))
|
||||||
except ValueError:
|
except (ValueError, UserInvalidError):
|
||||||
destination = HoloUser(msg.command[1])
|
destination = HoloUser(await find_user(app, query=msg.command[1]))
|
||||||
|
if (msg.text is not None) and (len(str(msg.text).split()) > 2):
|
||||||
if ((msg.text is not None) and (len(msg.text.split()) > 2)):
|
await destination.message(
|
||||||
await destination.message(context=msg, text=" ".join(msg.text.split()[2:]), caption=msg.caption, photo=msg.photo, video=msg.video, file=msg.document, adm_context=True)
|
context=msg,
|
||||||
elif ((msg.caption is not None) and (len(msg.caption.split()) > 2)):
|
text=" ".join(str(msg.text).split()[2:]),
|
||||||
await destination.message(context=msg, text=msg.text, caption=" ".join(msg.caption.split()[2:]), photo=msg.photo, video=msg.video, file=msg.document, adm_context=True)
|
caption=msg.caption,
|
||||||
|
photo=msg.photo,
|
||||||
|
video=msg.video,
|
||||||
|
file=msg.document,
|
||||||
|
voice=msg.voice,
|
||||||
|
animation=msg.animation,
|
||||||
|
adm_context=True,
|
||||||
|
)
|
||||||
|
elif (msg.caption is not None) and (len(msg.caption.split()) > 2):
|
||||||
|
await destination.message(
|
||||||
|
context=msg,
|
||||||
|
text=str(msg.text),
|
||||||
|
caption=" ".join(msg.caption.split()[2:]),
|
||||||
|
photo=msg.photo,
|
||||||
|
video=msg.video,
|
||||||
|
file=msg.document,
|
||||||
|
voice=msg.voice,
|
||||||
|
animation=msg.animation,
|
||||||
|
adm_context=True,
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
await destination.message(context=msg, text=None, caption=None, photo=msg.photo, video=msg.video, file=msg.document, adm_context=True)
|
await destination.message(
|
||||||
|
context=msg,
|
||||||
|
text=None,
|
||||||
|
caption=None,
|
||||||
|
photo=msg.photo,
|
||||||
|
video=msg.video,
|
||||||
|
file=msg.document,
|
||||||
|
voice=msg.voice,
|
||||||
|
animation=msg.animation,
|
||||||
|
adm_context=True,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("message_enter", "message", locale=msg.from_user)
|
||||||
|
)
|
||||||
|
message = await listen_message(app, msg.chat.id, timeout=None)
|
||||||
|
if message.text is not None and message.text == "/cancel":
|
||||||
|
return
|
||||||
|
sent = await app.forward_messages(
|
||||||
|
configGet("admin", "groups"), msg.chat.id, message.id
|
||||||
|
)
|
||||||
|
col_messages.insert_one(
|
||||||
|
{
|
||||||
|
"origin": {"chat": message.chat.id, "id": message.id},
|
||||||
|
"destination": {"chat": sent.chat.id, "id": sent.id},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
await message.reply_text(
|
||||||
|
locale("message_sent", "message", locale=message.from_user), quote=True
|
||||||
|
)
|
||||||
|
|
||||||
except IndexError:
|
except IndexError:
|
||||||
await msg.reply_text(locale("message_invalid_syntax", "message"), quote=should_quote(msg))
|
await msg.reply_text(
|
||||||
|
locale("message_invalid_syntax", "message", locale=msg.from_user),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
logWrite(f"Admin {msg.from_user.id} tried to send message but 'IndexError'")
|
logWrite(f"Admin {msg.from_user.id} tried to send message but 'IndexError'")
|
||||||
except ValueError:
|
except ValueError:
|
||||||
await msg.reply_text(locale("message_invalid_syntax", "message"), quote=should_quote(msg))
|
await msg.reply_text(
|
||||||
|
locale("message_invalid_syntax", "message", locale=msg.from_user),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
logWrite(f"Admin {msg.from_user.id} tried to send message but 'ValueError'")
|
logWrite(f"Admin {msg.from_user.id} tried to send message but 'ValueError'")
|
||||||
# ==============================================================================================================================
|
|
117
modules/commands/nearby.py
Normal file
117
modules/commands/nearby.py
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
from os import path
|
||||||
|
from traceback import print_exc
|
||||||
|
from app import app
|
||||||
|
from pyrogram import filters
|
||||||
|
from pyrogram.types import Message
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from classes.holo_user import HoloUser
|
||||||
|
from modules import custom_filters
|
||||||
|
from modules.logging import logWrite
|
||||||
|
from modules.utils import configGet, jsonLoad, locale, should_quote, find_location
|
||||||
|
from modules.database import col_applications, col_users
|
||||||
|
from classes.errors.geo import PlaceNotFoundError
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
custom_filters.enabled_applications
|
||||||
|
& ~filters.scheduled
|
||||||
|
& (
|
||||||
|
filters.private
|
||||||
|
| (
|
||||||
|
filters.chat(configGet("admin", "groups"))
|
||||||
|
| filters.chat(configGet("users", "groups"))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
& filters.command(["nearby"], prefixes=["/"])
|
||||||
|
& (custom_filters.allowed | custom_filters.admin)
|
||||||
|
& ~custom_filters.banned
|
||||||
|
)
|
||||||
|
async def cmd_nearby(app: Client, msg: Message):
|
||||||
|
holo_user = HoloUser(msg.from_user)
|
||||||
|
|
||||||
|
# Check if any place provided
|
||||||
|
if len(msg.command) == 1: # Action if no place provided
|
||||||
|
application = col_applications.find_one({"user": msg.from_user.id})
|
||||||
|
if application is None:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("nearby_user_empty", "message", locale=holo_user)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
location = (
|
||||||
|
application["application"]["3"]["location"][0],
|
||||||
|
application["application"]["3"]["location"][1],
|
||||||
|
)
|
||||||
|
else: # Find a place from input query
|
||||||
|
logWrite(f"Looking for the location by query '{' '.join(msg.command[1:])}'")
|
||||||
|
try:
|
||||||
|
location_coordinates = find_location(" ".join(msg.command[1:]))
|
||||||
|
location = float(location_coordinates["lng"]), float(
|
||||||
|
location_coordinates["lat"]
|
||||||
|
)
|
||||||
|
except PlaceNotFoundError: # Place is not found
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("nearby_invalid", "message", locale=holo_user),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
except Exception as exp: # Error occurred while finding the place
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("nearby_error", "message", locale=holo_user).format(
|
||||||
|
exp, print_exc()
|
||||||
|
),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# 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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
for entry in applications_nearby:
|
||||||
|
if not entry["user"] == msg.from_user.id:
|
||||||
|
user = col_users.find_one({"user": entry["user"]})
|
||||||
|
if user is not None:
|
||||||
|
if entry["user"] in jsonLoad(
|
||||||
|
path.join(configGet("cache", "locations"), "group_members")
|
||||||
|
):
|
||||||
|
if user["tg_username"] not in [
|
||||||
|
None,
|
||||||
|
"None",
|
||||||
|
"",
|
||||||
|
]: # Check if user has any name
|
||||||
|
output.append(
|
||||||
|
f'• **{user["tg_name"]}** (@{user["tg_username"]}):\n - {entry["application"]["3"]["name"]}, {entry["application"]["3"]["adminName1"]}'
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
output.append(
|
||||||
|
f'• **{user["tg_name"]}**:\n - {entry["application"]["3"]["name"]}, {entry["application"]["3"]["adminName1"]}'
|
||||||
|
)
|
||||||
|
|
||||||
|
logWrite(
|
||||||
|
f"{holo_user.id} tried to find someone nearby {location[1]} {location[0]} in the radius of {configGet('search_radius')} kilometers"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check if any users found
|
||||||
|
if len(output) > 0:
|
||||||
|
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)
|
||||||
|
)
|
@@ -1,45 +1,169 @@
|
|||||||
from app import app
|
from app import app
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message
|
||||||
from modules.utils import configGet, configSet, locale
|
from pyrogram.client import Client
|
||||||
|
from classes.holo_user import HoloUser
|
||||||
|
from modules.logging import logWrite
|
||||||
|
from modules.utils import configGet, locale, should_quote
|
||||||
from modules.handlers.welcome import welcome_pass
|
from modules.handlers.welcome import welcome_pass
|
||||||
|
from modules.database import col_tmp, col_applications
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
# Reapply command ==============================================================================================================
|
|
||||||
@app.on_message(~ filters.scheduled & filters.private & filters.command(["reapply"], prefixes=["/"]))
|
|
||||||
async def cmd_reapply(app, msg):
|
|
||||||
|
|
||||||
if configGet("approved", file=str(msg.from_user.id)) or configGet("refused", file=str(msg.from_user.id)):
|
@app.on_message(
|
||||||
if (configGet("stage", file=str(msg.from_user.id)) == 10) and not (configGet("sent", file=str(msg.from_user.id))):
|
custom_filters.enabled_applications
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.private
|
||||||
|
& filters.command(["reapply"], prefixes=["/"])
|
||||||
|
& ~custom_filters.banned
|
||||||
|
)
|
||||||
|
async def cmd_reapply(app: Client, msg: Message):
|
||||||
|
holo_user = HoloUser(msg.from_user)
|
||||||
|
|
||||||
|
# Check if user has approved/rejected tmp application
|
||||||
|
if (
|
||||||
|
(holo_user.application_state()[0] in ["approved", "rejected"])
|
||||||
|
or (holo_user.application_state()[0] == "none")
|
||||||
|
) and holo_user.spoiler_state() is False:
|
||||||
|
# Check if user's tmp application is already completed or even sent
|
||||||
|
if (
|
||||||
|
(holo_user.application_state()[1] is True)
|
||||||
|
and (
|
||||||
|
not col_tmp.find_one({"user": holo_user.id, "type": "application"})[
|
||||||
|
"sent"
|
||||||
|
]
|
||||||
|
)
|
||||||
|
) or (holo_user.application_state()[0] == "none"):
|
||||||
left_chat = True
|
left_chat = True
|
||||||
async for member in app.get_chat_members(configGet("destination_group")):
|
|
||||||
|
async for member in app.get_chat_members(configGet("users", "groups")):
|
||||||
if member.user.id == msg.from_user.id:
|
if member.user.id == msg.from_user.id:
|
||||||
left_chat = False
|
left_chat = False
|
||||||
if not left_chat:
|
|
||||||
configSet(["reapply"], True, file=str(msg.from_user.id))
|
if left_chat is True:
|
||||||
configSet(["confirmed"], False, file=str(msg.from_user.id))
|
if holo_user.application_state()[
|
||||||
await welcome_pass(app, msg, once_again=True)
|
1
|
||||||
else:
|
] is True and holo_user.application_state()[0] not in [
|
||||||
await msg.reply_text(locale("reapply_left_chat", "message"), reply_markup=InlineKeyboardMarkup([
|
"fill",
|
||||||
|
"rejected",
|
||||||
|
]:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("reapply_left_chat", "message", locale=holo_user),
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
[
|
[
|
||||||
InlineKeyboardButton(locale("reapply_old_one", "button"), f"reapply_old_{msg.id}")
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale(
|
||||||
|
"reapply_old_one",
|
||||||
|
"button",
|
||||||
|
locale=holo_user,
|
||||||
|
),
|
||||||
|
f"reapply_old_{msg.id}",
|
||||||
|
)
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
InlineKeyboardButton(locale("reapply_new_one", "button"), f"reapply_new_{msg.id}")
|
InlineKeyboardButton(
|
||||||
|
locale(
|
||||||
|
"reapply_new_one",
|
||||||
|
"button",
|
||||||
|
locale=holo_user,
|
||||||
|
),
|
||||||
|
f"reapply_new_{msg.id}",
|
||||||
|
)
|
||||||
|
],
|
||||||
]
|
]
|
||||||
]))
|
),
|
||||||
else:
|
)
|
||||||
await msg.reply_text(locale("reapply_in_progress", "message").format(locale("confirm", "keyboard")[1][0]), reply_markup=InlineKeyboardMarkup([
|
|
||||||
|
elif (
|
||||||
|
col_tmp.find_one({"user": holo_user.id, "type": "application"})
|
||||||
|
is None
|
||||||
|
and col_applications.find_one({"user": holo_user.id}) is not None
|
||||||
|
):
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("reapply_left_chat", "message", locale=holo_user),
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
[
|
[
|
||||||
InlineKeyboardButton(locale("applying_stop", "button"), f"reapply_stop_{msg.id}")
|
|
||||||
]
|
|
||||||
]))
|
|
||||||
else:
|
|
||||||
if configGet("sent", file=str(msg.from_user.id)):
|
|
||||||
await msg.reply_text(locale("reapply_forbidden", "message"))
|
|
||||||
else:
|
|
||||||
await msg.reply_text(locale("reapply_in_progress", "message").format(locale("confirm", "keyboard")[1][0]), reply_markup=InlineKeyboardMarkup([
|
|
||||||
[
|
[
|
||||||
InlineKeyboardButton(locale("applying_stop", "button"), f"reapply_stop_{msg.id}")
|
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:
|
||||||
|
if holo_user.sponsorship_state()[0] == "fill":
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("finish_sponsorship", "message"), quote=should_quote(msg)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
holo_user.application_restart(reapply=True)
|
||||||
|
await welcome_pass(app, msg, once_again=True)
|
||||||
|
|
||||||
|
else:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("reapply_in_progress", "message", locale=holo_user).format(
|
||||||
|
locale("confirm", "keyboard", locale=holo_user)[1][0]
|
||||||
|
),
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
|
[
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale("applying_stop", "button", locale=holo_user),
|
||||||
|
f"reapply_stop_{msg.id}",
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
elif holo_user.spoiler_state() is True:
|
||||||
|
await msg.reply_text(locale("spoiler_in_progress", "message", locale=holo_user))
|
||||||
|
|
||||||
|
else:
|
||||||
|
if (holo_user.application_state()[0] == "fill") and (
|
||||||
|
col_tmp.find_one({"user": holo_user.id, "type": "application"})["sent"]
|
||||||
|
is True
|
||||||
|
):
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("reapply_forbidden", "message", locale=holo_user)
|
||||||
|
)
|
||||||
|
|
||||||
|
else:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("reapply_in_progress", "message", locale=holo_user).format(
|
||||||
|
locale("confirm", "keyboard", locale=holo_user)[1][0]
|
||||||
|
),
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
|
[
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale("applying_stop", "button", locale=holo_user),
|
||||||
|
f"reapply_stop_{msg.id}",
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
@@ -1,19 +1,34 @@
|
|||||||
from app import app, isAnAdmin
|
from app import app
|
||||||
from os import getpid
|
from os import getpid, makedirs, path
|
||||||
from sys import exit
|
from sys import exit
|
||||||
|
from time import time
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from modules.utils import configGet, logWrite, should_quote
|
from pyrogram.types import Message
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from modules.utils import configGet, jsonSave, locale, logWrite, should_quote
|
||||||
from modules.scheduled import scheduler
|
from modules.scheduled import scheduler
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
pid = getpid()
|
pid = getpid()
|
||||||
|
|
||||||
# Shutdown command =============================================================================================================
|
|
||||||
@app.on_message(~ filters.scheduled & filters.private & filters.command(["kill", "die", "reboot"], prefixes=["/"]))
|
|
||||||
async def cmd_kill(app, msg):
|
|
||||||
|
|
||||||
if msg.chat.id == configGet("admin_group") or await isAnAdmin(msg.from_user.id):
|
@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}")
|
logWrite(f"Shutting down bot with pid {pid}")
|
||||||
await msg.reply_text(f"Вимкнення бота з підом `{pid}`", quote=should_quote(msg))
|
await msg.reply_text(
|
||||||
|
locale("shutdown", "message", locale=msg.from_user).format(pid),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
scheduler.shutdown()
|
scheduler.shutdown()
|
||||||
|
makedirs(configGet("cache", "locations"), exist_ok=True)
|
||||||
|
jsonSave(
|
||||||
|
{"timestamp": time()},
|
||||||
|
path.join(configGet("cache", "locations"), "shutdown_time"),
|
||||||
|
)
|
||||||
exit()
|
exit()
|
||||||
# ==============================================================================================================================
|
|
111
modules/commands/resetcommands.py
Normal file
111
modules/commands/resetcommands.py
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
from app import app
|
||||||
|
from os import getpid, listdir
|
||||||
|
from pyrogram import filters
|
||||||
|
from pyrogram.types import Message, BotCommandScopeDefault, BotCommandScopeChat
|
||||||
|
from pyrogram.errors import bad_request_400
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from modules.utils import logWrite, should_quote, configGet
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
|
pid = getpid()
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
custom_filters.enabled_general
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.private
|
||||||
|
& filters.command(["resetcommands"], prefixes=["/"])
|
||||||
|
& custom_filters.admin
|
||||||
|
)
|
||||||
|
async def cmd_resetcommands(app: Client, msg: Message):
|
||||||
|
if msg.from_user.id == configGet("owner"):
|
||||||
|
logWrite(f"Resetting all commands on owner's request")
|
||||||
|
|
||||||
|
valid_locales = []
|
||||||
|
files_locales = listdir(f'{configGet("locale", "locations")}')
|
||||||
|
|
||||||
|
for entry in files_locales:
|
||||||
|
if entry.endswith(".json"):
|
||||||
|
valid_locales.append(".".join(entry.split(".")[:-1]))
|
||||||
|
|
||||||
|
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 lc in valid_locales:
|
||||||
|
try:
|
||||||
|
logWrite(
|
||||||
|
f'Resetting commands in groups {configGet("admin", "groups")} and {configGet("users", "groups")} [{lc}]',
|
||||||
|
debug=True,
|
||||||
|
)
|
||||||
|
await app.delete_bot_commands(
|
||||||
|
scope=BotCommandScopeChat(chat_id=configGet("admin", "groups")),
|
||||||
|
language_code=lc,
|
||||||
|
)
|
||||||
|
await app.delete_bot_commands(
|
||||||
|
scope=BotCommandScopeChat(chat_id=configGet("users", "groups")),
|
||||||
|
language_code=lc,
|
||||||
|
)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
for admin in configGet("admins"):
|
||||||
|
try:
|
||||||
|
logWrite(f"Resetting commands for admin {admin}", debug=True)
|
||||||
|
await app.delete_bot_commands(scope=BotCommandScopeChat(chat_id=admin))
|
||||||
|
for lc in valid_locales:
|
||||||
|
try:
|
||||||
|
logWrite(
|
||||||
|
f"Resetting commands for admin {admin} [{lc}]", debug=True
|
||||||
|
)
|
||||||
|
await app.delete_bot_commands(
|
||||||
|
scope=BotCommandScopeChat(chat_id=admin), language_code=lc
|
||||||
|
)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
except bad_request_400.PeerIdInvalid:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
logWrite(f'Resetting commands for owner {configGet("owner")}', debug=True)
|
||||||
|
for lc in valid_locales:
|
||||||
|
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:
|
||||||
|
logWrite(f"Resetting commands for locale {lc}", debug=True)
|
||||||
|
await app.delete_bot_commands(
|
||||||
|
scope=BotCommandScopeDefault(), language_code=lc
|
||||||
|
)
|
||||||
|
|
||||||
|
logWrite(f"Resetting default commands", debug=True)
|
||||||
|
await app.delete_bot_commands()
|
||||||
|
|
||||||
|
await msg.reply_text("OK", quote=should_quote(msg))
|
||||||
|
|
||||||
|
logWrite(str(await app.get_bot_commands()), debug=True)
|
||||||
|
logWrite(
|
||||||
|
str(
|
||||||
|
await app.get_bot_commands(
|
||||||
|
scope=BotCommandScopeChat(chat_id=configGet("owner"))
|
||||||
|
)
|
||||||
|
),
|
||||||
|
debug=True,
|
||||||
|
)
|
@@ -1,34 +1,57 @@
|
|||||||
|
from typing import Union
|
||||||
from app import app
|
from app import app
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, User, Message
|
||||||
|
from pyrogram.client import Client
|
||||||
from modules.utils import locale
|
from modules.utils import locale
|
||||||
|
from modules import custom_filters
|
||||||
|
from classes.holo_user import HoloUser
|
||||||
|
|
||||||
# Rules command =============================================================================================================
|
|
||||||
default_rules_markup = InlineKeyboardMarkup(
|
class DefaultRulesMarkup(list):
|
||||||
|
def __init__(self, language_code: Union[str, HoloUser, User, None]):
|
||||||
|
super().__init__([])
|
||||||
|
self.keyboard = InlineKeyboardMarkup(
|
||||||
[
|
[
|
||||||
[
|
[
|
||||||
InlineKeyboardButton(locale("rules_home", "button"), callback_data="rules_home"),
|
InlineKeyboardButton(
|
||||||
InlineKeyboardButton(locale("rules_additional", "button"), callback_data="rules_additional")
|
locale("rules_home", "button", locale=language_code),
|
||||||
|
callback_data="rules_home",
|
||||||
|
),
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale("rules_additional", "button", locale=language_code),
|
||||||
|
callback_data="rules_additional",
|
||||||
|
),
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
InlineKeyboardButton("1", callback_data="rule_1"),
|
InlineKeyboardButton("1", callback_data="rule_1"),
|
||||||
InlineKeyboardButton("2", callback_data="rule_2"),
|
InlineKeyboardButton("2", callback_data="rule_2"),
|
||||||
InlineKeyboardButton("3", callback_data="rule_3")
|
InlineKeyboardButton("3", callback_data="rule_3"),
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
InlineKeyboardButton("4", callback_data="rule_4"),
|
InlineKeyboardButton("4", callback_data="rule_4"),
|
||||||
InlineKeyboardButton("5", callback_data="rule_5"),
|
InlineKeyboardButton("5", callback_data="rule_5"),
|
||||||
InlineKeyboardButton("6", callback_data="rule_6")
|
InlineKeyboardButton("6", callback_data="rule_6"),
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
InlineKeyboardButton("7", callback_data="rule_7"),
|
InlineKeyboardButton("7", callback_data="rule_7"),
|
||||||
InlineKeyboardButton("8", callback_data="rule_8"),
|
InlineKeyboardButton("8", callback_data="rule_8"),
|
||||||
InlineKeyboardButton("9", callback_data="rule_9")
|
InlineKeyboardButton("9", callback_data="rule_9"),
|
||||||
|
],
|
||||||
]
|
]
|
||||||
]
|
)
|
||||||
)
|
|
||||||
|
|
||||||
@app.on_message(~ filters.scheduled & filters.private & filters.command(["rules"], prefixes=["/"]))
|
|
||||||
async def cmd_rules(app, msg):
|
@app.on_message(
|
||||||
await msg.reply_text(locale("rules_msg"), disable_web_page_preview=True, reply_markup=default_rules_markup)
|
custom_filters.enabled_general
|
||||||
# ==============================================================================================================================
|
& ~filters.scheduled
|
||||||
|
& filters.private
|
||||||
|
& ~custom_filters.banned
|
||||||
|
& filters.command(["rules"], prefixes=["/"])
|
||||||
|
)
|
||||||
|
async def cmd_rules(app: Client, msg: Message):
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("rules_msg", locale=msg.from_user),
|
||||||
|
disable_web_page_preview=True,
|
||||||
|
reply_markup=DefaultRulesMarkup(msg.from_user).keyboard,
|
||||||
|
)
|
||||||
|
64
modules/commands/spoiler.py
Normal file
64
modules/commands/spoiler.py
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
from app import app
|
||||||
|
from pyrogram import filters
|
||||||
|
from pyrogram.types import Message, ReplyKeyboardMarkup
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from classes.errors.holo_user import UserNotFoundError, UserInvalidError
|
||||||
|
from classes.holo_user import HoloUser
|
||||||
|
from modules.logging import logWrite
|
||||||
|
from modules.utils import locale
|
||||||
|
from modules.database import col_spoilers, col_applications
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
custom_filters.enabled_spoilers
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.private
|
||||||
|
& ~custom_filters.banned
|
||||||
|
& filters.command(["spoiler"], prefixes=["/"])
|
||||||
|
)
|
||||||
|
async def cmd_spoiler(app: Client, msg: Message):
|
||||||
|
try:
|
||||||
|
holo_user = HoloUser(msg.from_user)
|
||||||
|
except (UserInvalidError, UserNotFoundError):
|
||||||
|
return
|
||||||
|
|
||||||
|
if col_applications.find_one({"user": holo_user.id}) is None:
|
||||||
|
await msg.reply_text(locale("not_member", "message", locale=msg.from_user))
|
||||||
|
return
|
||||||
|
|
||||||
|
if (
|
||||||
|
holo_user.application_state()[0] != "fill"
|
||||||
|
and holo_user.sponsorship_state()[0] != "fill"
|
||||||
|
):
|
||||||
|
if col_spoilers.find_one({"user": holo_user.id, "completed": False}) is None:
|
||||||
|
col_spoilers.insert_one(
|
||||||
|
{
|
||||||
|
"user": holo_user.id,
|
||||||
|
"completed": False,
|
||||||
|
"category": None,
|
||||||
|
"description": None,
|
||||||
|
"photo": None,
|
||||||
|
"video": None,
|
||||||
|
"audio": None,
|
||||||
|
"animation": None,
|
||||||
|
"document": None,
|
||||||
|
"caption": None,
|
||||||
|
"text": None,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("spoiler_started", "message", locale=msg.from_user),
|
||||||
|
reply_markup=ReplyKeyboardMarkup(
|
||||||
|
locale("spoiler_categories", "keyboard"),
|
||||||
|
resize_keyboard=True,
|
||||||
|
one_time_keyboard=True,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
logWrite(f"User {msg.from_user.id} started creating new spoiler")
|
||||||
|
|
||||||
|
else:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("spoiler_unfinished", "message", locale=msg.from_user)
|
||||||
|
)
|
@@ -1,23 +1,46 @@
|
|||||||
from datetime import datetime
|
|
||||||
from os import path, sep
|
|
||||||
from app import app
|
from app import app
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from modules.utils import configGet, jsonLoad, jsonSave
|
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from classes.holo_user import HoloUser
|
||||||
|
from modules import custom_filters
|
||||||
|
from modules.utils import locale, should_quote
|
||||||
|
from modules.database import col_applications
|
||||||
|
|
||||||
# Sponsorship command ==========================================================================================================
|
|
||||||
@app.on_message(~ filters.scheduled & filters.command(["sponsorship"], prefixes=["/"]))
|
@app.on_message(
|
||||||
async def cmd_sponsorship(app, msg):
|
custom_filters.enabled_sponsorships
|
||||||
if not path.exists(f"{configGet('data', 'locations')}{sep}sponsors{sep}{msg.from_user.id}.json"):
|
& ~filters.scheduled
|
||||||
jsonSave(jsonLoad(f"{configGet('data', 'locations')}{sep}sponsor_default.json"), f"{configGet('data', 'locations')}{sep}sponsors{sep}{msg.from_user.id}.json")
|
& filters.command(["sponsorship"], prefixes=["/"])
|
||||||
sponsor = jsonLoad(f"{configGet('data', 'locations')}{sep}sponsors{sep}{msg.from_user.id}.json")
|
& ~custom_filters.banned
|
||||||
if sponsor["approved"]:
|
& (custom_filters.allowed | custom_filters.admin)
|
||||||
if sponsor["expires"] is not None:
|
)
|
||||||
if datetime.strptime(sponsor["expires"], "%d.%m.%Y") > datetime.now():
|
async def cmd_sponsorship(app: Client, msg: Message):
|
||||||
await msg.reply_text(f"You have an active sub til **{sponsor['expires']}**.")
|
holo_user = HoloUser(msg.from_user)
|
||||||
else:
|
if holo_user.application_state()[0] == "fill":
|
||||||
await msg.reply_text(f"Your sub expired {int((datetime.now()-datetime.strptime(sponsor['expires'], '%d.%m.%Y')).days)} days ago.")
|
await msg.reply_text(
|
||||||
elif sponsor["approved"]:
|
locale("finish_application", "message", locale=msg.from_user),
|
||||||
await msg.reply_text(f"Your sub expiration date is not valid.")
|
quote=should_quote(msg),
|
||||||
else:
|
)
|
||||||
await msg.reply_text(f"You have no active subscription.")
|
return
|
||||||
# ==============================================================================================================================
|
if holo_user.spoiler_state() is True:
|
||||||
|
await msg.reply_text(locale("spoiler_in_progress", "message", locale=holo_user))
|
||||||
|
return
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("sponsorship_apply", "message", locale=msg.from_user),
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
|
[
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
text=str(
|
||||||
|
locale("sponsor_apply", "button", locale=msg.from_user)
|
||||||
|
),
|
||||||
|
callback_data=f"sponsor_apply_{msg.from_user.id}",
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
# else:
|
||||||
|
# await msg.reply_text(locale("sponsorship_application_empty", "message"))
|
||||||
|
@@ -1,28 +1,70 @@
|
|||||||
from app import app
|
from app import app
|
||||||
from os import sep
|
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from pyrogram.types import ReplyKeyboardMarkup
|
from pyrogram.types import ReplyKeyboardMarkup, Message
|
||||||
|
from pyrogram.client import Client
|
||||||
from modules.utils import locale, logWrite
|
from modules.utils import locale, logWrite
|
||||||
from modules.database import col_users
|
from modules.database import col_users, col_spoilers
|
||||||
|
from modules import custom_filters
|
||||||
|
from bson.objectid import ObjectId
|
||||||
|
from bson.errors import InvalidId
|
||||||
|
|
||||||
# Start command ================================================================================================================
|
|
||||||
@app.on_message(~ filters.scheduled & filters.private & filters.command(["start"], prefixes=["/"]))
|
|
||||||
async def cmd_start(app, msg):
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
custom_filters.enabled_applications
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.private
|
||||||
|
& filters.command(["start"], prefixes=["/"])
|
||||||
|
& ~custom_filters.banned
|
||||||
|
)
|
||||||
|
async def cmd_start(app: Client, msg: Message):
|
||||||
user = col_users.find_one({"user": msg.from_user.id})
|
user = col_users.find_one({"user": msg.from_user.id})
|
||||||
|
|
||||||
if user is None:
|
if user is None:
|
||||||
|
col_users.insert_one(
|
||||||
col_users.insert_one({
|
{
|
||||||
"user": msg.from_user.id,
|
"user": msg.from_user.id,
|
||||||
"link": None,
|
"link": None,
|
||||||
"label": "",
|
"label": "",
|
||||||
"tg_name": msg.from_user.first_name,
|
"tg_name": msg.from_user.first_name,
|
||||||
"tg_phone": msg.from_user.phone_number,
|
"tg_phone": msg.from_user.phone_number,
|
||||||
"tg_locale": msg.from_user.language_code,
|
"tg_locale": msg.from_user.language_code,
|
||||||
"tg_username": msg.from_user.username
|
"tg_username": msg.from_user.username,
|
||||||
})
|
}
|
||||||
|
)
|
||||||
|
|
||||||
logWrite(f"User {msg.from_user.id} started bot interaction")
|
logWrite(f"User {msg.from_user.id} started bot interaction")
|
||||||
await msg.reply_text(locale("start", "message"), reply_markup=ReplyKeyboardMarkup(locale("welcome", "keyboard"), resize_keyboard=True))
|
await msg.reply_text(
|
||||||
# ==============================================================================================================================
|
locale("start", "message", locale=msg.from_user),
|
||||||
|
reply_markup=ReplyKeyboardMarkup(
|
||||||
|
locale("welcome", "keyboard", locale=msg.from_user),
|
||||||
|
resize_keyboard=True,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
if len(msg.command) > 1:
|
||||||
|
try:
|
||||||
|
spoiler = col_spoilers.find_one({"_id": ObjectId(msg.command[1])})
|
||||||
|
if spoiler["photo"] is not None:
|
||||||
|
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["audio"] is not None:
|
||||||
|
await msg.reply_cached_media(
|
||||||
|
spoiler["audio"], 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_cached_media(
|
||||||
|
spoiler["document"], caption=spoiler["caption"]
|
||||||
|
)
|
||||||
|
if spoiler["text"] is not None:
|
||||||
|
await msg.reply_text(spoiler["text"])
|
||||||
|
except InvalidId:
|
||||||
|
await msg.reply_text(f"Got an invalid ID {msg.command[1]}")
|
||||||
|
@@ -1,20 +1,45 @@
|
|||||||
from os import sep
|
from datetime import datetime
|
||||||
from app import app, isAnAdmin
|
from app import app
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from modules.utils import jsonLoad, jsonSave, configGet, locale
|
from pyrogram.types import Message
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from modules.utils import configGet, locale
|
||||||
|
from modules.database import col_warnings
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
# Warn command =================================================================================================================
|
|
||||||
@app.on_message(~ filters.scheduled & filters.command(["warn"], prefixes=["/"]))
|
|
||||||
async def cmd_warn(app, msg):
|
|
||||||
|
|
||||||
if msg.chat.id == configGet("destination_group"):
|
@app.on_message(
|
||||||
|
custom_filters.enabled_warnings
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.command(["warn"], prefixes=["/"])
|
||||||
|
& custom_filters.admin
|
||||||
|
)
|
||||||
|
async def cmd_warn(app: Client, msg: Message):
|
||||||
|
if msg.chat.id == configGet("users", "groups"):
|
||||||
if msg.reply_to_message_id != None:
|
if msg.reply_to_message_id != None:
|
||||||
if isAnAdmin(msg.from_user.id):
|
message = " ".join(msg.command[1:]) if len(msg.command) > 1 else ""
|
||||||
warnings = jsonLoad(f"{configGet('data', 'locations')}{sep}warnings.json")
|
col_warnings.insert_one(
|
||||||
if str(msg.reply_to_message.from_user.id) not in warnings:
|
{
|
||||||
warnings[str(msg.reply_to_message.from_user.id)] = 1
|
"user": msg.reply_to_message.from_user.id,
|
||||||
|
"admin": msg.from_user.id,
|
||||||
|
"date": datetime.now(),
|
||||||
|
"reason": message,
|
||||||
|
"active": True,
|
||||||
|
"revoke_date": None,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if message == "":
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("warned", "message").format(
|
||||||
|
msg.reply_to_message.from_user.first_name,
|
||||||
|
msg.reply_to_message.from_user.id,
|
||||||
|
)
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
warnings[str(msg.reply_to_message.from_user.id)] += 1
|
await msg.reply_text(
|
||||||
jsonSave(warnings, f"{configGet('data', 'locations')}{sep}warnings.json")
|
locale("warned_reason", "message").format(
|
||||||
await msg.reply_text(locale("warned", "message").format(msg.reply_to_message.from_user.first_name, msg.reply_to_message.from_user.id))
|
msg.reply_to_message.from_user.first_name,
|
||||||
# ==============================================================================================================================
|
msg.reply_to_message.from_user.id,
|
||||||
|
message,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
@@ -1,41 +1,139 @@
|
|||||||
from os import path, sep
|
from os import path
|
||||||
from app import app, isAnAdmin
|
from app import app
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
|
from pyrogram.types import Message
|
||||||
|
from pyrogram.client import Client
|
||||||
from pyrogram.enums.chat_members_filter import ChatMembersFilter
|
from pyrogram.enums.chat_members_filter import ChatMembersFilter
|
||||||
from modules.utils import configGet, jsonLoad, locale, should_quote
|
from modules.utils import configGet, jsonLoad, locale, should_quote
|
||||||
|
from modules.database import col_users, col_warnings
|
||||||
|
from modules import custom_filters
|
||||||
|
from pykeyboard import InlineKeyboard, InlineButton
|
||||||
|
|
||||||
# Warnings command =============================================================================================================
|
|
||||||
@app.on_message(~ filters.scheduled & filters.command(["warnings"], prefixes=["/"]))
|
|
||||||
async def cmd_warnings(app, msg):
|
|
||||||
|
|
||||||
if msg.chat.id == configGet("admin_group") or await isAnAdmin(msg.from_user.id):
|
@app.on_message(
|
||||||
|
custom_filters.enabled_warnings
|
||||||
warnings = jsonLoad(f"{configGet('data', 'locations')}{sep}warnings.json")
|
& ~filters.scheduled
|
||||||
|
& filters.command(["warnings"], prefixes=["/"])
|
||||||
if len(msg.command) <= 1:
|
& custom_filters.admin
|
||||||
await msg.reply_text(locale("syntax_warnings", "message"), quote=should_quote(msg))
|
)
|
||||||
|
async def cmd_warnings(app: Client, msg: Message):
|
||||||
if path.exists(f"{configGet('data', 'locations')}{sep}users{sep}{msg.command[1]}.json"):
|
if len(msg.command) == 1:
|
||||||
target_id = str(int(msg.command[1]))
|
warnings = {}
|
||||||
target_name = "N/A"
|
warnings_output = []
|
||||||
|
group_members = jsonLoad(
|
||||||
|
path.join(configGet("cache", "locations"), "group_members")
|
||||||
|
)
|
||||||
|
for warning in col_warnings.find({"active": True}):
|
||||||
|
if warning["user"] not in group_members:
|
||||||
|
continue
|
||||||
|
if str(warning["user"]) not in warnings:
|
||||||
|
warnings[str(warning["user"])] = {
|
||||||
|
"name": (col_users.find_one({"user": warning["user"]}))["tg_name"],
|
||||||
|
"warns": 1,
|
||||||
|
}
|
||||||
else:
|
else:
|
||||||
|
warnings[str(warning["user"])]["warns"] += 1
|
||||||
|
for warning in warnings:
|
||||||
|
warnings_output.append(
|
||||||
|
locale("warnings_entry", "message", locale=msg.from_user).format(
|
||||||
|
warnings[warning]["name"], warning, warnings[warning]["warns"]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
warnings_output = (
|
||||||
|
locale("warnings_empty", "message", locale=msg.from_user)
|
||||||
|
if len(warnings_output) == 0
|
||||||
|
else "\n".join(warnings_output)
|
||||||
|
)
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("warnings_all", "message", locale=msg.from_user).format(
|
||||||
|
warnings_output
|
||||||
|
),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if len(msg.command) > 3:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("syntax_warnings", "message", locale=msg.from_user),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
user_db = col_users.find_one({"user": int(msg.command[1])})
|
||||||
|
target_id = user_db["user"]
|
||||||
|
target_name = user_db["tg_name"]
|
||||||
|
except:
|
||||||
list_of_users = []
|
list_of_users = []
|
||||||
async for m in app.get_chat_members(configGet("destination_group"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]):
|
async for m in app.get_chat_members(
|
||||||
|
configGet("users", "groups"),
|
||||||
|
filter=ChatMembersFilter.SEARCH,
|
||||||
|
query=msg.command[1],
|
||||||
|
):
|
||||||
list_of_users.append(m)
|
list_of_users.append(m)
|
||||||
|
|
||||||
if len(list_of_users) != 0:
|
if len(list_of_users) != 0:
|
||||||
target = list_of_users[0].user
|
target = list_of_users[0].user
|
||||||
target_name = target.first_name
|
target_name = target.first_name
|
||||||
target_id = str(target.id)
|
target_id = target.id
|
||||||
else:
|
else:
|
||||||
await msg.reply_text(locale("no_user_warnings", "message").format(msg.command[1]))
|
await msg.reply_text(
|
||||||
|
locale("no_user_warnings", "message", locale=msg.from_user).format(
|
||||||
|
msg.command[1]
|
||||||
|
)
|
||||||
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
if target_id not in warnings:
|
if len(msg.command) == 3 and msg.command[2].lower() == "revoke":
|
||||||
await msg.reply_text(locale("no_warnings", "message").format(target_name, target_id), quote=should_quote(msg))
|
if col_warnings.count_documents({"user": target_id, "active": True}) == 0:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("no_warnings", "message", locale=msg.from_user).format(
|
||||||
|
target_name, target_id
|
||||||
|
),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
keyboard = InlineKeyboard()
|
||||||
|
buttons = []
|
||||||
|
warnings = []
|
||||||
|
for index, warning in enumerate(
|
||||||
|
list(col_warnings.find({"user": target_id, "active": True}))
|
||||||
|
):
|
||||||
|
warnings.append(
|
||||||
|
f'{index+1}. {warning["date"].strftime("%d.%m.%Y, %H:%M")}\n Адмін: {warning["admin"]}\n Причина: {warning["reason"]}'
|
||||||
|
)
|
||||||
|
buttons.append(InlineButton(str(index + 1), f'w_rev_{str(warning["_id"])}'))
|
||||||
|
keyboard.add(*buttons)
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("warnings_revoke", "message", locale=msg.from_user).format(
|
||||||
|
target_name, "\n".join(warnings)
|
||||||
|
),
|
||||||
|
reply_markup=keyboard,
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
warns = col_warnings.count_documents({"user": target_id, "active": True})
|
||||||
|
|
||||||
|
if warns == 0:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("no_warnings", "message", locale=msg.from_user).format(
|
||||||
|
target_name, target_id
|
||||||
|
),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
if warnings[target_id] <= 5:
|
if warns <= 5:
|
||||||
await msg.reply_text(locale("warnings_1", "message").format(target_name, target_id, warnings[target_id]), quote=should_quote(msg))
|
await msg.reply_text(
|
||||||
|
locale("warnings_1", "message", locale=msg.from_user).format(
|
||||||
|
target_name, target_id, warns, target_id
|
||||||
|
),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
await msg.reply_text(locale("warnings_2", "message").format(target_name, target_id, warnings[target_id]), quote=should_quote(msg))
|
await msg.reply_text(
|
||||||
# ==============================================================================================================================
|
locale("warnings_2", "message", locale=msg.from_user).format(
|
||||||
|
target_name, target_id, warns, target_id
|
||||||
|
),
|
||||||
|
quote=should_quote(msg),
|
||||||
|
)
|
||||||
|
@@ -1,49 +0,0 @@
|
|||||||
from modules.logging import logWrite
|
|
||||||
from modules.utils import configGet
|
|
||||||
from pyrogram.types import BotCommand, BotCommandScopeChat
|
|
||||||
from pyrogram.errors import bad_request_400
|
|
||||||
|
|
||||||
def commands_register(app):
|
|
||||||
|
|
||||||
# Registering user commands
|
|
||||||
commands_list = []
|
|
||||||
for command in configGet("commands"):
|
|
||||||
commands_list.append(BotCommand(command, configGet("commands")[command]))
|
|
||||||
app.set_bot_commands(commands_list)
|
|
||||||
|
|
||||||
# Registering admin commands
|
|
||||||
commands_admin_list = []
|
|
||||||
for command in configGet("commands"):
|
|
||||||
commands_admin_list.append(BotCommand(command, configGet("commands")[command]))
|
|
||||||
|
|
||||||
for command in configGet("commands_admin"):
|
|
||||||
commands_admin_list.append(BotCommand(command, configGet("commands_admin")[command]))
|
|
||||||
|
|
||||||
for admin in configGet("admins"):
|
|
||||||
try:
|
|
||||||
app.set_bot_commands(commands_admin_list, scope=BotCommandScopeChat(chat_id=admin))
|
|
||||||
except bad_request_400.PeerIdInvalid:
|
|
||||||
pass
|
|
||||||
|
|
||||||
try:
|
|
||||||
app.set_bot_commands(commands_admin_list, scope=BotCommandScopeChat(chat_id=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
|
|
||||||
commands_group_admin_list = []
|
|
||||||
for command in configGet("commands_group_admin"):
|
|
||||||
commands_group_admin_list.append(BotCommand(command, configGet("commands_group_admin")[command]))
|
|
||||||
try:
|
|
||||||
app.set_bot_commands(commands_group_admin_list, scope=BotCommandScopeChat(chat_id=configGet("admin_group")))
|
|
||||||
except bad_request_400.ChannelInvalid:
|
|
||||||
logWrite(f"Could not register commands for admin group. Bot is likely not in the group.")
|
|
||||||
|
|
||||||
# Registering destination group commands
|
|
||||||
commands_group_destination_list = []
|
|
||||||
for command in configGet("commands_group_destination"):
|
|
||||||
commands_group_destination_list.append(BotCommand(command, configGet("commands_group_destination")[command]))
|
|
||||||
try:
|
|
||||||
app.set_bot_commands(commands_group_destination_list, scope=BotCommandScopeChat(chat_id=configGet("destination_group")))
|
|
||||||
except bad_request_400.ChannelInvalid:
|
|
||||||
logWrite(f"Could not register commands for destination group. Bot is likely not in the group.")
|
|
97
modules/custom_filters.py
Normal file
97
modules/custom_filters.py
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
"""Custom message filters made to improve commands
|
||||||
|
usage in context of Holo Users."""
|
||||||
|
|
||||||
|
from os import path
|
||||||
|
from app import isAnAdmin
|
||||||
|
from modules.utils import configGet, jsonLoad
|
||||||
|
from modules.database import col_applications, col_tmp, col_bans
|
||||||
|
from pyrogram import filters
|
||||||
|
from pyrogram.types import Message
|
||||||
|
|
||||||
|
|
||||||
|
async def admin_func(_, __, msg: Message):
|
||||||
|
return await isAnAdmin(msg.from_user.id)
|
||||||
|
|
||||||
|
|
||||||
|
async def member_func(_, __, msg: Message):
|
||||||
|
return (
|
||||||
|
True
|
||||||
|
if (
|
||||||
|
msg.from_user.id
|
||||||
|
in jsonLoad(path.join(configGet("cache", "locations"), "group_members"))
|
||||||
|
)
|
||||||
|
else False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def allowed_func(_, __, msg: Message):
|
||||||
|
output = False
|
||||||
|
output = (
|
||||||
|
True
|
||||||
|
if (col_applications.find_one({"user": msg.from_user.id}) is not None)
|
||||||
|
else False
|
||||||
|
)
|
||||||
|
if path.exists(path.join(configGet("cache", "locations"), "group_members")) and (
|
||||||
|
msg.from_user.id
|
||||||
|
not in jsonLoad(path.join(configGet("cache", "locations"), "group_members"))
|
||||||
|
):
|
||||||
|
output = False
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
async def banned_func(_, __, msg: Message):
|
||||||
|
return True if col_bans.find_one({"user": msg.from_user.id}) is not None else False
|
||||||
|
|
||||||
|
|
||||||
|
async def enabled_general_func(_, __, msg: Message):
|
||||||
|
return configGet("enabled", "features", "general")
|
||||||
|
|
||||||
|
|
||||||
|
async def enabled_applications_func(_, __, msg: Message):
|
||||||
|
return configGet("enabled", "features", "applications")
|
||||||
|
|
||||||
|
|
||||||
|
async def enabled_sponsorships_func(_, __, msg: Message):
|
||||||
|
return configGet("enabled", "features", "sponsorships")
|
||||||
|
|
||||||
|
|
||||||
|
async def enabled_warnings_func(_, __, msg: Message):
|
||||||
|
return configGet("enabled", "features", "warnings")
|
||||||
|
|
||||||
|
|
||||||
|
async def enabled_invites_check_func(_, __, msg: Message):
|
||||||
|
return configGet("enabled", "features", "invites_check")
|
||||||
|
|
||||||
|
|
||||||
|
async def enabled_dinovoice_func(_, __, msg: Message):
|
||||||
|
return configGet("enabled", "features", "dinovoice")
|
||||||
|
|
||||||
|
|
||||||
|
async def enabled_spoilers_func(_, __, msg: Message):
|
||||||
|
return configGet("enabled", "features", "spoilers")
|
||||||
|
|
||||||
|
|
||||||
|
async def filling_sponsorship_func(_, __, msg: Message):
|
||||||
|
return (
|
||||||
|
True
|
||||||
|
if col_tmp.find_one({"user": msg.from_user.id, "type": "sponsorship"})
|
||||||
|
is not None
|
||||||
|
else False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
admin = filters.create(admin_func)
|
||||||
|
member = filters.create(member_func)
|
||||||
|
allowed = filters.create(allowed_func)
|
||||||
|
|
||||||
|
banned = filters.create(banned_func)
|
||||||
|
|
||||||
|
enabled_general = filters.create(enabled_general_func)
|
||||||
|
enabled_applications = filters.create(enabled_applications_func)
|
||||||
|
enabled_sponsorships = filters.create(enabled_sponsorships_func)
|
||||||
|
enabled_warnings = filters.create(enabled_warnings_func)
|
||||||
|
enabled_invites_check = filters.create(enabled_invites_check_func)
|
||||||
|
enabled_dinovoice = filters.create(enabled_dinovoice_func)
|
||||||
|
enabled_spoilers = filters.create(enabled_spoilers_func)
|
||||||
|
|
||||||
|
filling_sponsorship = filters.create(filling_sponsorship_func)
|
@@ -1,4 +1,7 @@
|
|||||||
from pymongo import MongoClient
|
"""Module that provides all database columns and
|
||||||
|
creates geospatial index for col_applications"""
|
||||||
|
|
||||||
|
from pymongo import MongoClient, GEOSPHERE
|
||||||
from ujson import loads
|
from ujson import loads
|
||||||
|
|
||||||
with open("config.json", "r", encoding="utf-8") as f:
|
with open("config.json", "r", encoding="utf-8") as f:
|
||||||
@@ -6,18 +9,16 @@ with open("config.json", "r", encoding="utf-8") as f:
|
|||||||
f.close()
|
f.close()
|
||||||
|
|
||||||
if db_config["user"] is not None and db_config["password"] is not None:
|
if db_config["user"] is not None and db_config["password"] is not None:
|
||||||
con_string = 'mongodb://{0}:{1}@{2}:{3}/{4}'.format(
|
con_string = "mongodb://{0}:{1}@{2}:{3}/{4}".format(
|
||||||
db_config["user"],
|
db_config["user"],
|
||||||
db_config["password"],
|
db_config["password"],
|
||||||
db_config["host"],
|
db_config["host"],
|
||||||
db_config["port"],
|
db_config["port"],
|
||||||
db_config["name"]
|
db_config["name"],
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
con_string = 'mongodb://{0}:{1}/{2}'.format(
|
con_string = "mongodb://{0}:{1}/{2}".format(
|
||||||
db_config["host"],
|
db_config["host"], db_config["port"], db_config["name"]
|
||||||
db_config["port"],
|
|
||||||
db_config["name"]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
db_client = MongoClient(con_string)
|
db_client = MongoClient(con_string)
|
||||||
@@ -25,13 +26,30 @@ db = db_client.get_database(name=db_config["name"])
|
|||||||
|
|
||||||
collections = db.list_collection_names()
|
collections = db.list_collection_names()
|
||||||
|
|
||||||
for collection in ["users", "context", "messages", "warnings", "applications", "sponsorships"]:
|
for collection in [
|
||||||
|
"tmp",
|
||||||
|
"bans",
|
||||||
|
"users",
|
||||||
|
"context",
|
||||||
|
"youtube",
|
||||||
|
"spoilers",
|
||||||
|
"messages",
|
||||||
|
"warnings",
|
||||||
|
"applications",
|
||||||
|
"sponsorships",
|
||||||
|
]:
|
||||||
if not collection in collections:
|
if not collection in collections:
|
||||||
db.create_collection(collection)
|
db.create_collection(collection)
|
||||||
|
|
||||||
|
col_tmp = db.get_collection("tmp")
|
||||||
|
col_bans = db.get_collection("bans")
|
||||||
col_users = db.get_collection("users")
|
col_users = db.get_collection("users")
|
||||||
col_context = db.get_collection("context")
|
col_context = db.get_collection("context")
|
||||||
|
col_youtube = db.get_collection("youtube")
|
||||||
|
col_spoilers = db.get_collection("spoilers")
|
||||||
col_messages = db.get_collection("messages")
|
col_messages = db.get_collection("messages")
|
||||||
col_warnings = db.get_collection("warnings")
|
col_warnings = db.get_collection("warnings")
|
||||||
col_applications = db.get_collection("applications")
|
col_applications = db.get_collection("applications")
|
||||||
col_sponsorships = db.get_collection("sponsorships")
|
col_sponsorships = db.get_collection("sponsorships")
|
||||||
|
|
||||||
|
col_applications.create_index([("application.3.location", GEOSPHERE)])
|
||||||
|
@@ -1,99 +1,288 @@
|
|||||||
from os import sep
|
from typing import Literal
|
||||||
from time import time
|
|
||||||
from dateutil.relativedelta import relativedelta
|
from dateutil.relativedelta import relativedelta
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from app import app
|
from app import app
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from pyrogram.types import ReplyKeyboardRemove, InlineKeyboardMarkup, InlineKeyboardButton
|
from pyrogram.types import (
|
||||||
|
ReplyKeyboardRemove,
|
||||||
|
InlineKeyboardMarkup,
|
||||||
|
InlineKeyboardButton,
|
||||||
|
ForceReply,
|
||||||
|
Message,
|
||||||
|
)
|
||||||
|
from pyrogram.client import Client
|
||||||
from pyrogram.enums.parse_mode import ParseMode
|
from pyrogram.enums.parse_mode import ParseMode
|
||||||
from modules.utils import configGet, configSet, jsonLoad, jsonSave, locale, logWrite
|
from classes.holo_user import HoloUser
|
||||||
|
from modules.utils import all_locales, configGet, locale, logWrite
|
||||||
from modules.handlers.welcome import welcome_pass
|
from modules.handlers.welcome import welcome_pass
|
||||||
|
from modules.database import col_tmp, col_applications
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
# Confirmation =================================================================================================================
|
|
||||||
@app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("confirm", "keyboard")[0][0])))
|
|
||||||
async def confirm_yes(app, msg):
|
|
||||||
|
|
||||||
user_stage = configGet("stage", file=str(msg.from_user.id))
|
confirmation_1 = []
|
||||||
|
for pattern in all_locales("confirm", "keyboard"):
|
||||||
|
confirmation_1.append(pattern[0][0])
|
||||||
|
|
||||||
if user_stage == 10:
|
|
||||||
|
|
||||||
if not configGet("sent", file=str(msg.from_user.id)):
|
@app.on_message(
|
||||||
|
(custom_filters.enabled_applications | custom_filters.enabled_sponsorships)
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.private
|
||||||
|
& filters.command(confirmation_1, prefixes=[""])
|
||||||
|
& ~custom_filters.banned
|
||||||
|
)
|
||||||
|
async def confirm_yes(
|
||||||
|
app: Client,
|
||||||
|
msg: Message,
|
||||||
|
kind: Literal["application", "sponsorship", "unknown"] = "unknown",
|
||||||
|
):
|
||||||
|
holo_user = HoloUser(msg.from_user)
|
||||||
|
|
||||||
await msg.reply_text(locale("application_sent", "message"), reply_markup=ReplyKeyboardRemove())
|
if configGet("enabled", "features", "applications") is True:
|
||||||
|
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"}
|
||||||
|
)
|
||||||
|
|
||||||
applications = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")
|
if tmp_application is None:
|
||||||
|
logWrite(f"Application of {holo_user.id} is nowhere to be found.")
|
||||||
|
return
|
||||||
|
|
||||||
applications[str(msg.from_user.id)] = {
|
if tmp_application["sent"] is True:
|
||||||
"approved": False,
|
return
|
||||||
"approved_by": None,
|
|
||||||
"approval_date": None,
|
|
||||||
"refused": False,
|
|
||||||
"refused_by": False,
|
|
||||||
"refusal_date": False,
|
|
||||||
"application_date": int(time()),
|
|
||||||
"application": configGet("application", file=str(msg.from_user.id))
|
|
||||||
}
|
|
||||||
|
|
||||||
jsonSave(applications, f"{configGet('data', 'locations')}{sep}applications.json")
|
await msg.reply_text(
|
||||||
|
locale("application_sent", "message"),
|
||||||
|
reply_markup=ReplyKeyboardRemove(),
|
||||||
|
)
|
||||||
|
|
||||||
application_content = []
|
application_content = []
|
||||||
i = 1
|
i = 1
|
||||||
|
|
||||||
for question in configGet("application", file=str(msg.from_user.id)):
|
for question in tmp_application["application"]:
|
||||||
if i == 2:
|
if i == 2:
|
||||||
age = relativedelta(datetime.now(), datetime.strptime(configGet('application', file=str(msg.from_user.id))['2'], '%d.%m.%Y'))
|
age = relativedelta(
|
||||||
application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {configGet('application', file=str(msg.from_user.id))['2']} ({age.years} р.)")
|
datetime.now(), tmp_application["application"]["2"]
|
||||||
|
)
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles')} {tmp_application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)"
|
||||||
|
)
|
||||||
|
elif i == 3:
|
||||||
|
if tmp_application["application"]["3"]["countryCode"] == "UA":
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles')} {tmp_application['application']['3']['name']}"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {configGet('application', file=str(msg.from_user.id))[question]}")
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles')} {tmp_application['application']['3']['name']} ({tmp_application['application']['3']['adminName1']}, {tmp_application['application']['3']['countryName']})"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles')} {tmp_application['application'][question]}"
|
||||||
|
)
|
||||||
|
|
||||||
i += 1
|
i += 1
|
||||||
|
|
||||||
if configGet("reapply", file=str(msg.from_user.id)):
|
if (
|
||||||
await app.send_message(chat_id=configGet("admin_group"), text=(locale("reapply_got", "message")).format(str(msg.from_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(
|
tmp_application["reapply"] is True
|
||||||
|
and col_applications.find_one({"user": holo_user.id}) is not None
|
||||||
|
):
|
||||||
|
await app.send_message(
|
||||||
|
chat_id=configGet("admin", "groups"),
|
||||||
|
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_{msg.from_user.id}")
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("reapply_yes", "button")),
|
||||||
|
callback_data=f"reapply_yes_{holo_user.id}",
|
||||||
|
)
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
InlineKeyboardButton(text=str(locale("reapply_no", "button")), callback_data=f"reapply_no_{msg.from_user.id}")
|
InlineKeyboardButton(
|
||||||
]
|
text=str(locale("reapply_no", "button")),
|
||||||
]
|
callback_data=f"reapply_no_{holo_user.id}",
|
||||||
)
|
)
|
||||||
|
],
|
||||||
|
]
|
||||||
|
),
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await app.send_message(chat_id=configGet("admin_group"), text=(locale("application_got", "message")).format(str(msg.from_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", "groups"),
|
||||||
|
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_{msg.from_user.id}")
|
InlineKeyboardButton(
|
||||||
],
|
text=str(locale("sub_yes", "button")),
|
||||||
[
|
callback_data=f"sub_yes_{holo_user.id}",
|
||||||
InlineKeyboardButton(text=str(locale("sub_no", "button")), callback_data=f"sub_no_{msg.from_user.id}")
|
|
||||||
],
|
|
||||||
[
|
|
||||||
InlineKeyboardButton(text=str(locale("sub_no_aggressive", "button")), callback_data=f"sub_no_aggresive_{msg.from_user.id}")
|
|
||||||
],
|
|
||||||
[
|
|
||||||
InlineKeyboardButton(text=str(locale("sub_no_russian", "button")), callback_data=f"sub_no_russian_{msg.from_user.id}")
|
|
||||||
]
|
|
||||||
]
|
|
||||||
)
|
)
|
||||||
|
],
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("sub_no", "button")),
|
||||||
|
callback_data=f"sub_no_{holo_user.id}",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("sub_russian", "button")),
|
||||||
|
callback_data=f"sub_russian_{holo_user.id}",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
]
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
logWrite(f"User {msg.from_user.id} sent his application and it will now be reviewed")
|
logWrite(
|
||||||
|
f"User {holo_user.id} sent his application and it will now be reviewed"
|
||||||
|
)
|
||||||
|
|
||||||
configSet(["sent"], True, file=str(msg.from_user.id))
|
col_tmp.update_one(
|
||||||
configSet(["confirmed"], True, file=str(msg.from_user.id))
|
{"user": holo_user.id, "type": "application"}, {"$set": {"sent": True}}
|
||||||
|
)
|
||||||
|
|
||||||
@app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("confirm", "keyboard")[1][0])))
|
return
|
||||||
async def confirm_no(app, msg):
|
|
||||||
|
|
||||||
user_stage = configGet("stage", file=str(msg.from_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)
|
||||||
|
):
|
||||||
|
tmp_sponsorship = col_tmp.find_one(
|
||||||
|
{"user": holo_user.id, "type": "sponsorship"}
|
||||||
|
)
|
||||||
|
|
||||||
if user_stage == 10:
|
if tmp_sponsorship is None:
|
||||||
jsonSave(jsonLoad(f"{configGet('data', 'locations')}{sep}user_default.json"), f"{configGet('data', 'locations')}{sep}users{sep}{msg.from_user.id}.json")
|
logWrite(f"Sponsorship of {holo_user.id} is nowhere to be found.")
|
||||||
configSet(["telegram_id"], str(msg.from_user.username), file=str(msg.from_user.id))
|
return
|
||||||
configSet(["telegram_name"], f"{msg.from_user.first_name} {msg.from_user.last_name}", file=str(msg.from_user.id))
|
|
||||||
configSet(["telegram_phone"], str(msg.from_user.phone_number), file=str(msg.from_user.id))
|
if tmp_sponsorship["sent"] is True:
|
||||||
configSet(["telegram_locale"], str(msg.from_user.language_code), file=str(msg.from_user.id))
|
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":
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
sponsorship_content.append(
|
||||||
|
f"{locale(f'question_{question}', 'message', 'sponsor_titles')} {tmp_sponsorship['sponsorship'][question]}"
|
||||||
|
)
|
||||||
|
|
||||||
|
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}",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
[
|
||||||
|
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(
|
||||||
|
(custom_filters.enabled_applications | custom_filters.enabled_sponsorships)
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.private
|
||||||
|
& filters.command(confirmation_2, prefixes=[""])
|
||||||
|
& ~custom_filters.banned
|
||||||
|
)
|
||||||
|
async def confirm_no(
|
||||||
|
app: Client,
|
||||||
|
msg: Message,
|
||||||
|
kind: Literal["application", "sponsorship", "unknown"] = "unknown",
|
||||||
|
):
|
||||||
|
holo_user = HoloUser(msg.from_user)
|
||||||
|
|
||||||
|
if configGet("enabled", "features", "applications") 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)
|
await welcome_pass(app, msg, once_again=True)
|
||||||
logWrite(f"User {msg.from_user.id} restarted the application due to typo in it")
|
logWrite(
|
||||||
# ==============================================================================================================================
|
f"User {msg.from_user.id} restarted the application due to typo in it"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
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)
|
||||||
|
):
|
||||||
|
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
|
||||||
|
@@ -1,47 +1,83 @@
|
|||||||
from os import sep, path
|
|
||||||
from dateutil.relativedelta import relativedelta
|
from dateutil.relativedelta import relativedelta
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from app import app, isAnAdmin
|
from app import app
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from modules.utils import configGet, jsonLoad, locale, logWrite
|
from pyrogram.types import Message
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from modules.utils import locale, logWrite
|
||||||
|
from modules.database import col_applications
|
||||||
|
from classes.holo_user import HoloUser
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
custom_filters.enabled_applications
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.contact
|
||||||
|
& filters.private
|
||||||
|
& (custom_filters.allowed | custom_filters.admin)
|
||||||
|
& ~custom_filters.banned
|
||||||
|
)
|
||||||
|
async def get_contact(app: Client, msg: Message):
|
||||||
|
holo_user = HoloUser(msg.from_user)
|
||||||
|
|
||||||
# Contact getting ==============================================================================================================
|
|
||||||
@app.on_message(~ filters.scheduled & filters.contact & filters.private)
|
|
||||||
async def get_contact(app, msg):
|
|
||||||
if (path.exists(f"{configGet('data', 'locations')}{sep}users{sep}{msg.from_user.id}.json") and jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{msg.from_user.id}.json")["approved"]) or (await isAnAdmin(msg.from_user.id)):
|
|
||||||
if msg.contact.user_id != None:
|
if msg.contact.user_id != None:
|
||||||
try:
|
application = col_applications.find_one({"user": msg.contact.user_id})
|
||||||
user_data = jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{msg.contact.user_id}.json")
|
|
||||||
application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")[str(msg.contact.user_id)]
|
if application is None:
|
||||||
|
logWrite(
|
||||||
|
f"User {holo_user.id} requested application of {msg.contact.user_id} but user does not exists"
|
||||||
|
)
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("contact_invalid", "message", locale=holo_user.locale)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
application_content = []
|
application_content = []
|
||||||
i = 1
|
i = 1
|
||||||
|
|
||||||
for question in application["application"]:
|
for question in application["application"]:
|
||||||
if i == 2:
|
if i == 2:
|
||||||
age = relativedelta(datetime.now(), datetime.strptime(application['application']['2'], '%d.%m.%Y'))
|
age = relativedelta(datetime.now(), application["application"]["2"])
|
||||||
application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {application['application']['2']} ({age.years} р.)")
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)"
|
||||||
|
)
|
||||||
|
elif i == 3:
|
||||||
|
if application["application"]["3"]["countryCode"] == "UA":
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application']['3']['name']}"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {application['application'][question]}")
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application'][question]}"
|
||||||
|
)
|
||||||
|
|
||||||
i += 1
|
i += 1
|
||||||
if user_data["sent"]:
|
|
||||||
if user_data["approved"]:
|
application_status = locale(
|
||||||
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"))
|
"application_status_accepted", "message", locale=holo_user.locale
|
||||||
elif application["refused"]:
|
).format(
|
||||||
application_status = locale("application_status_refused", "message").format((await app.get_users(application["refused_by"])).first_name, datetime.fromtimestamp(application["refusal_date"]).strftime("%d.%m.%Y, %H:%M"))
|
(await app.get_users(application["admin"])).first_name,
|
||||||
|
application["date"].strftime("%d.%m.%Y, %H:%M"),
|
||||||
|
)
|
||||||
|
|
||||||
|
logWrite(f"User {holo_user.id} requested application of {msg.contact.user_id}")
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("contact", "message", locale=holo_user.locale).format(
|
||||||
|
str(msg.contact.user_id),
|
||||||
|
"\n".join(application_content),
|
||||||
|
application_status,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
application_status = locale("application_status_on_hold", "message")
|
logWrite(
|
||||||
else:
|
f"User {holo_user.id} requested application of someone but user is not telegram user"
|
||||||
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"))
|
await msg.reply_text(
|
||||||
elif application["refused"]:
|
locale("contact_not_member", "message", locale=holo_user.locale)
|
||||||
application_status = locale("application_status_refused", "message").format((await app.get_users(application["refused_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 {msg.contact.user_id}")
|
|
||||||
await msg.reply_text(locale("contact", "message").format(str(msg.contact.user_id), "\n".join(application_content), application_status))
|
|
||||||
except FileNotFoundError:
|
|
||||||
logWrite(f"User {msg.from_user.id} requested application of {msg.contact.user_id} but user does not exists")
|
|
||||||
await msg.reply_text(locale("contact_invalid", "message"))
|
|
||||||
else:
|
|
||||||
logWrite(f"User {msg.from_user.id} requested application of someone but user is not telegram user")
|
|
||||||
await msg.reply_text(locale("contact_not_member", "message"))
|
|
||||||
# ==============================================================================================================================
|
|
||||||
|
@@ -1,121 +1,393 @@
|
|||||||
from datetime import datetime
|
from traceback import print_exc
|
||||||
from os import sep
|
|
||||||
from app import app, isAnAdmin
|
from app import app, isAnAdmin
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from ftfy import fix_text
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from pyrogram.types import ForceReply, ReplyKeyboardMarkup, Message
|
from pyrogram.types import (
|
||||||
|
Message,
|
||||||
|
ForceReply,
|
||||||
|
InlineKeyboardMarkup,
|
||||||
|
InlineKeyboardButton,
|
||||||
|
ReplyKeyboardRemove,
|
||||||
|
)
|
||||||
|
from pyrogram.client import Client
|
||||||
from classes.holo_user import HoloUser
|
from classes.holo_user import HoloUser
|
||||||
from modules.utils import configGet, configSet, jsonLoad, jsonSave, locale, logWrite, should_quote
|
from modules.utils import configGet, logWrite, locale, all_locales
|
||||||
from modules.database import col_messages
|
from modules.database import col_messages, col_spoilers
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
|
|
||||||
async def message_involved(msg: Message) -> bool:
|
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})
|
message = col_messages.find_one(
|
||||||
|
{
|
||||||
|
"destination.id": msg.reply_to_message.id,
|
||||||
|
"destination.chat": msg.reply_to_message.chat.id,
|
||||||
|
}
|
||||||
|
)
|
||||||
if message is not None:
|
if message is not None:
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
async def message_context(msg: Message) -> tuple:
|
async def message_context(msg: Message) -> tuple:
|
||||||
message = col_messages.find_one({"destination.id": msg.reply_to_message.id, "destination.chat": msg.reply_to_message.chat.id})
|
message = col_messages.find_one(
|
||||||
|
{
|
||||||
|
"destination.id": msg.reply_to_message.id,
|
||||||
|
"destination.chat": msg.reply_to_message.chat.id,
|
||||||
|
}
|
||||||
|
)
|
||||||
if message is not None:
|
if message is not None:
|
||||||
return message["origin"]["chat"], message["origin"]["id"]
|
return message["origin"]["chat"], message["origin"]["id"]
|
||||||
return 0, 0
|
return 0, 0
|
||||||
|
|
||||||
# Any other input ==============================================================================================================
|
|
||||||
@app.on_message(~ filters.scheduled & filters.private)
|
|
||||||
async def any_stage(app, msg):
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
~filters.scheduled
|
||||||
|
& (filters.private | filters.chat(configGet("admin", "groups")))
|
||||||
|
& ~custom_filters.banned
|
||||||
|
)
|
||||||
|
async def any_stage(app: Client, msg: Message):
|
||||||
if msg.via_bot is None:
|
if msg.via_bot is None:
|
||||||
|
holo_user = HoloUser(msg.from_user)
|
||||||
|
|
||||||
if (msg.reply_to_message != None) and (await message_involved(msg)):
|
if (msg.reply_to_message is not None) and (await message_involved(msg)):
|
||||||
|
|
||||||
context = await message_context(msg)
|
context = await message_context(msg)
|
||||||
context_message = await app.get_messages(context[0], context[1])
|
context_message = await app.get_messages(context[0], context[1])
|
||||||
|
|
||||||
holo_user = HoloUser(msg.from_user)
|
|
||||||
destination_user = HoloUser(context_message.from_user)
|
destination_user = HoloUser(context_message.from_user)
|
||||||
|
|
||||||
|
if destination_user is None:
|
||||||
|
return
|
||||||
|
|
||||||
await destination_user.message(
|
await destination_user.message(
|
||||||
origin=context_message,
|
origin=context_message,
|
||||||
context=msg,
|
context=msg,
|
||||||
text=msg.text,
|
text=str(msg.text),
|
||||||
caption=msg.caption,
|
caption=msg.caption,
|
||||||
photo=msg.photo,
|
photo=msg.photo,
|
||||||
video=msg.video,
|
video=msg.video,
|
||||||
file=msg.document,
|
file=msg.document,
|
||||||
|
animation=msg.animation,
|
||||||
|
voice=msg.voice,
|
||||||
adm_origin=await isAnAdmin(context_message.from_user.id),
|
adm_origin=await isAnAdmin(context_message.from_user.id),
|
||||||
adm_context=await isAnAdmin(msg.from_user.id)
|
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
|
return
|
||||||
|
|
||||||
# user_stage = configGet("stage", file=str(msg.from_user.id))
|
if msg.chat.id == configGet("admin", "groups"):
|
||||||
|
return
|
||||||
|
|
||||||
# if user_stage == 1:
|
if msg.text is not None:
|
||||||
# await msg.reply_text(locale(f"question{user_stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage+1}", "force_reply"))))
|
if configGet("enabled", "features", "applications") is True:
|
||||||
# logWrite(f"User {msg.from_user.id} completed stage {user_stage} of application")
|
await holo_user.application_next(str(msg.text), msg=msg)
|
||||||
# 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:
|
if configGet("enabled", "features", "sponsorships") is True:
|
||||||
|
await holo_user.sponsorship_next(str(msg.text), msg)
|
||||||
|
|
||||||
# try:
|
if msg.photo is not None:
|
||||||
|
await holo_user.sponsorship_next(str(msg.text), msg=msg, photo=msg.photo)
|
||||||
|
|
||||||
# configSet(["application", str(user_stage)], str(msg.text), file=str(msg.from_user.id))
|
if (
|
||||||
|
holo_user.application_state()[0] != "fill"
|
||||||
|
and holo_user.sponsorship_state()[0] != "fill"
|
||||||
|
):
|
||||||
|
if configGet("enabled", "features", "spoilers") is False:
|
||||||
|
return
|
||||||
|
|
||||||
# input_dt = datetime.strptime(msg.text, "%d.%m.%Y")
|
spoiler = col_spoilers.find_one(
|
||||||
|
{"user": msg.from_user.id, "completed": False}
|
||||||
|
)
|
||||||
|
|
||||||
# if datetime.now() <= input_dt:
|
if spoiler is None:
|
||||||
# logWrite(f"User {msg.from_user.id} failed stage {user_stage} due to joking")
|
return
|
||||||
# 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):
|
if spoiler["category"] is None:
|
||||||
# logWrite(f"User {msg.from_user.id} failed stage {user_stage} due to being underage")
|
found = False
|
||||||
# await msg.reply_text(locale("question2_underage", "message").format(str(configGet("age_allowed"))), reply_markup=ForceReply(placeholder=str(locale("question2", "force_reply"))))
|
|
||||||
|
|
||||||
# else:
|
# Find category in all locales
|
||||||
# logWrite(f"User {msg.from_user.id} completed stage {user_stage} of application")
|
for lc in all_locales("spoiler_categories", "message"):
|
||||||
# await msg.reply_text(locale(f"question{user_stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage+1}", "force_reply"))))
|
for key in lc:
|
||||||
# configSet(["stage"], user_stage+1, file=str(msg.from_user.id))
|
if lc[key] == str(msg.text):
|
||||||
|
found = True
|
||||||
|
category = key
|
||||||
|
|
||||||
# except ValueError:
|
if found is False:
|
||||||
# logWrite(f"User {msg.from_user.id} failed stage {user_stage} due to sending invalid date format")
|
await msg.reply_text(
|
||||||
# await msg.reply_text(locale(f"question2_invalid", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage}", "force_reply"))))
|
locale(
|
||||||
|
"spoiler_incorrect_category",
|
||||||
|
"message",
|
||||||
|
locale=msg.from_user,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
# else:
|
col_spoilers.find_one_and_update(
|
||||||
# if user_stage <= 9:
|
{"_id": spoiler["_id"]}, {"$set": {"category": category}}
|
||||||
# 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"))))
|
await msg.reply_text(
|
||||||
# configSet(["application", str(user_stage)], str(msg.text), file=str(msg.from_user.id))
|
locale("spoiler_send_description", "message", locale=msg.from_user),
|
||||||
# configSet(["stage"], user_stage+1, file=str(msg.from_user.id))
|
reply_markup=ForceReply(
|
||||||
# else:
|
placeholder=locale(
|
||||||
# if not configGet("sent", file=str(msg.from_user.id)):
|
"spoiler_description", "force_reply", locale=msg.from_user
|
||||||
# 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
|
return
|
||||||
# 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("refused", 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("refused", file=str(msg.from_user.id)):
|
|
||||||
# await msg.reply_text(locale("already_sent", "message"))
|
|
||||||
|
|
||||||
@app.on_message(~ filters.scheduled & filters.group)
|
if spoiler["description"] is None and (
|
||||||
async def message_in_group(app, msg):
|
spoiler["photo"] is None
|
||||||
|
and spoiler["video"] is None
|
||||||
|
and spoiler["audio"] is None
|
||||||
|
and spoiler["animation"] is None
|
||||||
|
and spoiler["text"] is None
|
||||||
|
):
|
||||||
|
# for lc in all_locales("spoiler_description", "keyboard"):
|
||||||
|
# if msg.text == lc[-1][0]:
|
||||||
|
# await msg.reply_text(locale("spoiler_description_enter", "message", locale=msg.from_user), reply_markup=ForceReply(placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user)))
|
||||||
|
# return
|
||||||
|
|
||||||
|
msg.text = fix_text(str(msg.text))
|
||||||
|
if len(str(msg.text)) > 1024:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale(
|
||||||
|
"spoiler_description_too_long",
|
||||||
|
"message",
|
||||||
|
locale=msg.from_user,
|
||||||
|
),
|
||||||
|
reply_markup=ForceReply(
|
||||||
|
placeholder=locale(
|
||||||
|
"spoiler_description",
|
||||||
|
"force_reply",
|
||||||
|
locale=msg.from_user,
|
||||||
|
)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
col_spoilers.find_one_and_update(
|
||||||
|
{"user": msg.from_user.id, "completed": False},
|
||||||
|
{"$set": {"description": msg.text}},
|
||||||
|
)
|
||||||
|
|
||||||
|
logWrite(
|
||||||
|
f"Adding description '{str(msg.text)}' to {msg.from_user.id}'s spoiler"
|
||||||
|
)
|
||||||
|
await msg.reply_text(
|
||||||
|
locale(
|
||||||
|
"spoiler_using_description", "message", locale=msg.from_user
|
||||||
|
).format(msg.text),
|
||||||
|
reply_markup=ForceReply(
|
||||||
|
placeholder=locale(
|
||||||
|
"spoiler_content", "force_reply", locale=msg.from_user
|
||||||
|
)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
|
ready = False
|
||||||
|
|
||||||
|
if msg.photo is not None:
|
||||||
|
col_spoilers.find_one_and_update(
|
||||||
|
{"user": msg.from_user.id, "completed": False},
|
||||||
|
{
|
||||||
|
"$set": {
|
||||||
|
"photo": msg.photo.file_id,
|
||||||
|
"caption": msg.caption,
|
||||||
|
"completed": True,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
logWrite(
|
||||||
|
f"Adding photo with id {msg.photo.file_id} to {msg.from_user.id}'s spoiler"
|
||||||
|
)
|
||||||
|
ready = True
|
||||||
|
|
||||||
|
if msg.video is not None:
|
||||||
|
col_spoilers.find_one_and_update(
|
||||||
|
{"user": msg.from_user.id, "completed": False},
|
||||||
|
{
|
||||||
|
"$set": {
|
||||||
|
"video": msg.video.file_id,
|
||||||
|
"caption": msg.caption,
|
||||||
|
"completed": True,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
logWrite(
|
||||||
|
f"Adding audio with id {msg.video.file_id} to {msg.from_user.id}'s spoiler"
|
||||||
|
)
|
||||||
|
ready = True
|
||||||
|
|
||||||
|
if msg.audio is not None:
|
||||||
|
col_spoilers.find_one_and_update(
|
||||||
|
{"user": msg.from_user.id, "completed": False},
|
||||||
|
{
|
||||||
|
"$set": {
|
||||||
|
"audio": msg.audio.file_id,
|
||||||
|
"caption": msg.caption,
|
||||||
|
"completed": True,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
logWrite(
|
||||||
|
f"Adding video with id {msg.audio.file_id} to {msg.from_user.id}'s spoiler"
|
||||||
|
)
|
||||||
|
ready = True
|
||||||
|
|
||||||
|
if msg.animation is not None:
|
||||||
|
col_spoilers.find_one_and_update(
|
||||||
|
{"user": msg.from_user.id, "completed": False},
|
||||||
|
{
|
||||||
|
"$set": {
|
||||||
|
"animation": msg.animation.file_id,
|
||||||
|
"caption": msg.caption,
|
||||||
|
"completed": True,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
logWrite(
|
||||||
|
f"Adding animation with id {msg.animation.file_id} to {msg.from_user.id}'s spoiler"
|
||||||
|
)
|
||||||
|
ready = True
|
||||||
|
|
||||||
|
if msg.document is not None:
|
||||||
|
col_spoilers.find_one_and_update(
|
||||||
|
{"user": msg.from_user.id, "completed": False},
|
||||||
|
{
|
||||||
|
"$set": {
|
||||||
|
"document": msg.document.file_id,
|
||||||
|
"caption": msg.caption,
|
||||||
|
"completed": True,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
logWrite(
|
||||||
|
f"Adding document with id {msg.document.file_id} to {msg.from_user.id}'s spoiler"
|
||||||
|
)
|
||||||
|
ready = True
|
||||||
|
|
||||||
|
if (
|
||||||
|
spoiler["photo"] is None
|
||||||
|
and spoiler["video"] is None
|
||||||
|
and spoiler["audio"] is None
|
||||||
|
and spoiler["animation"] is None
|
||||||
|
and spoiler["document"] is None
|
||||||
|
and spoiler["text"] is None
|
||||||
|
):
|
||||||
|
if msg.text is not None:
|
||||||
|
col_spoilers.find_one_and_update(
|
||||||
|
{"user": msg.from_user.id, "completed": False},
|
||||||
|
{"$set": {"text": str(msg.text), "completed": True}},
|
||||||
|
)
|
||||||
|
logWrite(
|
||||||
|
f"Adding text '{str(msg.text)}' to {msg.from_user.id}'s spoiler"
|
||||||
|
)
|
||||||
|
ready = True
|
||||||
|
|
||||||
|
if ready is True:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("spoiler_ready", "message", locale=msg.from_user),
|
||||||
|
reply_markup=ReplyKeyboardRemove(),
|
||||||
|
)
|
||||||
|
if configGet("allow_external", "features", "spoilers") is True:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("spoiler_send", "message", locale=msg.from_user),
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
|
[
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale(
|
||||||
|
"spoiler_preview",
|
||||||
|
"button",
|
||||||
|
locale=msg.from_user,
|
||||||
|
),
|
||||||
|
callback_data=f"sid_{spoiler['_id'].__str__()}",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale(
|
||||||
|
"spoiler_send_chat",
|
||||||
|
"button",
|
||||||
|
locale=msg.from_user,
|
||||||
|
),
|
||||||
|
callback_data=f"shc_{spoiler['_id'].__str__()}",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale(
|
||||||
|
"spoiler_send_other",
|
||||||
|
"button",
|
||||||
|
locale=msg.from_user,
|
||||||
|
),
|
||||||
|
switch_inline_query=f"spoiler:{spoiler['_id'].__str__()}",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("spoiler_send", "message", locale=msg.from_user),
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
|
[
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale(
|
||||||
|
"spoiler_preview",
|
||||||
|
"button",
|
||||||
|
locale=msg.from_user,
|
||||||
|
),
|
||||||
|
callback_data=f"sid_{spoiler['_id'].__str__()}",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale(
|
||||||
|
"spoiler_send_chat",
|
||||||
|
"button",
|
||||||
|
locale=msg.from_user,
|
||||||
|
),
|
||||||
|
callback_data=f"shc_{spoiler['_id'].__str__()}",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("spoiler_incorrect_content", "message", locale=msg.from_user)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_message(~filters.scheduled & filters.group)
|
||||||
|
async def message_in_group(app: Client, msg: Message):
|
||||||
if (msg.chat is not None) and (msg.via_bot is not None):
|
if (msg.chat is not None) and (msg.via_bot is not None):
|
||||||
if (msg.via_bot.id == configGet("bot_id")) and (msg.chat.id == configGet("destination_group")):
|
if (msg.via_bot.id == (await app.get_me()).id) and (
|
||||||
|
msg.chat.id == configGet("users", "groups")
|
||||||
|
):
|
||||||
|
if str(msg.text).startswith(
|
||||||
|
locale("spoiler_described", "message").split()[0]
|
||||||
|
):
|
||||||
|
logWrite(f"User {msg.from_user.id} sent spoiler to user's group")
|
||||||
|
try:
|
||||||
|
logWrite("Forwarding spoiler to admin's group")
|
||||||
|
await msg.copy(
|
||||||
|
configGet("admin", "groups"), disable_notification=True
|
||||||
|
)
|
||||||
|
except Exception as exp:
|
||||||
|
logWrite(
|
||||||
|
f"Could not forward spoiler to admin's group due to '{exp}': {print_exc()}"
|
||||||
|
)
|
||||||
|
return
|
||||||
if configGet("remove_application_time") > 0:
|
if configGet("remove_application_time") > 0:
|
||||||
logWrite(f"User {msg.from_user.id} requested application in destination group, removing in {configGet('remove_application_time')} minutes")
|
logWrite(
|
||||||
await asyncio.sleep(configGet("remove_application_time")*60)
|
f"User {msg.from_user.id} requested application in destination group, removing in {configGet('remove_application_time')} minutes"
|
||||||
|
)
|
||||||
|
await asyncio.sleep(configGet("remove_application_time") * 60)
|
||||||
await msg.delete()
|
await msg.delete()
|
||||||
logWrite(f"Removed application requested by {msg.from_user.id} in destination group")
|
logWrite(
|
||||||
# ==============================================================================================================================
|
f"Removed application requested by {msg.from_user.id} in destination group"
|
||||||
|
)
|
||||||
|
@@ -1,33 +1,151 @@
|
|||||||
from os import sep, path
|
from datetime import datetime
|
||||||
from app import app, isAnAdmin
|
from app import app, isAnAdmin
|
||||||
from pyrogram.types import ChatPermissions, InlineKeyboardMarkup, InlineKeyboardButton
|
from pyrogram.types import (
|
||||||
from modules.utils import configGet, jsonLoad, locale
|
ChatPermissions,
|
||||||
|
InlineKeyboardMarkup,
|
||||||
|
InlineKeyboardButton,
|
||||||
|
ChatMemberUpdated,
|
||||||
|
)
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from modules.utils import configGet, locale
|
||||||
|
from modules import custom_filters
|
||||||
|
from modules.logging import logWrite
|
||||||
|
from modules.database import col_applications
|
||||||
|
from classes.holo_user import HoloUser
|
||||||
|
from dateutil.relativedelta import relativedelta
|
||||||
|
|
||||||
# Filter users on join =========================================================================================================
|
|
||||||
@app.on_chat_member_updated(group=configGet("destination_group"))
|
@app.on_chat_member_updated(
|
||||||
#@app.on_message(filters.new_chat_members, group=configGet("destination_group"))
|
custom_filters.enabled_invites_check, group=configGet("users", "groups")
|
||||||
async def filter_join(app, member):
|
)
|
||||||
|
# @app.on_message(filters.new_chat_members, group=configGet("users", "groups"))
|
||||||
|
async def filter_join(app: Client, member: ChatMemberUpdated):
|
||||||
if member.invite_link != None:
|
if member.invite_link != None:
|
||||||
if (path.exists(f"{configGet('data', 'locations')}{sep}users{sep}{member.from_user.id}.json") and jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{member.from_user.id}.json")["approved"]) or (await isAnAdmin(member.from_user.id)):
|
holo_user = HoloUser(member.from_user)
|
||||||
if configGet("link", file=str(member.from_user.id)) == member.invite_link.invite_link:
|
|
||||||
|
if (holo_user.link is not None) and (
|
||||||
|
holo_user.link == member.invite_link.invite_link
|
||||||
|
):
|
||||||
|
logWrite(
|
||||||
|
f"User {holo_user.id} joined destination group with correct link {holo_user.link}"
|
||||||
|
)
|
||||||
|
|
||||||
|
application = col_applications.find_one({"user": holo_user.id})
|
||||||
|
application_content = []
|
||||||
|
i = 1
|
||||||
|
|
||||||
|
for question in application["application"]:
|
||||||
|
if i == 2:
|
||||||
|
age = relativedelta(datetime.now(), application["application"]["2"])
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)"
|
||||||
|
)
|
||||||
|
elif i == 3:
|
||||||
|
if application["application"]["3"]["countryCode"] == "UA":
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles')} {application['application'][question]}"
|
||||||
|
)
|
||||||
|
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
await app.send_message(
|
||||||
|
configGet("users", "groups"),
|
||||||
|
locale("joined_application", "message").format(
|
||||||
|
member.from_user.first_name,
|
||||||
|
member.from_user.username,
|
||||||
|
"\n".join(application_content),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
return
|
return
|
||||||
|
|
||||||
if await isAnAdmin(member.invite_link.creator.id):
|
if await isAnAdmin(member.invite_link.creator.id):
|
||||||
|
logWrite(
|
||||||
|
f"User {holo_user.id} joined destination group with link {holo_user.link} of an admin {member.invite_link.creator.id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
application = col_applications.find_one({"user": holo_user.id})
|
||||||
|
|
||||||
|
if application is None:
|
||||||
return
|
return
|
||||||
await app.send_message(configGet("admin_group"), f"User **{member.from_user.first_name}** (`{member.from_user.id}`) joined the chat not with his personal link", reply_markup=InlineKeyboardMarkup(
|
|
||||||
|
application_content = []
|
||||||
|
i = 1
|
||||||
|
|
||||||
|
for question in application["application"]:
|
||||||
|
if i == 2:
|
||||||
|
age = relativedelta(datetime.now(), application["application"]["2"])
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)"
|
||||||
|
)
|
||||||
|
elif i == 3:
|
||||||
|
if application["application"]["3"]["countryCode"] == "UA":
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles')} {application['application'][question]}"
|
||||||
|
)
|
||||||
|
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
await app.send_message(
|
||||||
|
configGet("users", "groups"),
|
||||||
|
locale("joined_application", "message").format(
|
||||||
|
member.from_user.first_name,
|
||||||
|
member.from_user.username,
|
||||||
|
"\n".join(application_content),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
|
logWrite(
|
||||||
|
f"User {holo_user.id} joined destination group with stolen/unapproved link {holo_user.link}"
|
||||||
|
)
|
||||||
|
|
||||||
|
await app.send_message(
|
||||||
|
configGet("admin", "groups"),
|
||||||
|
locale("joined_false_link", "message").format(
|
||||||
|
member.from_user.first_name, member.from_user.id
|
||||||
|
),
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
[
|
[
|
||||||
[
|
[
|
||||||
InlineKeyboardButton(text=str(locale("sus_allow", "button")), callback_data=f"sus_allow_{member.from_user.id}")
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("sus_allow", "button")),
|
||||||
|
callback_data=f"sus_allow_{member.from_user.id}",
|
||||||
|
)
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
InlineKeyboardButton(text=str(locale("sus_refuse", "button")), callback_data=f"sus_refuse_{member.from_user.id}")
|
InlineKeyboardButton(
|
||||||
|
text=str(locale("sus_reject", "button")),
|
||||||
|
callback_data=f"sus_reject_{member.from_user.id}",
|
||||||
|
)
|
||||||
|
],
|
||||||
]
|
]
|
||||||
]
|
),
|
||||||
))
|
)
|
||||||
await app.restrict_chat_member(member.chat.id, member.from_user.id, permissions=ChatPermissions(
|
await app.restrict_chat_member(
|
||||||
|
member.chat.id,
|
||||||
|
member.from_user.id,
|
||||||
|
permissions=ChatPermissions(
|
||||||
can_send_messages=False,
|
can_send_messages=False,
|
||||||
can_send_media_messages=False,
|
can_send_media_messages=False,
|
||||||
can_send_other_messages=False,
|
can_send_other_messages=False,
|
||||||
can_send_polls=False
|
can_send_polls=False,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
)
|
|
||||||
# ==============================================================================================================================
|
|
@@ -1 +0,0 @@
|
|||||||
from app import app
|
|
19
modules/handlers/voice.py
Normal file
19
modules/handlers/voice.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from random import choice
|
||||||
|
from app import app
|
||||||
|
from pyrogram import filters
|
||||||
|
from pyrogram.types import Message
|
||||||
|
from pyrogram.client import Client
|
||||||
|
from modules.logging import logWrite
|
||||||
|
from modules.utils import configGet, locale
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
custom_filters.enabled_dinovoice
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.voice
|
||||||
|
& filters.chat(configGet("users", "groups"))
|
||||||
|
)
|
||||||
|
async def voice_message(app: Client, msg: Message):
|
||||||
|
logWrite(f"User {msg.from_user.id} sent voice message in destination group")
|
||||||
|
await msg.reply_text(choice(locale("voice_message", "message")))
|
@@ -1,12 +1,26 @@
|
|||||||
from app import app
|
from app import app
|
||||||
from pyrogram import filters
|
from pyrogram import filters
|
||||||
from pyrogram.types import ForceReply, ReplyKeyboardMarkup
|
from pyrogram.types import ForceReply, ReplyKeyboardMarkup, Message
|
||||||
|
from pyrogram.client import Client
|
||||||
from classes.holo_user import HoloUser
|
from classes.holo_user import HoloUser
|
||||||
from modules.utils import configGet, configSet, locale, logWrite
|
from modules.utils import all_locales, locale, logWrite
|
||||||
|
from modules import custom_filters
|
||||||
|
|
||||||
# Welcome check ================================================================================================================
|
welcome_1 = []
|
||||||
@app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("welcome", "keyboard")[0][0]) | filters.regex(locale("return", "keyboard")[0][0])))
|
for pattern in all_locales("welcome", "keyboard"):
|
||||||
async def welcome_pass(app, msg, once_again: bool = True) -> None:
|
welcome_1.append(pattern[0][0])
|
||||||
|
for pattern in all_locales("return", "keyboard"):
|
||||||
|
welcome_1.append(pattern[0][0])
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
custom_filters.enabled_applications
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.private
|
||||||
|
& filters.command(welcome_1, prefixes=[""])
|
||||||
|
& ~custom_filters.banned
|
||||||
|
)
|
||||||
|
async def welcome_pass(app: Client, msg: Message, once_again: bool = False) -> None:
|
||||||
"""Set user's stage to 1 and start a fresh application
|
"""Set user's stage to 1 and start a fresh application
|
||||||
|
|
||||||
### Args:
|
### Args:
|
||||||
@@ -15,19 +29,45 @@ async def welcome_pass(app, msg, once_again: bool = True) -> None:
|
|||||||
* once_again (bool, optional): Set to False if it's the first time as user applies. Defaults to True.
|
* once_again (bool, optional): Set to False if it's the first time as user applies. Defaults to True.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
holo_user = HoloUser(msg.from_user)
|
|
||||||
|
|
||||||
if not once_again:
|
if not once_again:
|
||||||
await msg.reply_text(locale("privacy_notice", "message"))
|
await msg.reply_text(locale("privacy_notice", "message"))
|
||||||
|
|
||||||
|
holo_user = HoloUser(msg.from_user)
|
||||||
|
|
||||||
|
if once_again is False:
|
||||||
|
holo_user.application_restart()
|
||||||
|
|
||||||
|
if once_again is True:
|
||||||
logWrite(f"User {msg.from_user.id} confirmed starting the application")
|
logWrite(f"User {msg.from_user.id} confirmed starting the application")
|
||||||
await msg.reply_text(locale("question1", "message"), reply_markup=ForceReply(placeholder=locale("question1", "force_reply")))
|
else:
|
||||||
configSet(["stage"], 1, file=str(msg.from_user.id))
|
logWrite(
|
||||||
configSet(["sent"], False, file=str(msg.from_user.id))
|
f"User {msg.from_user.id} confirmed starting the application once again"
|
||||||
|
)
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("question1", "message", locale=msg.from_user),
|
||||||
|
reply_markup=ForceReply(
|
||||||
|
placeholder=locale("question1", "force_reply", locale=msg.from_user)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
@app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("welcome", "keyboard")[1][0])))
|
|
||||||
async def welcome_reject(app, msg):
|
|
||||||
|
|
||||||
logWrite(f"User {msg.from_user.id} refused to start the application")
|
welcome_2 = []
|
||||||
await msg.reply_text(locale("goodbye", "message"), reply_markup=ReplyKeyboardMarkup(locale("return", "keyboard"), resize_keyboard=True))
|
for pattern in all_locales("welcome", "keyboard"):
|
||||||
# ==============================================================================================================================
|
welcome_2.append(pattern[1][0])
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_message(
|
||||||
|
custom_filters.enabled_applications
|
||||||
|
& ~filters.scheduled
|
||||||
|
& filters.private
|
||||||
|
& filters.command(welcome_2, prefixes=[""])
|
||||||
|
& ~custom_filters.banned
|
||||||
|
)
|
||||||
|
async def welcome_reject(app: Client, msg: Message):
|
||||||
|
logWrite(f"User {msg.from_user.id} rejected to start the application")
|
||||||
|
await msg.reply_text(
|
||||||
|
locale("goodbye", "message", locale=msg.from_user),
|
||||||
|
reply_markup=ReplyKeyboardMarkup(
|
||||||
|
locale("return", "keyboard", locale=msg.from_user), resize_keyboard=True
|
||||||
|
),
|
||||||
|
)
|
||||||
|
@@ -1,72 +1,236 @@
|
|||||||
|
"""Module responsible for providing answers to
|
||||||
|
all inline queries that bot receives"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from os import path, sep
|
from os import path, sep
|
||||||
from pyrogram.types import InlineQueryResultArticle, InputTextMessageContent
|
from app import app, isAnAdmin
|
||||||
|
from pyrogram.types import (
|
||||||
|
InlineQueryResultArticle,
|
||||||
|
InputTextMessageContent,
|
||||||
|
InlineQuery,
|
||||||
|
InlineKeyboardMarkup,
|
||||||
|
InlineKeyboardButton,
|
||||||
|
)
|
||||||
|
from pyrogram.client import Client
|
||||||
from pyrogram.enums.chat_type import ChatType
|
from pyrogram.enums.chat_type import ChatType
|
||||||
from pyrogram.enums.chat_members_filter import ChatMembersFilter
|
from pyrogram.enums.chat_members_filter import ChatMembersFilter
|
||||||
from dateutil.relativedelta import relativedelta
|
from dateutil.relativedelta import relativedelta
|
||||||
|
from classes.errors.holo_user import UserNotFoundError, UserInvalidError
|
||||||
from app import app, isAnAdmin
|
from classes.holo_user import HoloUser
|
||||||
|
from modules.logging import logWrite
|
||||||
from modules.utils import configGet, jsonLoad, locale
|
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
|
||||||
|
|
||||||
|
|
||||||
@app.on_inline_query()
|
@app.on_inline_query()
|
||||||
async def inline_answer(client, inline_query):
|
async def inline_answer(client: Client, inline_query: InlineQuery):
|
||||||
|
results = []
|
||||||
|
|
||||||
|
if configGet("allow_external", "features", "spoilers") is True:
|
||||||
|
if inline_query.query.startswith("spoiler:"):
|
||||||
|
try:
|
||||||
|
spoil = col_spoilers.find_one(
|
||||||
|
{"_id": ObjectId(inline_query.query.removeprefix("spoiler:"))}
|
||||||
|
)
|
||||||
|
|
||||||
|
if spoil is not None:
|
||||||
|
desc = locale(
|
||||||
|
"spoiler_described",
|
||||||
|
"message",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
).format(
|
||||||
|
locale(spoil["category"], "message", "spoiler_categories"),
|
||||||
|
spoil["description"],
|
||||||
|
)
|
||||||
|
|
||||||
|
results = [
|
||||||
|
InlineQueryResultArticle(
|
||||||
|
title=locale(
|
||||||
|
"title",
|
||||||
|
"inline",
|
||||||
|
"spoiler",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
),
|
||||||
|
description=locale(
|
||||||
|
"description",
|
||||||
|
"inline",
|
||||||
|
"spoiler",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
),
|
||||||
|
input_message_content=InputTextMessageContent(
|
||||||
|
desc, disable_web_page_preview=True
|
||||||
|
),
|
||||||
|
reply_markup=InlineKeyboardMarkup(
|
||||||
|
[
|
||||||
|
[
|
||||||
|
InlineKeyboardButton(
|
||||||
|
locale(
|
||||||
|
"spoiler_view",
|
||||||
|
"button",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
),
|
||||||
|
callback_data=f'sid_{inline_query.query.removeprefix("spoiler:")}',
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
except InvalidId:
|
||||||
|
results = []
|
||||||
|
|
||||||
|
await inline_query.answer(results=results)
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
if inline_query.chat_type in [ChatType.CHANNEL]:
|
if inline_query.chat_type in [ChatType.CHANNEL]:
|
||||||
await inline_query.answer(
|
await inline_query.answer(
|
||||||
results=[
|
results=[
|
||||||
InlineQueryResultArticle(
|
InlineQueryResultArticle(
|
||||||
title=locale("title", "inline", "not_pm"),
|
title=locale(
|
||||||
input_message_content=InputTextMessageContent(
|
"title", "inline", "not_pm", locale=inline_query.from_user
|
||||||
locale("message_content", "inline", "not_pm")
|
),
|
||||||
|
input_message_content=InputTextMessageContent(
|
||||||
|
locale(
|
||||||
|
"message_content",
|
||||||
|
"inline",
|
||||||
|
"not_pm",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
)
|
||||||
|
),
|
||||||
|
description=locale(
|
||||||
|
"description", "inline", "not_pm", locale=inline_query.from_user
|
||||||
),
|
),
|
||||||
description=locale("description", "inline", "not_pm")
|
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
if (path.exists(f"{configGet('data', 'locations')}{sep}users{sep}{inline_query.from_user.id}.json") and jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{inline_query.from_user.id}.json")["approved"]) or (await isAnAdmin(inline_query.from_user.id)):
|
results_forbidden = [
|
||||||
|
InlineQueryResultArticle(
|
||||||
list_of_users = []
|
title=locale("title", "inline", "forbidden", locale=inline_query.from_user),
|
||||||
async for m in app.get_chat_members(configGet("destination_group"), limit=configGet("inline_preview_count"), filter=ChatMembersFilter.SEARCH, query=inline_query.query):
|
input_message_content=InputTextMessageContent(
|
||||||
list_of_users.append(m)
|
locale(
|
||||||
|
"message_content",
|
||||||
results = []
|
"inline",
|
||||||
|
"forbidden",
|
||||||
applications = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")
|
locale=inline_query.from_user,
|
||||||
|
)
|
||||||
for match in list_of_users:
|
),
|
||||||
|
description=locale(
|
||||||
|
"description", "inline", "forbidden", locale=inline_query.from_user
|
||||||
|
),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
try:
|
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=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
|
||||||
|
)
|
||||||
|
|
||||||
|
list_of_users = []
|
||||||
|
async for m in app.get_chat_members(
|
||||||
|
configGet("users", "groups"),
|
||||||
|
limit=max_results,
|
||||||
|
filter=ChatMembersFilter.SEARCH,
|
||||||
|
query=inline_query.query,
|
||||||
|
):
|
||||||
|
list_of_users.append(m)
|
||||||
|
|
||||||
|
for match in list_of_users:
|
||||||
|
application = col_applications.find_one({"user": match.user.id})
|
||||||
|
|
||||||
|
if application is None:
|
||||||
|
continue
|
||||||
|
|
||||||
application_content = []
|
application_content = []
|
||||||
i = 1
|
i = 1
|
||||||
for question in applications[str(match.user.id)]["application"]:
|
|
||||||
|
for question in application["application"]:
|
||||||
if i == 2:
|
if i == 2:
|
||||||
age = relativedelta(datetime.now(), datetime.strptime(applications[str(match.user.id)]['application']['2'], '%d.%m.%Y'))
|
age = relativedelta(datetime.now(), application["application"]["2"])
|
||||||
application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {applications[str(match.user.id)]['application']['2']} ({age.years} р.)")
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles', locale=inline_query.from_user)} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)"
|
||||||
|
)
|
||||||
|
elif i == 3:
|
||||||
|
if application["application"]["3"]["countryCode"] == "UA":
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles', locale=inline_query.from_user)} {application['application']['3']['name']}"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {applications[str(match.user.id)]['application'][question]}")
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles', locale=inline_query.from_user)} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
application_content.append(
|
||||||
|
f"{locale(f'question{i}', 'message', 'question_titles', locale=inline_query.from_user)} {application['application'][question]}"
|
||||||
|
)
|
||||||
|
|
||||||
i += 1
|
i += 1
|
||||||
except KeyError:
|
|
||||||
continue
|
|
||||||
except FileNotFoundError:
|
|
||||||
continue
|
|
||||||
except TypeError:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if match.user.photo != None:
|
if match.user.photo != None:
|
||||||
try:
|
try:
|
||||||
if not path.exists(f'{configGet("cache", "locations")}{sep}avatars{sep}{match.user.photo.big_file_id}'):
|
if not path.exists(
|
||||||
print(f'Downloaded avatar {match.user.photo.big_file_id} of {match.user.id} and uploaded to {configGet("api")}/?avatar_id={match.user.photo.big_file_id}', flush=True)
|
f'{configGet("cache", "locations")}{sep}avatars{sep}{match.user.photo.big_file_id}'
|
||||||
await app.download_media(match.user.photo.big_file_id, file_name=f'{configGet("cache", "locations")}{sep}avatars{sep}{match.user.photo.big_file_id}')
|
):
|
||||||
|
print(
|
||||||
|
f'Downloaded avatar {match.user.photo.big_file_id} of {match.user.id} and uploaded to {configGet("api")}/?avatar_id={match.user.photo.big_file_id}',
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
await app.download_media(
|
||||||
|
match.user.photo.big_file_id,
|
||||||
|
file_name=f'{configGet("cache", "locations")}{sep}avatars{sep}{match.user.photo.big_file_id}',
|
||||||
|
)
|
||||||
results.append(
|
results.append(
|
||||||
InlineQueryResultArticle(
|
InlineQueryResultArticle(
|
||||||
title=str(match.user.first_name),
|
title=str(match.user.first_name),
|
||||||
input_message_content=InputTextMessageContent(
|
input_message_content=InputTextMessageContent(
|
||||||
locale("message_content", "inline", "user").format(match.user.first_name, match.user.username, "\n".join(application_content))
|
locale(
|
||||||
|
"message_content",
|
||||||
|
"inline",
|
||||||
|
"user",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
).format(
|
||||||
|
match.user.first_name,
|
||||||
|
match.user.username,
|
||||||
|
"\n".join(application_content),
|
||||||
|
)
|
||||||
),
|
),
|
||||||
description=locale("description", "inline", "user").format(match.user.first_name, match.user.username),
|
description=locale(
|
||||||
thumb_url=f'{configGet("api")}/?avatar_id={match.user.photo.big_file_id}'
|
"description",
|
||||||
|
"inline",
|
||||||
|
"user",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
).format(match.user.first_name, match.user.username),
|
||||||
|
thumb_url=f'{configGet("api")}/?avatar_id={match.user.photo.big_file_id}',
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
@@ -74,9 +238,23 @@ async def inline_answer(client, inline_query):
|
|||||||
InlineQueryResultArticle(
|
InlineQueryResultArticle(
|
||||||
title=str(match.user.first_name),
|
title=str(match.user.first_name),
|
||||||
input_message_content=InputTextMessageContent(
|
input_message_content=InputTextMessageContent(
|
||||||
locale("message_content", "inline", "user").format(match.user.first_name, match.user.username, "\n".join(application_content))
|
locale(
|
||||||
|
"message_content",
|
||||||
|
"inline",
|
||||||
|
"user",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
).format(
|
||||||
|
match.user.first_name,
|
||||||
|
match.user.username,
|
||||||
|
"\n".join(application_content),
|
||||||
|
)
|
||||||
),
|
),
|
||||||
description=locale("description", "inline", "user").format(match.user.first_name, match.user.username)
|
description=locale(
|
||||||
|
"description",
|
||||||
|
"inline",
|
||||||
|
"user",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
).format(match.user.first_name, match.user.username),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
@@ -84,9 +262,23 @@ async def inline_answer(client, inline_query):
|
|||||||
InlineQueryResultArticle(
|
InlineQueryResultArticle(
|
||||||
title=str(match.user.first_name),
|
title=str(match.user.first_name),
|
||||||
input_message_content=InputTextMessageContent(
|
input_message_content=InputTextMessageContent(
|
||||||
locale("message_content", "inline", "user").format(match.user.first_name, match.user.username, "\n".join(application_content))
|
locale(
|
||||||
|
"message_content",
|
||||||
|
"inline",
|
||||||
|
"user",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
).format(
|
||||||
|
match.user.first_name,
|
||||||
|
match.user.username,
|
||||||
|
"\n".join(application_content),
|
||||||
|
)
|
||||||
),
|
),
|
||||||
description=locale("description", "inline", "user").format(match.user.first_name, match.user.username)
|
description=locale(
|
||||||
|
"description",
|
||||||
|
"inline",
|
||||||
|
"user",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
).format(match.user.first_name, match.user.username),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@@ -94,27 +286,24 @@ async def inline_answer(client, inline_query):
|
|||||||
InlineQueryResultArticle(
|
InlineQueryResultArticle(
|
||||||
title=str(match.user.first_name),
|
title=str(match.user.first_name),
|
||||||
input_message_content=InputTextMessageContent(
|
input_message_content=InputTextMessageContent(
|
||||||
locale("message_content", "inline", "user").format(match.user.first_name, match.user.username, "\n".join(application_content))
|
locale(
|
||||||
|
"message_content",
|
||||||
|
"inline",
|
||||||
|
"user",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
).format(
|
||||||
|
match.user.first_name,
|
||||||
|
match.user.username,
|
||||||
|
"\n".join(application_content),
|
||||||
|
)
|
||||||
),
|
),
|
||||||
description=locale("description", "inline", "user").format(match.user.first_name, match.user.username)
|
description=locale(
|
||||||
|
"description",
|
||||||
|
"inline",
|
||||||
|
"user",
|
||||||
|
locale=inline_query.from_user,
|
||||||
|
).format(match.user.first_name, match.user.username),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
await inline_query.answer(
|
await inline_query.answer(results=results, cache_time=10, is_personal=True)
|
||||||
results=results,
|
|
||||||
cache_time=10
|
|
||||||
)
|
|
||||||
|
|
||||||
else:
|
|
||||||
await inline_query.answer(
|
|
||||||
results=[
|
|
||||||
InlineQueryResultArticle(
|
|
||||||
title=locale("title", "inline", "forbidden"),
|
|
||||||
input_message_content=InputTextMessageContent(
|
|
||||||
locale("message_content", "inline", "forbidden")
|
|
||||||
),
|
|
||||||
description=locale("description", "inline", "forbidden")
|
|
||||||
)
|
|
||||||
]
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
@@ -5,14 +5,20 @@ from shutil import copyfileobj
|
|||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
with open(getcwd()+path.sep+"config.json", "r", encoding='utf8') as file:
|
with open(getcwd() + path.sep + "config.json", "r", encoding="utf8") as file:
|
||||||
json_contents = loads(file.read())
|
json_contents = loads(file.read())
|
||||||
log_size = json_contents["logging"]["size"]
|
log_size = json_contents["logging"]["size"]
|
||||||
log_folder = json_contents["logging"]["location"]
|
log_folder = json_contents["logging"]["location"]
|
||||||
file.close()
|
file.close()
|
||||||
|
|
||||||
|
|
||||||
# Check latest log size
|
# Check latest log size
|
||||||
def checkSize(debug=False):
|
def checkSize(debug=False):
|
||||||
|
"""Check size of latest.log file and rotate it if needed
|
||||||
|
|
||||||
|
### Args:
|
||||||
|
* debug (`bool`, *optional*): Whether this is a debug log. Defaults to `False`.
|
||||||
|
"""
|
||||||
|
|
||||||
global log_folder
|
global log_folder
|
||||||
|
|
||||||
@@ -25,17 +31,32 @@ def checkSize(debug=False):
|
|||||||
makedirs(log_folder, exist_ok=True)
|
makedirs(log_folder, exist_ok=True)
|
||||||
log = stat(path.join(log_folder, log_file))
|
log = stat(path.join(log_folder, log_file))
|
||||||
if (log.st_size / 1024) > log_size:
|
if (log.st_size / 1024) > log_size:
|
||||||
with open(path.join(log_folder, log_file), 'rb') as f_in:
|
with open(path.join(log_folder, log_file), "rb") as f_in:
|
||||||
with gzipopen(path.join(log_folder, f'{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.log.gz'), 'wb') as f_out:
|
with gzipopen(
|
||||||
|
path.join(
|
||||||
|
log_folder,
|
||||||
|
f'{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.log.gz',
|
||||||
|
),
|
||||||
|
"wb",
|
||||||
|
) as f_out:
|
||||||
copyfileobj(f_in, f_out)
|
copyfileobj(f_in, f_out)
|
||||||
print(f'Copied {path.join(log_folder, datetime.now().strftime("%d.%m.%Y_%H:%M:%S"))}.log.gz')
|
print(
|
||||||
open(path.join(log_folder, log_file), 'w').close()
|
f'Copied {path.join(log_folder, datetime.now().strftime("%d.%m.%Y_%H:%M:%S"))}.log.gz'
|
||||||
|
)
|
||||||
|
open(path.join(log_folder, log_file), "w").close()
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
print(f'Log file {path.join(log_folder, log_file)} does not exist')
|
print(f"Log file {path.join(log_folder, log_file)} does not exist")
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
# Append string to log
|
# Append string to log
|
||||||
def logAppend(message, debug=False):
|
def logAppend(message: str, debug=False):
|
||||||
|
"""Write message to log file
|
||||||
|
|
||||||
|
### Args:
|
||||||
|
* message (`str`): Message to write
|
||||||
|
* debug (`bool`, *optional*): Whether this is a debug log. Defaults to `False`.
|
||||||
|
"""
|
||||||
|
|
||||||
global log_folder
|
global log_folder
|
||||||
|
|
||||||
@@ -47,12 +68,19 @@ def logAppend(message, debug=False):
|
|||||||
else:
|
else:
|
||||||
log_file = "latest.log"
|
log_file = "latest.log"
|
||||||
|
|
||||||
log = open(path.join(log_folder, log_file), 'a')
|
log = open(path.join(log_folder, log_file), "a")
|
||||||
log.write(f'{message_formatted}\n')
|
log.write(f"{message_formatted}\n")
|
||||||
log.close()
|
log.close()
|
||||||
|
|
||||||
|
|
||||||
# Print to stdout and then to log
|
# Print to stdout and then to log
|
||||||
def logWrite(message, debug=False):
|
def logWrite(message: str, debug=False):
|
||||||
|
"""Write message to stdout and log file
|
||||||
|
|
||||||
|
### Args:
|
||||||
|
* message (`str`): Message to print and write
|
||||||
|
* debug (`bool`, *optional*): Whether this is a debug log. Defaults to `False`.
|
||||||
|
"""
|
||||||
# save to log file and rotation is to be done
|
# save to log file and rotation is to be done
|
||||||
logAppend(f'{message}', debug=debug)
|
logAppend(f"{message}", debug=debug)
|
||||||
print(f"{message}", flush=True)
|
print(f"{message}", flush=True)
|
@@ -1,35 +1,451 @@
|
|||||||
|
"""Automatically register commands and execute
|
||||||
|
some scheduled tasks is the main idea of this module"""
|
||||||
|
|
||||||
|
from asyncio import sleep
|
||||||
|
from os import listdir, makedirs, path, sep
|
||||||
|
from traceback import format_exc
|
||||||
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||||
from datetime import datetime
|
from datetime import datetime, timedelta
|
||||||
from os import fsdecode, listdir, sep
|
from ujson import dumps
|
||||||
from app import app
|
from app import app
|
||||||
from modules.utils import configGet, jsonLoad, locale, logWrite
|
from pyrogram.types import (
|
||||||
|
BotCommand,
|
||||||
|
BotCommandScopeChat,
|
||||||
|
BotCommandScopeChatAdministrators,
|
||||||
|
)
|
||||||
|
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, jsonLoad, jsonSave, locale, logWrite
|
||||||
from dateutil.relativedelta import relativedelta
|
from dateutil.relativedelta import relativedelta
|
||||||
from modules.database import col_applications
|
from modules.database import (
|
||||||
|
col_applications,
|
||||||
|
col_sponsorships,
|
||||||
|
col_youtube,
|
||||||
|
col_warnings,
|
||||||
|
)
|
||||||
|
from xmltodict import parse
|
||||||
|
from requests import get
|
||||||
|
|
||||||
scheduler = AsyncIOScheduler()
|
scheduler = AsyncIOScheduler()
|
||||||
|
|
||||||
# for user_file in listdir(f"{configGet('data', 'locations')}{sep}users{sep}"):
|
if configGet("enabled", "scheduler", "cache_members"):
|
||||||
# filename = fsdecode(f"{configGet('data', 'locations')}{sep}users{sep}{user_file}")
|
|
||||||
# if filename.endswith(".json"):
|
|
||||||
# user = jsonLoad(filename)
|
|
||||||
# if isinstance(user["application"]["2"], str):
|
|
||||||
# try:
|
|
||||||
# if ".".join([((user["application"]["2"]).split("."))[0], ((user["application"]["2"]).split("."))[1]]) == datetime.now().strftime("%d.%m"):
|
|
||||||
# tg_user = await app.get_users(int(user_file.replace(".json", "")))
|
|
||||||
# await app.send_message( configGet("admin_group"), locale("birthday", "message").format(str(tg_user.first_name), str(tg_user.username), str(relativedelta(datetime.now(), datetime.strptime(user["application"]["2"], '%d.%m.%Y')).years)) )
|
|
||||||
# except AttributeError:
|
|
||||||
# continue
|
|
||||||
|
|
||||||
if configGet("enabled", "scheduler", "birthdays"):
|
@scheduler.scheduled_job(
|
||||||
@scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "birthdays"))
|
trigger="interval", seconds=configGet("interval", "scheduler", "cache_members")
|
||||||
|
)
|
||||||
|
async def cache_group_members():
|
||||||
|
list_of_users = []
|
||||||
|
async for member in app.get_chat_members(configGet("users", "groups")):
|
||||||
|
list_of_users.append(member.user.id)
|
||||||
|
makedirs(configGet("cache", "locations"), exist_ok=True)
|
||||||
|
jsonSave(
|
||||||
|
list_of_users, path.join(configGet("cache", "locations"), "group_members")
|
||||||
|
)
|
||||||
|
if configGet("debug") is True:
|
||||||
|
logWrite("User group caching performed", debug=True)
|
||||||
|
|
||||||
|
|
||||||
|
if configGet("enabled", "scheduler", "cache_admins"):
|
||||||
|
|
||||||
|
@scheduler.scheduled_job(
|
||||||
|
trigger="interval", seconds=configGet("interval", "scheduler", "cache_admins")
|
||||||
|
)
|
||||||
|
async def cache_admins():
|
||||||
|
list_of_users = []
|
||||||
|
async for member in app.get_chat_members(configGet("admin", "groups")):
|
||||||
|
list_of_users.append(member.user.id)
|
||||||
|
makedirs(configGet("cache", "locations"), exist_ok=True)
|
||||||
|
jsonSave(list_of_users, path.join(configGet("cache", "locations"), "admins"))
|
||||||
|
if configGet("debug") is True:
|
||||||
|
logWrite("Admin group caching performed", debug=True)
|
||||||
|
|
||||||
|
|
||||||
|
# Cache the avatars of group members
|
||||||
|
if configGet("enabled", "scheduler", "cache_avatars"):
|
||||||
|
|
||||||
|
@scheduler.scheduled_job(
|
||||||
|
trigger="date", run_date=datetime.now() + timedelta(seconds=15)
|
||||||
|
)
|
||||||
|
@scheduler.scheduled_job(
|
||||||
|
trigger="interval", hours=configGet("interval", "scheduler", "cache_avatars")
|
||||||
|
)
|
||||||
|
async def cache_avatars():
|
||||||
|
list_of_users = []
|
||||||
|
async for member in app.get_chat_members(
|
||||||
|
configGet("users", "groups"), filter=ChatMembersFilter.SEARCH, query=""
|
||||||
|
):
|
||||||
|
list_of_users.append(member.user)
|
||||||
|
for user in list_of_users:
|
||||||
|
if user.photo != None:
|
||||||
|
if not path.exists(
|
||||||
|
f'{configGet("cache", "locations")}{sep}avatars{sep}{user.photo.big_file_id}'
|
||||||
|
):
|
||||||
|
print(
|
||||||
|
f"Pre-cached avatar {user.photo.big_file_id} of {user.id}",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
await app.download_media(
|
||||||
|
user.photo.big_file_id,
|
||||||
|
file_name=path.join(
|
||||||
|
configGet("cache", "locations"),
|
||||||
|
"avatars",
|
||||||
|
user.photo.big_file_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
logWrite("Avatars caching performed")
|
||||||
|
|
||||||
|
|
||||||
|
# Check for birthdays
|
||||||
|
if configGet("enabled", "features", "applications") is True:
|
||||||
|
if configGet("enabled", "scheduler", "birthdays") is True:
|
||||||
|
|
||||||
|
@scheduler.scheduled_job(
|
||||||
|
trigger="cron", hour=configGet("time", "scheduler", "birthdays")
|
||||||
|
)
|
||||||
async def check_birthdays():
|
async def check_birthdays():
|
||||||
for entry in col_applications.find({"2": datetime.now().strftime("%d.%m.%Y")}):
|
for entry in col_applications.find():
|
||||||
|
if entry["application"]["2"].strftime(
|
||||||
|
"%d.%m"
|
||||||
|
) == datetime.now().strftime("%d.%m"):
|
||||||
|
try:
|
||||||
|
if entry["user"] not in jsonLoad(
|
||||||
|
path.join(configGet("cache", "locations"), "group_members")
|
||||||
|
):
|
||||||
|
continue
|
||||||
tg_user = await app.get_users(entry["user"])
|
tg_user = await app.get_users(entry["user"])
|
||||||
await app.send_message( configGet("admin_group"), locale("birthday", "message").format(str(tg_user.first_name), str(tg_user.username), str(relativedelta(datetime.now(), datetime.strptime(entry["2"], '%d.%m.%Y')).years)) ) # type: ignore
|
await app.send_message(configGet("admin", "groups"), 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
|
||||||
logWrite(f"Notified admins about {entry['user']}'s birthday")
|
logWrite(f"Notified admins about {entry['user']}'s birthday")
|
||||||
|
except Exception as exp:
|
||||||
|
logWrite(
|
||||||
|
f"Could not find user {entry['user']} to send a message about birthday due to '{exp}'"
|
||||||
|
)
|
||||||
|
continue
|
||||||
logWrite("Birthdays check performed")
|
logWrite("Birthdays check performed")
|
||||||
|
|
||||||
if configGet("enabled", "scheduler", "sponsorships"):
|
|
||||||
@scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "sponsorships"))
|
# Check for expired sponsorships
|
||||||
|
if configGet("enabled", "features", "sponsorships") is True:
|
||||||
|
if configGet("enabled", "scheduler", "sponsorships") is True:
|
||||||
|
|
||||||
|
@scheduler.scheduled_job(
|
||||||
|
trigger="cron", hour=configGet("time", "scheduler", "sponsorships")
|
||||||
|
)
|
||||||
async def check_sponsors():
|
async def check_sponsors():
|
||||||
|
for entry in col_sponsorships.find(
|
||||||
|
{"sponsorship.expires": {"$lt": datetime.now() + timedelta(days=2)}}
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
if entry["user"] not in jsonLoad(
|
||||||
|
path.join(configGet("cache", "locations"), "group_members")
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
tg_user = await app.get_users(entry["user"])
|
||||||
|
until_expiry = (
|
||||||
|
abs(
|
||||||
|
relativedelta(
|
||||||
|
datetime.now(), entry["sponsorship"]["expires"]
|
||||||
|
).days
|
||||||
|
)
|
||||||
|
+ 1
|
||||||
|
)
|
||||||
|
await app.send_message(tg_user.id, locale("sponsorships_expires", "message").format(until_expiry)) # type: ignore
|
||||||
|
logWrite(
|
||||||
|
f"Notified user {entry['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() - timedelta(days=1)}}
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
holo_user = HoloUser(entry["user"])
|
||||||
|
col_sponsorships.find_one_and_delete({"user": holo_user.id})
|
||||||
|
if entry["user"] not in jsonLoad(
|
||||||
|
path.join(configGet("cache", "locations"), "group_members")
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
await app.send_message(entry["user"], locale("sponsorships_expired", "message")) # type: ignore
|
||||||
|
await holo_user.label_reset(configGet("users", "groups"))
|
||||||
|
try:
|
||||||
|
tg_user = await app.get_users(entry["user"])
|
||||||
|
logWrite(
|
||||||
|
f"Notified user {entry['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")
|
logWrite("Sponsorships check performed")
|
||||||
|
|
||||||
|
|
||||||
|
# Revoke old warnings
|
||||||
|
if configGet("enabled", "features", "warnings") is True:
|
||||||
|
if configGet("enabled", "scheduler", "warnings_revocation") is True:
|
||||||
|
|
||||||
|
@scheduler.scheduled_job(
|
||||||
|
trigger="date", run_date=datetime.now() + timedelta(seconds=10)
|
||||||
|
)
|
||||||
|
@scheduler.scheduled_job(
|
||||||
|
trigger="interval",
|
||||||
|
hours=configGet("interval", "scheduler", "warnings_revocation"),
|
||||||
|
)
|
||||||
|
async def revoke_warnings():
|
||||||
|
for warning in list(
|
||||||
|
col_warnings.find(
|
||||||
|
{
|
||||||
|
"active": True,
|
||||||
|
"date": {"$lt": datetime.now() - timedelta(days=90)},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
):
|
||||||
|
if (
|
||||||
|
col_warnings.count_documents(
|
||||||
|
{
|
||||||
|
"user": warning["user"],
|
||||||
|
"active": True,
|
||||||
|
"date": {"$gt": datetime.now() - timedelta(days=90)},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
== 0
|
||||||
|
):
|
||||||
|
col_warnings.update_one(
|
||||||
|
{"_id": warning["_id"]},
|
||||||
|
{"$set": {"active": False, "revoke_date": datetime.now()}},
|
||||||
|
)
|
||||||
|
logWrite(
|
||||||
|
f'Revoked warning {str(warning["_id"])} of user {warning["user"]} because no active warnings for the last 90 days found.'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Register all bot commands
|
||||||
|
@scheduler.scheduled_job(
|
||||||
|
trigger="date", run_date=datetime.now() + timedelta(seconds=10)
|
||||||
|
)
|
||||||
|
async def commands_register():
|
||||||
|
commands = {
|
||||||
|
"users": [],
|
||||||
|
"admins": [],
|
||||||
|
"owner": [],
|
||||||
|
"group_users": [],
|
||||||
|
"group_admins": [],
|
||||||
|
"group_users_admins": [],
|
||||||
|
"locales": {},
|
||||||
|
}
|
||||||
|
|
||||||
|
commands_raw = {
|
||||||
|
"users": [],
|
||||||
|
"admins": [],
|
||||||
|
"owner": [],
|
||||||
|
"group_users": [],
|
||||||
|
"group_admins": [],
|
||||||
|
"group_users_admins": [],
|
||||||
|
"locales": {},
|
||||||
|
}
|
||||||
|
|
||||||
|
valid_locales = []
|
||||||
|
files_locales = listdir(f'{configGet("locale", "locations")}')
|
||||||
|
|
||||||
|
for entry in files_locales:
|
||||||
|
if entry.endswith(".json"):
|
||||||
|
valid_locales.append(".".join(entry.split(".")[:-1]))
|
||||||
|
commands["locales"][".".join(entry.split(".")[:-1])] = {
|
||||||
|
"users": [],
|
||||||
|
"admins": [],
|
||||||
|
"owner": [],
|
||||||
|
"group_users": [],
|
||||||
|
"group_admins": [],
|
||||||
|
"group_users_admins": [],
|
||||||
|
}
|
||||||
|
if configGet("debug") is True:
|
||||||
|
commands_raw["locales"][".".join(entry.split(".")[:-1])] = {
|
||||||
|
"users": [],
|
||||||
|
"admins": [],
|
||||||
|
"owner": [],
|
||||||
|
"group_users": [],
|
||||||
|
"group_admins": [],
|
||||||
|
"group_users_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]["enabled"] is True:
|
||||||
|
enabled = True
|
||||||
|
|
||||||
|
if enabled is False:
|
||||||
|
logWrite(f"Not registering {command} at all", debug=True)
|
||||||
|
continue
|
||||||
|
|
||||||
|
for permission in config_commands[command]["permissions"]:
|
||||||
|
commands[permission].append(
|
||||||
|
BotCommand(command, locale("commands")[command])
|
||||||
|
)
|
||||||
|
|
||||||
|
if configGet("debug") is True:
|
||||||
|
commands_raw[permission].append(
|
||||||
|
{f"{command}": locale("commands")[command]}
|
||||||
|
)
|
||||||
|
logWrite(f"Registering {command} for {permission}")
|
||||||
|
|
||||||
|
for lc in valid_locales:
|
||||||
|
commands["locales"][lc][permission].append(
|
||||||
|
BotCommand(command, locale("commands", locale=lc)[command])
|
||||||
|
)
|
||||||
|
|
||||||
|
if configGet("debug") is True:
|
||||||
|
commands_raw["locales"][lc][permission].append(
|
||||||
|
{f"{command}": locale("commands", locale=lc)[command]}
|
||||||
|
)
|
||||||
|
logWrite(f"Registering {command} for {permission} [{lc}]")
|
||||||
|
|
||||||
|
# Registering user commands
|
||||||
|
await app.set_bot_commands(commands["users"])
|
||||||
|
logWrite("Registered user commands for default locale")
|
||||||
|
|
||||||
|
# Registering user commands for each locale
|
||||||
|
for lc in valid_locales:
|
||||||
|
await app.set_bot_commands(commands["locales"][lc]["users"], language_code=lc)
|
||||||
|
logWrite(f"Registered user commands for locale {lc}")
|
||||||
|
|
||||||
|
# Registering admin commands
|
||||||
|
for admin in configGet("admins"):
|
||||||
|
try:
|
||||||
|
await app.set_bot_commands(
|
||||||
|
commands["admins"] + commands["users"],
|
||||||
|
scope=BotCommandScopeChat(chat_id=admin),
|
||||||
|
)
|
||||||
|
logWrite(f"Registered admin commands for admin {admin}")
|
||||||
|
except bad_request_400.PeerIdInvalid:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Registering owner commands
|
||||||
|
try:
|
||||||
|
await app.set_bot_commands(
|
||||||
|
commands["admins"] + commands["owner"] + commands["users"],
|
||||||
|
scope=BotCommandScopeChat(chat_id=configGet("owner")),
|
||||||
|
)
|
||||||
|
for lc in valid_locales:
|
||||||
|
await app.set_bot_commands(
|
||||||
|
commands["locales"][lc]["admins"]
|
||||||
|
+ commands["locales"][lc]["owner"]
|
||||||
|
+ commands["locales"][lc]["users"],
|
||||||
|
scope=BotCommandScopeChat(chat_id=configGet("owner")),
|
||||||
|
)
|
||||||
|
logWrite(f"Registered admin commands for owner {configGet('owner')}")
|
||||||
|
except bad_request_400.PeerIdInvalid:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Registering admin group commands
|
||||||
|
try:
|
||||||
|
await app.set_bot_commands(
|
||||||
|
commands["group_admins"],
|
||||||
|
scope=BotCommandScopeChat(chat_id=configGet("admin", "groups")),
|
||||||
|
)
|
||||||
|
logWrite("Registered admin group commands for default locale")
|
||||||
|
except bad_request_400.ChannelInvalid:
|
||||||
|
logWrite(
|
||||||
|
f"Could not register commands for admin group. Bot is likely not in the group."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Registering destination group commands
|
||||||
|
try:
|
||||||
|
await app.set_bot_commands(
|
||||||
|
commands["group_users"],
|
||||||
|
scope=BotCommandScopeChat(chat_id=configGet("users", "groups")),
|
||||||
|
)
|
||||||
|
logWrite("Registered destination group commands")
|
||||||
|
except bad_request_400.ChannelInvalid:
|
||||||
|
logWrite(
|
||||||
|
f"Could not register commands for destination group. Bot is likely not in the group."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Registering destination group admin commands
|
||||||
|
try:
|
||||||
|
await app.set_bot_commands(
|
||||||
|
commands["group_users_admins"],
|
||||||
|
scope=BotCommandScopeChatAdministrators(
|
||||||
|
chat_id=configGet("users", "groups")
|
||||||
|
),
|
||||||
|
)
|
||||||
|
logWrite("Registered destination group admin commands")
|
||||||
|
except bad_request_400.ChannelInvalid:
|
||||||
|
logWrite(
|
||||||
|
f"Could not register admin commands for destination group. Bot is likely not in the group."
|
||||||
|
)
|
||||||
|
|
||||||
|
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)}",
|
||||||
|
debug=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if configGet("enabled", "scheduler", "channels_monitor"):
|
||||||
|
|
||||||
|
@scheduler.scheduled_job(
|
||||||
|
trigger="interval",
|
||||||
|
minutes=configGet("interval", "scheduler", "channels_monitor"),
|
||||||
|
)
|
||||||
|
async def channels_monitor():
|
||||||
|
for channel in configGet("channels", "scheduler", "channels_monitor"):
|
||||||
|
if configGet("debug") is True:
|
||||||
|
logWrite(
|
||||||
|
f'Processing videos of {channel["name"]} ({channel["id"]})',
|
||||||
|
debug=True,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
req = get(
|
||||||
|
f'https://www.youtube.com/feeds/videos.xml?channel_id={channel["id"]}'
|
||||||
|
)
|
||||||
|
parsed = parse(req.content)
|
||||||
|
if "feed" not in parsed:
|
||||||
|
continue
|
||||||
|
if "entry" not in parsed["feed"]:
|
||||||
|
continue
|
||||||
|
for entry in parsed["feed"]["entry"]:
|
||||||
|
if "yt:videoId" not in entry:
|
||||||
|
continue
|
||||||
|
if (
|
||||||
|
col_youtube.find_one(
|
||||||
|
{"channel": channel["id"], "video": entry["yt:videoId"]}
|
||||||
|
)
|
||||||
|
is None
|
||||||
|
):
|
||||||
|
col_youtube.insert_one(
|
||||||
|
{
|
||||||
|
"channel": channel["id"],
|
||||||
|
"video": entry["yt:videoId"],
|
||||||
|
"date": datetime.fromisoformat(entry["published"]),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
await app.send_message(
|
||||||
|
configGet("users", "groups"),
|
||||||
|
locale("youtube_video", "message").format(
|
||||||
|
channel["name"],
|
||||||
|
channel["link"],
|
||||||
|
entry["title"],
|
||||||
|
entry["link"]["@href"],
|
||||||
|
),
|
||||||
|
disable_web_page_preview=False,
|
||||||
|
)
|
||||||
|
await sleep(2)
|
||||||
|
except Exception as exp:
|
||||||
|
logWrite(
|
||||||
|
f'Could not get last videos of {channel["name"]} ({channel["id"]}) due to {exp}: {format_exc()}'
|
||||||
|
)
|
||||||
|
if configGet("debug") is True:
|
||||||
|
logWrite("Admin group caching performed", debug=True)
|
||||||
|
157
modules/utils.py
157
modules/utils.py
@@ -1,4 +1,6 @@
|
|||||||
from typing import Any, Union
|
from typing import Any, Literal, Tuple, Union
|
||||||
|
from uuid import uuid1
|
||||||
|
from requests import get
|
||||||
from pyrogram.enums.chat_type import ChatType
|
from pyrogram.enums.chat_type import ChatType
|
||||||
from pyrogram.types import User
|
from pyrogram.types import User
|
||||||
from pyrogram.client import Client
|
from pyrogram.client import Client
|
||||||
@@ -7,29 +9,36 @@ from ujson import JSONDecodeError as JSONDecodeError
|
|||||||
from ujson import loads, dumps
|
from ujson import loads, dumps
|
||||||
|
|
||||||
from sys import exit
|
from sys import exit
|
||||||
from os import kill, sep
|
from os import kill, listdir, makedirs, path, sep
|
||||||
from os import name as osname
|
from os import name as osname
|
||||||
from traceback import print_exc
|
from traceback import print_exc
|
||||||
|
from classes.errors.geo import PlaceNotFoundError
|
||||||
|
|
||||||
from modules.logging import logWrite
|
from modules.logging import logWrite
|
||||||
|
|
||||||
|
|
||||||
def jsonLoad(filename):
|
def jsonLoad(filename):
|
||||||
"""Loads arg1 as json and returns its contents"""
|
"""Loads arg1 as json and returns its contents"""
|
||||||
with open(filename, "r", encoding='utf8') as file:
|
with open(filename, "r", encoding="utf8") as file:
|
||||||
try:
|
try:
|
||||||
output = loads(file.read())
|
output = loads(file.read())
|
||||||
except JSONDecodeError:
|
except JSONDecodeError:
|
||||||
logWrite(f"Could not load json file {filename}: file seems to be incorrect!\n{print_exc()}")
|
logWrite(
|
||||||
|
f"Could not load json file {filename}: file seems to be incorrect!\n{print_exc()}"
|
||||||
|
)
|
||||||
raise
|
raise
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
logWrite(f"Could not load json file {filename}: file does not seem to exist!\n{print_exc()}")
|
logWrite(
|
||||||
|
f"Could not load json file {filename}: file does not seem to exist!\n{print_exc()}"
|
||||||
|
)
|
||||||
raise
|
raise
|
||||||
return output
|
return output
|
||||||
|
|
||||||
|
|
||||||
def jsonSave(contents, filename):
|
def jsonSave(contents, filename):
|
||||||
"""Dumps dict/list arg1 to file arg2"""
|
"""Dumps dict/list arg1 to file arg2"""
|
||||||
try:
|
try:
|
||||||
with open(filename, "w", encoding='utf8') as file:
|
with open(filename, "w", encoding="utf8") as file:
|
||||||
file.write(dumps(contents, ensure_ascii=False, indent=4))
|
file.write(dumps(contents, ensure_ascii=False, indent=4))
|
||||||
except Exception as exp:
|
except Exception as exp:
|
||||||
logWrite(f"Could not save json file {filename}: {exp}\n{print_exc()}")
|
logWrite(f"Could not save json file {filename}: {exp}\n{print_exc()}")
|
||||||
@@ -49,6 +58,7 @@ def nested_set(dic, keys, value, create_missing=True):
|
|||||||
d[keys[-1]] = value
|
d[keys[-1]] = value
|
||||||
return dic
|
return dic
|
||||||
|
|
||||||
|
|
||||||
def configSet(keys: list, value: Any, file: str = "config", create_missing=True):
|
def configSet(keys: list, value: Any, file: str = "config", create_missing=True):
|
||||||
"""Set config's value to provided one
|
"""Set config's value to provided one
|
||||||
|
|
||||||
@@ -66,7 +76,10 @@ def configSet(keys: list, value: Any, file: str = "config", create_missing=True)
|
|||||||
this_dict = jsonLoad("config_debug.json")
|
this_dict = jsonLoad("config_debug.json")
|
||||||
file = "config_debug"
|
file = "config_debug"
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
print("Debug mode is set but config_debug.json is not there! Falling back to config.json", flush=True)
|
print(
|
||||||
|
"Debug mode is set but config_debug.json is not there! Falling back to config.json",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
filepath = f"data{sep}users{sep}"
|
filepath = f"data{sep}users{sep}"
|
||||||
this_dict = jsonLoad(f"{filepath}{file}.json")
|
this_dict = jsonLoad(f"{filepath}{file}.json")
|
||||||
@@ -75,6 +88,7 @@ def configSet(keys: list, value: Any, file: str = "config", create_missing=True)
|
|||||||
jsonSave(this_dict, f"{filepath}{file}.json")
|
jsonSave(this_dict, f"{filepath}{file}.json")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
def configGet(key: str, *args: str, file: str = "config"):
|
def configGet(key: str, *args: str, file: str = "config"):
|
||||||
"""Get value of the config key
|
"""Get value of the config key
|
||||||
### Args:
|
### Args:
|
||||||
@@ -88,13 +102,19 @@ def configGet(key: str, *args: str, file: str = "config"):
|
|||||||
try:
|
try:
|
||||||
this_dict = jsonLoad("config.json")
|
this_dict = jsonLoad("config.json")
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
print("Config file not found! Copy config_example.json to config.json, configure it and rerun the bot!", flush=True)
|
print(
|
||||||
|
"Config file not found! Copy config_example.json to config.json, configure it and rerun the bot!",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
exit()
|
exit()
|
||||||
if this_dict["debug"] is True:
|
if this_dict["debug"] is True:
|
||||||
try:
|
try:
|
||||||
this_dict = jsonLoad("config_debug.json")
|
this_dict = jsonLoad("config_debug.json")
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
print("Debug mode is set but config_debug.json is not there! Falling back to config.json", flush=True)
|
print(
|
||||||
|
"Debug mode is set but config_debug.json is not there! Falling back to config.json",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
this_dict = jsonLoad(f"data{sep}users{sep}{file}.json")
|
this_dict = jsonLoad(f"data{sep}users{sep}{file}.json")
|
||||||
this_key = this_dict
|
this_key = this_dict
|
||||||
@@ -102,17 +122,20 @@ def configGet(key: str, *args: str, file: str = "config"):
|
|||||||
this_key = this_key[dict_key]
|
this_key = this_key[dict_key]
|
||||||
return this_key[key]
|
return this_key[key]
|
||||||
|
|
||||||
|
|
||||||
def locale(key: str, *args: str, locale: Union[str, User] = configGet("locale")) -> Any:
|
def locale(key: str, *args: str, locale: Union[str, User] = configGet("locale")) -> Any:
|
||||||
"""Get value of locale string
|
"""Get value of locale string
|
||||||
### Args:
|
### Args:
|
||||||
* key (`str`): The last key of the locale's keys path.
|
* key (`str`): The last key of the locale's keys path.
|
||||||
* *args (`list`): Path to key like: dict[args][key].
|
* *args (`list`): Path to key like: dict[args][key].
|
||||||
* locale (`Union[str, User]`): Locale to looked up in. Provide User to get his `.language_code`. Defaults to config's locale value.
|
* locale (`Union[str, User, HoloUser]`): Locale to looked up in. Provide User to get his `.language_code`. Defaults to config's locale value.
|
||||||
### Returns:
|
### Returns:
|
||||||
* any: Value of provided locale key. In normal case must be `str`, `dict` or `list`.
|
* any: Value of provided locale key. In normal case must be `str`, `dict` or `list`.
|
||||||
"""
|
"""
|
||||||
if isinstance(locale, User):
|
if isinstance(locale, User):
|
||||||
locale = locale.language_code
|
locale = locale.language_code
|
||||||
|
elif hasattr(locale, "locale"):
|
||||||
|
locale = locale.locale
|
||||||
|
|
||||||
if locale is None:
|
if locale is None:
|
||||||
locale = configGet("locale")
|
locale = configGet("locale")
|
||||||
@@ -121,7 +144,9 @@ def locale(key: str, *args: str, locale: Union[str, User] = configGet("locale"))
|
|||||||
this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{locale}.json')
|
this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{locale}.json')
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
try:
|
try:
|
||||||
this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{configGet("locale")}.json')
|
this_dict = jsonLoad(
|
||||||
|
f'{configGet("locale", "locations")}{sep}{configGet("locale")}.json'
|
||||||
|
)
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
|
return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
|
||||||
|
|
||||||
@@ -134,24 +159,132 @@ def locale(key: str, *args: str, locale: Union[str, User] = configGet("locale"))
|
|||||||
except KeyError:
|
except KeyError:
|
||||||
return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
|
return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
|
||||||
|
|
||||||
|
|
||||||
|
def all_locales(key: str, *args: str) -> list:
|
||||||
|
"""Get value of the provided key and path in all available locales
|
||||||
|
|
||||||
|
### Args:
|
||||||
|
* key (`str`): The last key of the locale's keys path.
|
||||||
|
* *args (`list`): Path to key like: dict[args][key].
|
||||||
|
|
||||||
|
### Returns:
|
||||||
|
* `list`: List of all values in all locales
|
||||||
|
"""
|
||||||
|
|
||||||
|
output = []
|
||||||
|
valid_locales = []
|
||||||
|
|
||||||
|
files_locales = listdir(f'{configGet("locale", "locations")}')
|
||||||
|
for entry in files_locales:
|
||||||
|
valid_locales.append(".".join(entry.split(".")[:-1]))
|
||||||
|
|
||||||
|
for lc in valid_locales:
|
||||||
|
try:
|
||||||
|
this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{lc}.json')
|
||||||
|
except FileNotFoundError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
this_key = this_dict
|
||||||
|
for dict_key in args:
|
||||||
|
this_key = this_key[dict_key]
|
||||||
|
|
||||||
|
try:
|
||||||
|
output.append(this_key[key])
|
||||||
|
except KeyError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def find_location(query: str) -> dict:
|
||||||
|
"""Find location on geonames.org by query. Search is made with feature classes A and P.
|
||||||
|
|
||||||
|
### Args:
|
||||||
|
* query (`str`): Some city/village/state name
|
||||||
|
|
||||||
|
### Raises:
|
||||||
|
* PlaceNotFoundError: Exception is raised when API result is empty
|
||||||
|
|
||||||
|
### Returns:
|
||||||
|
* `dict`: One instance of geonames response
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
result = (
|
||||||
|
get(
|
||||||
|
f"http://api.geonames.org/searchJSON?q={query}&maxRows=1&countryBias=UA&lang=uk&orderby=relevance&featureClass=P&featureClass=A&username={configGet('username', 'geocoding')}"
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
return result["geonames"][0]
|
||||||
|
except (ValueError, KeyError, IndexError):
|
||||||
|
raise PlaceNotFoundError(query)
|
||||||
|
|
||||||
|
|
||||||
|
def create_tmp(
|
||||||
|
bytedata: Union[bytes, bytearray],
|
||||||
|
kind: Union[Literal["image", "video"], None] = None,
|
||||||
|
) -> str:
|
||||||
|
"""Create temporary file to help uploading it
|
||||||
|
|
||||||
|
### Args:
|
||||||
|
* bytedata (`Union[bytes, bytearray]`): Some bytes to be written
|
||||||
|
* kind (`Union[Literal["image", "video"], None]`): Kind of upload. Will add `.jpg` or `.mp4` if needed
|
||||||
|
|
||||||
|
### Returns:
|
||||||
|
* `str`: Path to temporary file
|
||||||
|
"""
|
||||||
|
filename = str(uuid1())
|
||||||
|
if kind == "image":
|
||||||
|
filename += ".jpg"
|
||||||
|
elif kind == "video":
|
||||||
|
filename += ".mp4"
|
||||||
|
makedirs("tmp", exist_ok=True)
|
||||||
|
with open(path.join("tmp", filename), "wb") as file:
|
||||||
|
file.write(bytedata)
|
||||||
|
return path.join("tmp", filename)
|
||||||
|
|
||||||
|
|
||||||
|
async def download_tmp(app: Client, file_id: str) -> Tuple[str, bytes]:
|
||||||
|
"""Download file by its ID and return its bytes
|
||||||
|
|
||||||
|
### Args:
|
||||||
|
* app (`Client`): App that will download the file
|
||||||
|
* file_id (`str`): File's unique id
|
||||||
|
|
||||||
|
### Returns:
|
||||||
|
* `Tuple[str, bytes]`: First is a filepath and the second is file's bytes
|
||||||
|
"""
|
||||||
|
filename = str(uuid1())
|
||||||
|
makedirs("tmp", exist_ok=True)
|
||||||
|
await app.download_media(file_id, path.join("tmp", filename))
|
||||||
|
with open(path.join("tmp", filename), "rb") as f:
|
||||||
|
bytedata = f.read()
|
||||||
|
return path.join("tmp", filename), bytedata
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from psutil import Process
|
from psutil import Process
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
# print(locale("deps_missing", "console", locale=configGet("locale")), flush=True)
|
# print(locale("deps_missing", "console", locale=configGet("locale")), flush=True)
|
||||||
print("Missing dependencies! Please install all needed dependencies and run the bot again!")
|
print(
|
||||||
|
"Missing dependencies! Please install all needed dependencies and run the bot again!"
|
||||||
|
)
|
||||||
exit()
|
exit()
|
||||||
|
|
||||||
|
|
||||||
def killProc(pid):
|
def killProc(pid):
|
||||||
if osname == "posix":
|
if osname == "posix":
|
||||||
from signal import SIGKILL
|
from signal import SIGKILL
|
||||||
|
|
||||||
kill(pid, SIGKILL)
|
kill(pid, SIGKILL)
|
||||||
else:
|
else:
|
||||||
p = Process(pid)
|
p = Process(pid)
|
||||||
p.kill()
|
p.kill()
|
||||||
|
|
||||||
|
|
||||||
def should_quote(msg):
|
def should_quote(msg):
|
||||||
return True if msg.chat.type is not ChatType.PRIVATE else False
|
return True if msg.chat.type is not ChatType.PRIVATE else False
|
||||||
|
|
||||||
|
|
||||||
async def find_user(app: Client, query: Union[str, int]):
|
async def find_user(app: Client, query: Union[str, int]):
|
||||||
try:
|
try:
|
||||||
result = await app.get_users(int(query))
|
result = await app.get_users(int(query))
|
||||||
|
@@ -1,9 +1,16 @@
|
|||||||
APScheduler==3.9.1.post1
|
aiocsv==1.2.3
|
||||||
fastapi==0.88.0
|
aiofiles~=23.1.0
|
||||||
|
APScheduler~=3.10.1
|
||||||
|
convopyro==0.5
|
||||||
|
fastapi~=0.95.0
|
||||||
|
ftfy~=6.1.1
|
||||||
psutil==5.9.4
|
psutil==5.9.4
|
||||||
pymongo==4.3.3
|
pymongo==4.3.3
|
||||||
Pyrogram==2.0.69
|
Pyrogram~=2.0.102
|
||||||
tgcrypto==1.2.5
|
|
||||||
python_dateutil==2.8.2
|
python_dateutil==2.8.2
|
||||||
starlette==0.22.0
|
pykeyboard==0.1.5
|
||||||
ujson==5.6.0
|
requests==2.28.2
|
||||||
|
starlette==0.26.1
|
||||||
|
tgcrypto==1.2.5
|
||||||
|
ujson~=5.7.0
|
||||||
|
xmltodict==0.13.0
|
@@ -1,6 +1,87 @@
|
|||||||
{
|
{
|
||||||
"$jsonSchema": {
|
"$jsonSchema": {
|
||||||
"required": [],
|
"required": [
|
||||||
"properties": {}
|
"user",
|
||||||
|
"date",
|
||||||
|
"admin",
|
||||||
|
"application",
|
||||||
|
"application.1",
|
||||||
|
"application.2",
|
||||||
|
"application.3",
|
||||||
|
"application.3.name",
|
||||||
|
"application.3.adminName1",
|
||||||
|
"application.3.countryCode",
|
||||||
|
"application.3.countryName",
|
||||||
|
"application.3.location",
|
||||||
|
"application.4",
|
||||||
|
"application.5",
|
||||||
|
"application.6",
|
||||||
|
"application.7",
|
||||||
|
"application.8",
|
||||||
|
"application.9",
|
||||||
|
"application.10"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"user": {
|
||||||
|
"bsonType": ["int", "long"],
|
||||||
|
"description": "Telegram ID of user"
|
||||||
|
},
|
||||||
|
"date": {
|
||||||
|
"bsonType": "date",
|
||||||
|
"description": "Date when application was accepted"
|
||||||
|
},
|
||||||
|
"admin": {
|
||||||
|
"bsonType": ["int", "long"],
|
||||||
|
"description": "Telegram ID of admin that accepted the application"
|
||||||
|
},
|
||||||
|
"application": {
|
||||||
|
"bsonType": "object"
|
||||||
|
},
|
||||||
|
"application.1": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"application.2": {
|
||||||
|
"bsonType": "date"
|
||||||
|
},
|
||||||
|
"application.3": {
|
||||||
|
"bsonType": "object"
|
||||||
|
},
|
||||||
|
"application.3.name": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"application.3.adminName1": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"application.3.countryCode": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"application.3.countryName": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"application.3.location": {
|
||||||
|
"bsonType": "array"
|
||||||
|
},
|
||||||
|
"application.4": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"application.5": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"application.6": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"application.7": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"application.8": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"application.9": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"application.10": {
|
||||||
|
"bsonType": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
29
validation/bans.json
Normal file
29
validation/bans.json
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"$jsonSchema": {
|
||||||
|
"required": [
|
||||||
|
"user",
|
||||||
|
"admin",
|
||||||
|
"date"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"user": {
|
||||||
|
"bsonType": [
|
||||||
|
"int",
|
||||||
|
"long"
|
||||||
|
],
|
||||||
|
"description": "Telegram ID of user"
|
||||||
|
},
|
||||||
|
"admin": {
|
||||||
|
"bsonType": [
|
||||||
|
"int",
|
||||||
|
"long"
|
||||||
|
],
|
||||||
|
"description": "Telegram ID of admin"
|
||||||
|
},
|
||||||
|
"date": {
|
||||||
|
"bsonType": "date",
|
||||||
|
"description": "Date and time of getting"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
64
validation/spoilers.json
Normal file
64
validation/spoilers.json
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
{
|
||||||
|
"$jsonSchema": {
|
||||||
|
"required": [
|
||||||
|
"user",
|
||||||
|
"completed",
|
||||||
|
"category",
|
||||||
|
"description",
|
||||||
|
"photo",
|
||||||
|
"video",
|
||||||
|
"audio",
|
||||||
|
"animation",
|
||||||
|
"document",
|
||||||
|
"caption",
|
||||||
|
"text"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"user": {
|
||||||
|
"bsonType": ["int", "long"],
|
||||||
|
"description": "Telegram ID of user"
|
||||||
|
},
|
||||||
|
"completed": {
|
||||||
|
"bsonType": "bool",
|
||||||
|
"description": "Whether spoiler is a completed one"
|
||||||
|
},
|
||||||
|
"category": {
|
||||||
|
"bsonType": ["string", "null"],
|
||||||
|
"enum": ["nsfw", "deanon", "other"],
|
||||||
|
"description": "Spoiler's category"
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"bsonType": ["string", "null"],
|
||||||
|
"description": "Spoiler's description"
|
||||||
|
},
|
||||||
|
"photo": {
|
||||||
|
"bsonType": ["string", "null"],
|
||||||
|
"description": "Spoilered photo"
|
||||||
|
},
|
||||||
|
"video": {
|
||||||
|
"bsonType": ["string", "null"],
|
||||||
|
"description": "Spoilered video"
|
||||||
|
},
|
||||||
|
"audio": {
|
||||||
|
"bsonType": ["string", "null"],
|
||||||
|
"description": "Spoilered audio"
|
||||||
|
},
|
||||||
|
"animation": {
|
||||||
|
"bsonType": ["string", "null"],
|
||||||
|
"description": "Spoilered animation/GIF"
|
||||||
|
},
|
||||||
|
"document": {
|
||||||
|
"bsonType": ["string", "null"],
|
||||||
|
"description": "Spoilered document/file"
|
||||||
|
},
|
||||||
|
"caption": {
|
||||||
|
"bsonType": ["string", "null"],
|
||||||
|
"description": "Spoilered caption for media"
|
||||||
|
},
|
||||||
|
"text": {
|
||||||
|
"bsonType": ["string", "null"],
|
||||||
|
"description": "Spoilered text"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@@ -1,6 +1,43 @@
|
|||||||
{
|
{
|
||||||
"$jsonSchema": {
|
"$jsonSchema": {
|
||||||
"required": [],
|
"required": [
|
||||||
"properties": {}
|
"user",
|
||||||
|
"date",
|
||||||
|
"admin",
|
||||||
|
"sponsorship",
|
||||||
|
"sponsorship.streamer",
|
||||||
|
"sponsorship.expires",
|
||||||
|
"sponsorship.proof",
|
||||||
|
"sponsorship.label"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"user": {
|
||||||
|
"bsonType": ["int", "long"],
|
||||||
|
"description": "Telegram ID of user"
|
||||||
|
},
|
||||||
|
"date": {
|
||||||
|
"bsonType": "date",
|
||||||
|
"description": "Date when sponsorship was accepted"
|
||||||
|
},
|
||||||
|
"admin": {
|
||||||
|
"bsonType": ["int", "long"],
|
||||||
|
"description": "Telegram ID of admin that accepted the sponsorship"
|
||||||
|
},
|
||||||
|
"sponsorship": {
|
||||||
|
"bsonType": "object"
|
||||||
|
},
|
||||||
|
"sponsorship.streamer": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"sponsorship.expires": {
|
||||||
|
"bsonType": "date"
|
||||||
|
},
|
||||||
|
"sponsorship.proof": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"sponsorship.label": {
|
||||||
|
"bsonType": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
6
validation/tmp.json
Normal file
6
validation/tmp.json
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"$jsonSchema": {
|
||||||
|
"required": [],
|
||||||
|
"properties": {}
|
||||||
|
}
|
||||||
|
}
|
@@ -1,6 +1,47 @@
|
|||||||
{
|
{
|
||||||
"$jsonSchema": {
|
"$jsonSchema": {
|
||||||
"required": [],
|
"required": [
|
||||||
"properties": {}
|
"user",
|
||||||
|
"admin",
|
||||||
|
"date",
|
||||||
|
"reason",
|
||||||
|
"active",
|
||||||
|
"revoke_date"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"user": {
|
||||||
|
"bsonType": [
|
||||||
|
"int",
|
||||||
|
"long"
|
||||||
|
],
|
||||||
|
"description": "Telegram ID of user"
|
||||||
|
},
|
||||||
|
"admin": {
|
||||||
|
"bsonType": [
|
||||||
|
"int",
|
||||||
|
"long"
|
||||||
|
],
|
||||||
|
"description": "Telegram ID of admin"
|
||||||
|
},
|
||||||
|
"date": {
|
||||||
|
"bsonType": "date",
|
||||||
|
"description": "Date and time of getting"
|
||||||
|
},
|
||||||
|
"reason": {
|
||||||
|
"bsonType": "string",
|
||||||
|
"description": "Broken rule or admin's comment"
|
||||||
|
},
|
||||||
|
"active": {
|
||||||
|
"bsonType": "bool",
|
||||||
|
"description": "Whether warning is still present"
|
||||||
|
},
|
||||||
|
"revoke_date": {
|
||||||
|
"bsonType": [
|
||||||
|
"date",
|
||||||
|
"null"
|
||||||
|
],
|
||||||
|
"description": "Date when warning got inactive"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
Reference in New Issue
Block a user