Skip to content

Commit 0ae7e38

Browse files
committed
update
1 parent 8a104be commit 0ae7e38

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

74 files changed

+1632
-1755
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,3 +142,5 @@ backup
142142

143143
*/plugins/custom/*
144144
!*/plugins/custom/__init__.py
145+
146+
.ruff*

Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
# Please read the GNU Affero General Public License in
66
# < https://github.com/kastaid/getter/blob/main/LICENSE/ >.
77

8-
FROM python:3.10-slim-bullseye
8+
FROM python:3.12-slim-bookworm
99

1010
ENV TZ=Asia/Jakarta \
1111
TERM=xterm-256color \

getter/__init__.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# ruff: noqa: F401
12
# getter < https://t.me/kastaid >
23
# Copyright (C) 2022-present kastaid
34
#
@@ -28,9 +29,6 @@
2829
sys.exit(1)
2930
if "/com.termux" in sys.executable:
3031
print("You are detected using Termux, maybe the functionality will not work normally.")
31-
if sys.version_info < (3, 10, 0):
32-
print(f"You must use at least Python version 3.10.0, currently {__pyversion__}. Quitting...")
33-
sys.exit(1)
3432

3533
Root: Path = Path(__file__).parent.parent
3634
LOOP = uvloop.new_event_loop()

getter/__main__.py

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,32 +6,34 @@
66
# < https://github.com/kastaid/getter/blob/main/LICENSE/ >.
77

