Compare commits

...

12 Commits
v1.1 ... v1.6

Author SHA1 Message Date
f4e74b5bc6 Added trailing slashes 2023-06-29 16:03:49 +02:00
7b8434ae71 Updated to 1.6 2023-06-29 15:59:06 +02:00
8c2054f496 Improved init flexibility 2023-06-29 15:58:50 +02:00
fe9cc3674f Removed duplicate py version 2023-06-29 15:58:20 +02:00
c71a7555f9 Updated to 1.5 2023-06-26 13:29:47 +02:00
cb755faa9a Added scopes_placeholders 2023-06-26 13:29:26 +02:00
1859d0532c Updated to 1.4 2023-06-26 13:06:55 +02:00
ebce8e0141 Fixed workers and max_concurrent_transmissions 2023-06-26 13:06:23 +02:00
9af6d5cb7c Integrated the scheduler 2023-06-26 12:45:39 +02:00
7f054a6d93 Updated to 1.3 2023-06-26 12:31:52 +02:00
d6e3ecb564 Updated to 1.2 2023-06-26 12:26:13 +02:00
e93e73bca9 Added missing import 2023-06-26 12:25:55 +02:00
4 changed files with 100 additions and 36 deletions

8
.gitignore vendored
View File

@@ -161,8 +161,8 @@ cython_debug/
#.idea/
# Project
venv
venv_linux
venv_windows
venv/
venv_linux/
venv_windows/
.vscode
.vscode/

View File

@@ -1,7 +1,9 @@
__name__ = "libbot"
__version__ = "1.1"
__version__ = "1.6"
__license__ = "GPL3"
__author__ = "Profitroll"
from .__main__ import *
from . import sync
from . import i18n
from . import pyrogram

View File

