Compare commits

...

8 Commits

Author SHA1 Message Date
Profitroll
93cfc75d1d Column change 2022-12-10 15:53:41 +01:00
Profitroll
efe3c8338e Scheduler changes 2022-12-10 15:53:30 +01:00
Profitroll
5b5b38a394 Fixed starlette version 2022-12-10 15:53:19 +01:00
Profitroll
09cd36d5ba Scheduler refactor 2022-12-10 15:52:34 +01:00
Profitroll
4e8fb00475 Changed used columns 2022-12-10 15:52:07 +01:00
Profitroll
d6161515c1 Improved registration logic 2022-12-10 15:51:48 +01:00
Profitroll
b5058c00e1 Optimized imports, removed scheduler 2022-12-10 15:51:37 +01:00
Profitroll
dc92a3d82a Updated requirements 2022-12-10 15:13:12 +01:00
8 changed files with 101 additions and 57 deletions

View File

@ -1,6 +1,6 @@
from typing import Union
from pyrogram.types import User, ChatMember
from modules.database import col_users, col_context, col_warnings, col_subscriptions
from modules.database import col_users, col_context, col_warnings, col_applications, col_sponsorships
class UserNotFoundError(Exception):
"""HoloUser could not find user with such an ID in database"""

View File

@ -4,8 +4,6 @@
"owner": 0,
"bot_id": 0,
"age_allowed": 0,
"birthdays_notify": true,
"birthdays_time": "09:00",
"api": "http://example.com",
"inline_preview_count": 7,
"admin_group": 0,
@ -28,6 +26,16 @@
"size": 512,
"location": "logs"
},
"scheduler": {
"birthdays": {
"time": 9,
"enabled": true
},
"sponsorships": {
"time": 9,
"enabled": true
}
},
"locations": {
"cache": "cache",
"locale": "locale"

54
main.py
View File

@ -1,10 +1,6 @@
from threading import Thread
from time import time
from os import getpid, path
from modules.birthdays import check_birthdays
from os import getpid
from modules.utils import *
from modules.inline import *
from schedule import run_pending, every
from app import app
from modules.commands_register import commands_register
@ -38,6 +34,8 @@ from modules.handlers.group_join import *
from modules.handlers.welcome import *
from modules.handlers.everything import *
from modules.scheduled import *
if __name__ == "__main__":
logWrite(f"Starting up with pid {pid}")
@ -46,33 +44,41 @@ if __name__ == "__main__":
# I did compare performance, almost no difference and it's much more useful this way. Change my mind.
app.start()
if configGet("birthdays_notify"):
# if configGet("birthdays_notify"):
every().day.at(configGet("birthdays_time")).do(check_birthdays, app)
# 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()
# # 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()
app.send_message(configGet("owner"), f"Starting up with pid `{pid}`")
try:
app.send_message(configGet("owner"), f"Starting up with pid `{pid}`")
except bad_request_400.PeerIdInvalid:
logWrite(f"Could not send startup message to bot owner. Perhaps user has not started the bot yet.")
commands_register(app)
scheduler.start()
idle()
app.send_message(configGet("owner"), f"Shutting with pid `{pid}`")
try:
app.send_message(configGet("owner"), f"Shutting with pid `{pid}`")
except bad_request_400.PeerIdInvalid:
logWrite(f"Could not send shutdown message to bot owner. Perhaps user has not started the bot yet.")
app.stop()

View File

@ -1,18 +0,0 @@
from datetime import datetime
from os import fsdecode, listdir, sep
from modules.utils import configGet, jsonLoad, locale
from dateutil.relativedelta import relativedelta
def check_birthdays(app):
for user_file in listdir(f"{configGet('data', 'locations')}{sep}users{sep}"):
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 = app.get_users(int(user_file.replace(".json", "")))
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

View File

@ -1,3 +1,4 @@
from modules.logging import logWrite
from modules.utils import configGet
from pyrogram.types import BotCommand, BotCommandScopeChat
from pyrogram.errors import bad_request_400
@ -24,16 +25,25 @@ def commands_register(app):
except bad_request_400.PeerIdInvalid:
pass
app.set_bot_commands(commands_admin_list, scope=BotCommandScopeChat(chat_id=configGet("owner")))
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]))
app.set_bot_commands(commands_group_admin_list, scope=BotCommandScopeChat(chat_id=configGet("admin_group")))
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]))
app.set_bot_commands(commands_group_destination_list, scope=BotCommandScopeChat(chat_id=configGet("destination_group")))
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.")

View File

@ -25,7 +25,7 @@ db = db_client.get_database(name=db_config["name"])
collections = db.list_collection_names()
for collection in ["users", "context", "messages", "warnings", "subscriptions"]:
for collection in ["users", "context", "messages", "warnings", "applications", "sponsorships"]:
if not collection in collections:
db.create_collection(collection)
@ -33,4 +33,5 @@ col_users = db.get_collection("users")
col_context = db.get_collection("context")
col_messages = db.get_collection("messages")
col_warnings = db.get_collection("warnings")
col_subscriptions = db.get_collection("subscriptions")
col_applications = db.get_collection("applications")
col_sponsorships = db.get_collection("sponsorships")

35
modules/scheduled.py Normal file
View File

@ -0,0 +1,35 @@
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
from os import fsdecode, listdir, sep
from app import app
from modules.utils import configGet, jsonLoad, locale, logWrite
from dateutil.relativedelta import relativedelta
from modules.database import col_applications
scheduler = BackgroundScheduler()
# for user_file in listdir(f"{configGet('data', 'locations')}{sep}users{sep}"):
# 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(trigger="cron", hour=configGet("time", "scheduler", "birthdays"))
async def check_birthdays():
for entry in col_applications.find({"2": datetime.now().strftime("%d.%m.%Y")}):
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
logWrite(f"Notified admins about {entry['user']}'s birthday")
logWrite("Birthdays check performed")
if configGet("enabled", "scheduler", "sponsorships"):
@scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "sponsorships"))
async def check_sponsors():
logWrite("Sponsorships check performed")

View File

@ -1,7 +1,9 @@
pyrogram>=2.0.59
tgcrypto>=1.2.4
ujson>=5.5.0
psutil>=5.9.2
schedule
fastapi
uvicorn[standard]
APScheduler==3.9.1.post1
fastapi==0.88.0
psutil==5.9.4
pymongo==4.3.3
Pyrogram==2.0.69
tgcrypto==1.2.5
python_dateutil==2.8.2
starlette==0.22.0
ujson==5.6.0