88
import sys
9+
from asyncio import gather
910
from importlib import import_module
1011
from time import monotonic
1112
from requests.packages import urllib3
1213
import getter.core.patched # noqa
13-
from getter import (
14+
from . import (
1415
__license__,
1516
__copyright__,
1617
__version__,
1718
__tlversion__,
1819
__layer__,
1920
__pyversion__,
2021
)
21-
from getter.config import Var, hl
22-
from getter.core.base_client import getter_app
23-
from getter.core.helper import plugins_help
24-
from getter.core.property import do_not_remove_credit
25-
from getter.core.startup import (
22+
from .config import Var, hl
23+
from .core.base_client import getter_app
24+
from .core.db import db_connect
25+
from .core.helper import plugins_help, jdata
26+
from .core.property import do_not_remove_credit
27+
from .core.startup import (
2628
trap,
2729
migrations,
2830
autopilot,
2931
verify,
3032
autous,
3133
finishing,
3234
)
33-
from getter.core.utils import time_formatter
34-
from getter.logger import LOG
35+
from .core.utils import time_formatter
36+
from .logger import LOG
3537

3638
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
3739

@@ -46,6 +48,8 @@
4648

4749

4850
async def main() -> None:
51+
await db_connect()
52+
await jdata.sudo_users()
4953
migrations()
5054
await autopilot()
5155
await verify()
@@ -54,14 +58,19 @@ async def main() -> None:
5458
plugins = getter_app.all_plugins
5559
for p in plugins:
5660
try:
57-
if p["path"].startswith("custom"):
58-
plugin = "getter.plugins." + p["path"]
59-
else:
60-
plugin = "getter." + p["path"]
61+
plugin = (
62+
"".join(("getter.plugins.", p["path"]))
63+
if p["path"].startswith("custom")
64+
else "".join(("getter.", p["path"]))
65+
)
6166
import_module(plugin)
6267
LOG.success("[+] " + p["name"])
6368
except Exception as err:
6469
LOG.exception(f"[-] {p['name']} : {err}")
70+
from .plugins.afk import handle_afk
71+
from .plugins.pmpermit import handle_pmpermit
72+
73+
await gather(*[handle_afk(), handle_pmpermit()])
6574
loaded_time = time_formatter((monotonic() - load) * 1000)
6675
loaded_msg = ">> Loaded Plugins: {} , Commands: {} (took {}) : {}".format(
6776
plugins_help.count,
@@ -71,13 +80,8 @@ async def main() -> None:
7180
)
7281
LOG.info(loaded_msg)
7382
do_not_remove_credit()
74-
python_msg = ">> Python Version - {}".format(
75-
__pyversion__,
76-
)
77-
telethon_msg = ">> Telethon Version - {} [Layer: {}]".format(
78-
__tlversion__,
79-
__layer__,
80-
)
83+
python_msg = f">> Python Version - {__pyversion__}"
84+
telethon_msg = f">> Telethon Version - {__tlversion__} [Layer: {__layer__}]"
8185
launch_msg = ">> 🚀 Getter v{} launch ({} - {}) in {} with handler [ {}ping ]".format(
8286
__version__,
8387
getter_app.full_name,

getter/config.py

Lines changed: 16 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,25 @@
55
# Please read the GNU Affero General Public License in
66
# < https://github.com/kastaid/getter/blob/main/LICENSE/ >.
77

8-
import typing
98
from base64 import b64decode
109
from os import getenv
1110
from string import ascii_lowercase
11+
from typing import Any
12+
from zoneinfo import ZoneInfo
1213
from dotenv import load_dotenv, find_dotenv
13-
from pytz import timezone
1414

1515
load_dotenv(find_dotenv("config.env"))
1616

1717

18-
def tobool(val: str) -> typing.Optional[int]:
18+
def tobool(val: str) -> int | None:
1919
"""
2020
Convert a string representation of truth to true (1) or false (0).
2121
https://github.com/python/cpython/blob/main/Lib/distutils/util.py
2222
"""
2323
val = val.lower()
2424
if val in ("y", "yes", "t", "true", "on", "1"):
2525
return 1
26-
elif val in ("n", "no", "f", "false", "off", "0"):
26+
if val in ("n", "no", "f", "false", "off", "0"):
2727
return 0
2828
raise ValueError("invalid truth value %r" % (val,))
2929

@@ -34,15 +34,10 @@ class Var:
3434
API_HASH: str = getenv("API_HASH", "").strip()
3535
STRING_SESSION: str = getenv("STRING_SESSION", "").strip()
3636
DATABASE_URL: str = (
37-
lambda c: c.replace(c.split("://")[0], "postgresql+psycopg2")
38-
if c.startswith(
39-
(
40-
"postgres:",
41-
"postgresql:",
42-
)
37+
lambda c: (
38+
c.replace(c.split("://")[0], "postgresql+asyncpg") if c.startswith(("postgres:", "postgresql:")) else c
4339
)
44-
else c
45-
)(getenv("DATABASE_URL", "sqlite:///./getter.db").strip())
40+
)(getenv("DATABASE_URL", "sqlite+aiosqlite:///./getter.db").strip())
4641
BOTLOGS: int = int(getenv("BOTLOGS", "0").strip())
4742
HANDLER: str = getenv("HANDLER", ".").strip()
4843
NO_HANDLER: bool = tobool(getenv("NO_HANDLER", "false").strip())
@@ -53,12 +48,12 @@ class Var:
5348

5449

5550
try:
56-
tz = timezone(Var.TZ)
51+
tz = ZoneInfo(Var.TZ)
5752
except BaseException:
5853
_ = "Asia/Jakarta"
5954
print("An error or unknown TZ :", Var.TZ)
6055
print("Set default TZ as", _)
61-
tz = timezone(_)
56+
tz = ZoneInfo(_)
6257

6358
if not (
6459
Var.HANDLER.lower().startswith(
@@ -81,16 +76,16 @@ class Var:
8176
)
8277
):
8378
hl = "."
84-
print("Your HANDLER [ {} ] is not supported.".format(Var.HANDLER))
79+
print(f"Your HANDLER [ {Var.HANDLER} ] is not supported.")
8580
print("Set default HANDLER as dot [ .command ]")
8681
else:
8782
hl = "".join(Var.HANDLER.split())
8883

89-
BOTLOGS_CACHE: typing.Set[int] = set()
90-
DEV_CMDS: typing.Dict[str, typing.List[str]] = {}
91-
SUDO_CMDS: typing.Dict[str, typing.List[str]] = {}
92-
INVITE_WORKER: typing.Dict[str, typing.Any] = {}
93-
CALLS: typing.Dict[int, typing.Any] = {}
84+
BOTLOGS_CACHE: set[int] = set()
85+
DEV_CMDS: dict[str, list[str]] = {}
86+
SUDO_CMDS: dict[str, list[str]] = {}
87+
INVITE_WORKER: dict[str, Any] = {}
88+
CALLS: dict[int, Any] = {}
9489
TESTER = {5215824623}
9590
# va, vn, en, xl
9691
DEVS = {
@@ -101,4 +96,4 @@ class Var:
10196
-1001699144606,
10297
-1001700971911,
10398
}
104-
del typing, b64decode, ascii_lowercase, load_dotenv, find_dotenv, timezone
99+
del Any, b64decode, ascii_lowercase, ZoneInfo, load_dotenv, find_dotenv

getter/core/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# ruff: noqa: F401, F403
12
# getter < https://t.me/kastaid >
23
# Copyright (C) 2022-present kastaid
34
#

getter/core/base_client.py

Lines changed: 37 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,13 @@
88
import importlib.util
99
import os
1010
import sys
11-
import typing
1211
from asyncio import sleep, Future
12+
from collections.abc import Coroutine
1313
from inspect import getmembers
1414
from platform import version, machine
1515
from random import choice
1616
from time import time
17+
from typing import Any, NoReturn
1718
from telethon.client.telegramclient import TelegramClient
1819
from telethon.errors import (
1920
ApiIdInvalidError,
@@ -32,12 +33,19 @@
3233
__version__,
3334
LOOP,
3435
)
35-
from getter.config import Var, DEVS
36-
from getter.core.db import sgvar
37-
from getter.core.functions import display_name
38-
from getter.core.property import do_not_remove_credit, get_blacklisted
39-
from getter.core.utils import time_formatter
36+
from getter.config import (
37+
Var,
38+
tz,
39+
hl,
40+
INVITE_WORKER,
41+
DEVS,
42+
)
4043
from getter.logger import LOG, TelethonLogger
44+
from .db import sgvar
45+
from .functions import display_name
46+
from .helper import plugins_help
47+
from .property import do_not_remove_credit, get_blacklisted
48+
from .utils import time_formatter
4149

4250

4351
class ReverseList(list):
@@ -48,10 +56,10 @@ def __iter__(self):
4856
class KastaClient(TelegramClient):
4957
def __init__(
5058
self,
51-
session: typing.Union[str, Session],
52-
api_id: typing.Optional[int] = None,
53-
api_hash: typing.Optional[str] = None,
54-
bot_token: typing.Optional[str] = None,
59+
session: str | Session,
60+
api_id: int | None = None,
61+
api_hash: str | None = None,
62+
bot_token: str | None = None,
5563
*args,
5664
**kwargs,
5765
):
@@ -75,14 +83,10 @@ def __init__(
7583
self.dc_id = self.session.dc_id
7684

7785
def __repr__(self):
78-
return "<Kasta.Client:\n self: {}\n id: {}\n bot: {}\n>".format(
79-
self.full_name,
80-
self.uid,
81-
self._bot,
82-
)
86+
return f"<Kasta.Client:\n self: {self.full_name}\n id: {self.uid}\n bot: {self._bot}\n>"
8387

8488
@property
85-
def __dict__(self) -> typing.Optional[dict]:
89+
def __dict__(self) -> dict | None:
8690
if self.me:
8791
return self.me.to_dict()
8892

@@ -117,19 +121,9 @@ async def start_client(self, **kwargs) -> None:
117121
fallbacks=None,
118122
)
119123
if self.uid in KASTA_BLACKLIST:
120-
self.log.error(
121-
"({} - {}) YOU ARE BLACKLISTED !!".format(
122-
me,
123-
self.uid,
124-
)
125-
)
124+
self.log.error(f"({me} - {self.uid}) YOU ARE BLACKLISTED !!")
126125
sys.exit(1)
127-
self.log.success(
128-
"Logged in as {} [{}]".format(
129-
me,
130-
self.uid,
131-
)
132-
)
126+
self.log.success(f"Logged in as {me} [{self.uid}]")
133127
except (ValueError, ApiIdInvalidError):
134128
self.log.critical("API_ID and API_HASH combination does not match, please re-check! Quitting...")
135129
sys.exit(1)
@@ -145,10 +139,10 @@ async def start_client(self, **kwargs) -> None:
145139
self.log.exception(f"[KastaClient] - {err}")
146140
sys.exit(1)
147141

148-
def run_in_loop(self, func: typing.Coroutine[typing.Any, typing.Any, None]) -> typing.Any:
142+
def run_in_loop(self, func: Coroutine[Any, Any, None]) -> Any:
149143
return self.loop.run_until_complete(func)
150144

151-
def run(self) -> typing.NoReturn:
145+
def run(self) -> NoReturn:
152146
try:
153147
self.run_until_disconnected()
154148
except InvalidBufferError as err:
@@ -174,10 +168,13 @@ def add_handler(
174168
return
175169
self.add_event_handler(func, *args, **kwargs)
176170

177-
def reboot(self, message: typ.Message) -> typing.NoReturn:
171+
async def reboot(
172+
self,
173+
message: typ.Message,
174+
) -> NoReturn:
178175
try:
179176
chat_id = message.chat_id or message.from_id
180-
sgvar("_reboot", f"{chat_id}|{message.id}")
177+
await sgvar("_reboot", f"{chat_id}|{message.id}")
181178
except BaseException:
182179
pass
183180
try:
@@ -200,6 +197,12 @@ def load_plugin(
200197
name = f"getter.plugins.custom.{plug}"
201198
spec = importlib.util.spec_from_file_location(name, path)
202199
mod = importlib.util.module_from_spec(spec)
200+
mod.Var = Var
201+
mod.tz = tz
202+
mod.hl = hl
203+
mod.INVITE_WORKER = INVITE_WORKER
204+
mod.DEVS = DEVS
205+
mod.plugins_help = plugins_help
203206
spec.loader.exec_module(mod)
204207
self._plugins[plug] = mod
205208
self.log.success(f"Successfully loaded custom plugin {plug}!")
@@ -215,14 +218,14 @@ def unload_plugin(
215218
) -> None:
216219
name = self._plugins[plugin].__name__
217220
for x in reversed(range(len(self._event_builders))):
218-
ev, cb = self._event_builders[x]
221+
_, cb = self._event_builders[x]
219222
if cb.__module__ == name:
220223
del self._event_builders[x]
221224
del self._plugins[plugin]
222225
self.log.success(f"Removed custom plugin {plugin}!")
223226

224227
@property
225-
def all_plugins(self) -> typing.List[typing.Dict[str, str]]:
228+
def all_plugins(self) -> list[dict[str, str]]:
226229
return [
227230
{
228231
"path": ".".join(str(_.resolve()).replace(".py", "").split("/")[-2:]),

0 commit comments

Comments
 (0)