@@ -1,12 +1,15 @@
import asyncio
import logging
from datetime import datetime, timedelta
from os import getpid
from os import cpu_count, getpid
from pathlib import Path
from time import time
from typing import List, Union
from typing import Any, Dict, List, Union
try:
import pyrogram
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.schedulers.background import BackgroundScheduler
from pyrogram.client import Client
from pyrogram.errors import BadRequest
from pyrogram.handlers.message_handler import MessageHandler
@@ -40,29 +43,69 @@ logger = logging.getLogger(__name__)
class PyroClient(Client):
def __init__(self):
with open("config.json", "r", encoding="utf-8") as f:
self.config: dict = loads(f.read())
def __init__(
self,
name: str = "bot_client",
config: Union[Dict[str, Any], None] = None,
config_path: Union[str, Path] = Path("config.json"),
api_id: Union[int, None] = None,
api_hash: Union[str, None] = None,
bot_token: Union[str, None] = None,
workers: int = min(32, cpu_count() + 4),
locales_root: Union[str, Path, None] = None,
plugins_root: str = "plugins",
plugins_exclude: Union[List[str], None] = None,
sleep_threshold: int = 120,
max_concurrent_transmissions: int = 1,
commands_source: Union[Dict[str, dict], None] = None,
scheduler: Union[AsyncIOScheduler, BackgroundScheduler, None] = None,
):
if config is None:
with open(config_path, "r", encoding="utf-8") as f:
self.config: dict = loads(f.read())
else:
self.config = config
super().__init__(
name="bot_client",
api_id=self.config["bot"]["api_id"],
api_hash=self.config["bot"]["api_hash"],
bot_token=self.config["bot"]["bot_token"],
# Workers should be commented when using convopyro, otherwise
name=name,
api_id=self.config["bot"]["api_id"] if api_id is None else api_id,
api_hash=self.config["bot"]["api_hash"] if api_hash is None else api_hash,
bot_token=self.config["bot"]["bot_token"]
if bot_token is None
else bot_token,
# Workers should be `min(32, cpu_count() + 4)`, otherwise
# handlers land in another event loop and you won't see them
workers=self.config["bot"]["workers"],
plugins=dict(root="plugins", exclude=self.config["disabled_plugins"]),
sleep_threshold=120,
workers=self.config["bot"]["workers"]
if "workers" in self.config["bot"]
else workers,
plugins=dict(
root=plugins_root,
exclude=self.config["disabled_plugins"]
if plugins_exclude is None
else plugins_exclude,
),
sleep_threshold=sleep_threshold,
max_concurrent_transmissions=self.config["bot"][
"max_concurrent_transmissions"
],
]
if "max_concurrent_transmissions" in self.config["bot"]
else max_concurrent_transmissions,
)
self.owner: int = self.config["bot"]["owner"]
self.commands: List[PyroCommand] = []
self.commands_source: Dict[str, dict] = (
self.config["commands"] if commands_source is None else commands_source
)
self.scoped_commands: bool = self.config["bot"]["scoped_commands"]
self.start_time: float = 0
self.bot_locale: BotLocale = BotLocale(Path(self.config["locations"]["locale"]))
self.bot_locale: BotLocale = BotLocale(
(
Path(self.config["locations"]["locale"])
if locales_root is None
else locales_root
)
)
self.default_locale: str = self.bot_locale.default
self.locales: dict = self.bot_locale.locales
@@ -70,7 +113,11 @@ class PyroClient(Client):
self.in_all_locales = self.bot_locale.in_all_locales
self.in_every_locale = self.bot_locale.in_every_locale
async def start(self, scheduler):
self.scheduler: Union[AsyncIOScheduler, BackgroundScheduler, None] = scheduler
self.scopes_placeholders: Dict[str, int] = {"owner": self.owner}
async def start(self, register_commands: bool = True):
await super().start()
self.start_time = time()
@@ -89,28 +136,42 @@ class PyroClient(Client):
text=f"Bot started PID `{getpid()}`",
)
scheduler.add_job(
self.register_commands,
trigger="date",
run_date=datetime.now() + timedelta(seconds=5),
kwargs={"command_sets": await self.collect_commands()},
)
if self.scheduler is None:
return
scheduler.start()
if register_commands:
self.scheduler.add_job(
self.register_commands,
trigger="date",
run_date=datetime.now() + timedelta(seconds=5),
kwargs={"command_sets": await self.collect_commands()},
)
self.scheduler.start()
except BadRequest:
logger.warning("Unable to send message to report chat.")
async def stop(self):
async def stop(self, exit_completely: bool = True):
try:
await self.send_message(
chat_id=self.config["reports"]["chat_id"],
text=f"Bot stopped with PID `{getpid()}`",
)
await asyncio.sleep(0.5)
except BadRequest:
logger.warning("Unable to send message to report chat.")
await super().stop()
logger.warning("Bot stopped with PID %s.", getpid())
if exit_completely:
try:
exit()
except SystemExit as exp:
raise SystemExit(
"Bot has been shut down, this is not an application error!"
) from exp
async def collect_commands(self) -> Union[List[CommandSet], None]:
"""Gather list of the bot's commands
@@ -126,7 +187,7 @@ class PyroClient(Client):
command_sets = []
# Iterate through all commands in config
for command, contents in self.config["commands"].items():
for command, contents in self.commands_source.items():
# Iterate through all scopes of a command
for scope in contents["scopes"]:
if dumps(scope) not in scopes:
@@ -151,8 +212,9 @@ class PyroClient(Client):
scope_dict = loads(scope)
# Replace "owner" in the bot scope with owner's id
if "chat_id" in scope_dict and scope_dict["chat_id"] == "owner":
scope_dict["chat_id"] = self.owner
for placeholder, chat_id in self.scopes_placeholders.items():
if "chat_id" in scope_dict and scope_dict["chat_id"] == placeholder:
scope_dict["chat_id"] = chat_id
# Create object with the same name and args from the dict
try:

View File

@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "libbot"
version = "1.1"
version = "1.6"
authors = [{ name = "Profitroll" }]
description = "Universal bot library with functions needed for basic Discord/Telegram bot development."
readme = "README.md"
@@ -25,8 +25,8 @@ classifiers = [
dependencies = ["aiofiles~=23.1.0"]
[project.optional-dependencies]
pycord = ["py-cord>=2.0.0"]
pyrogram = ["pyrogram>=2.0.0"]
pycord = ["py-cord~=2.4.1"]
pyrogram = ["pyrogram~=2.0.106", "apscheduler~=3.10.1"]
speed = ["ujson~=5.8.0"]
[project.urls]
@@ -48,7 +48,7 @@ packages = [
[tool.setuptools_scm]
[tool.black]
target-version = ['py38', 'py38', 'py39', 'py310', 'py311']
target-version = ['py38', 'py39', 'py310', 'py311']
[tool.isort]
profile = "black"