Compare commits

..

No commits in common. "93cfc75d1dbde2646fdbd7742ba0d165a4dcd96e" and "bd2a3fc81c153680054e1eede30c3248a9f4772d" have entirely different histories.

8 changed files with 57 additions and 101 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_applications, col_sponsorships
from modules.database import col_users, col_context, col_warnings, col_subscriptions
class UserNotFoundError(Exception):
"""HoloUser could not find user with such an ID in database"""

View File

@ -4,6 +4,8 @@
"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,
@ -26,16 +28,6 @@
"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,6 +1,10 @@
from os import getpid
from threading import Thread
from time import time
from os import getpid, path
from modules.birthdays import check_birthdays
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
@ -34,8 +38,6 @@ 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}")
@ -44,41 +46,33 @@ 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()
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.")
app.send_message(configGet("owner"), f"Starting up with pid `{pid}`")
commands_register(app)
scheduler.start()
idle()
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.send_message(configGet("owner"), f"Shutting with pid `{pid}`")
app.stop()

18
modules/birthdays.py Normal file
View File

@ -0,0 +1,18 @@
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,4 +1,3 @@
from modules.logging import logWrite
from modules.utils import configGet
from pyrogram.types import BotCommand, BotCommandScopeChat
from pyrogram.errors import bad_request_400
@ -25,25 +24,16 @@ def commands_register(app):
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.")
app.set_bot_commands(commands_admin_list, scope=BotCommandScopeChat(chat_id=configGet("owner")))
# 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.")
app.set_bot_commands(commands_group_admin_list, scope=BotCommandScopeChat(chat_id=configGet("admin_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.")
app.set_bot_commands(commands_group_destination_list, scope=BotCommandScopeChat(chat_id=configGet("destination_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", "applications", "sponsorships"]:
for collection in ["users", "context", "messages", "warnings", "subscriptions"]:
if not collection in collections:
db.create_collection(collection)
@ -33,5 +33,4 @@ 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_applications = db.get_collection("applications")
col_sponsorships = db.get_collection("sponsorships")
col_subscriptions = db.get_collection("subscriptions")

View File

@ -1,35 +0,0 @@
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,9 +1,7 @@
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
pyrogram>=2.0.59
tgcrypto>=1.2.4
ujson>=5.5.0
psutil>=5.9.2
schedule
fastapi
uvicorn[standard]