This repository has been archived on 2024-08-21. You can view files and clone it, but cannot push or open issues or pull requests.
TelegramPoster/main.py

399 lines
18 KiB
Python
Raw Normal View History

2022-08-08 15:53:26 +03:00
import os
import random
import shutil
import sys
from threading import Thread
import time
import traceback
2022-08-11 10:59:30 +03:00
from pathlib import Path
2022-08-08 15:53:26 +03:00
2022-08-09 12:18:23 +03:00
from modules.logging import logWrite
2022-08-10 14:08:15 +03:00
from modules.utils import configGet, jsonLoad, jsonSave, killProc, locale
2022-08-09 12:18:23 +03:00
2022-08-09 14:02:52 +03:00
# Args =====================================================================================================================================
2022-08-09 12:18:23 +03:00
if "--move-sent" in sys.argv:
for entry in jsonLoad(configGet("index", "locations"))["sent"]:
try:
shutil.move(configGet("queue", "locations")+os.sep+entry, configGet("sent", "locations")+os.sep+entry)
except FileNotFoundError:
2022-08-10 14:08:15 +03:00
logWrite(locale("move_sent_doesnt_exist", "console", locale=configGet("locale")).format(entry))
2022-08-09 12:18:23 +03:00
except Exception as exp:
2022-08-10 14:08:15 +03:00
logWrite(locale("move_sent_doesnt_exception", "console", locale=configGet("locale")).format(entry, exp))
logWrite(locale("move_sent_completed", "console", locale=configGet("locale")))
2022-08-09 12:18:23 +03:00
if "--cleanup" in sys.argv:
2022-08-09 12:45:52 +03:00
if "--confirm" in sys.argv:
2022-08-09 12:56:01 +03:00
index = jsonLoad(configGet("index", "locations"))
for entry in index["sent"]:
2022-08-09 12:18:23 +03:00
try:
2022-08-09 12:45:52 +03:00
try:
os.remove(configGet("queue", "locations")+os.sep+entry)
except FileNotFoundError:
pass
try:
os.remove(configGet("sent", "locations")+os.sep+entry)
except FileNotFoundError:
pass
except Exception as exp:
2022-08-10 14:08:15 +03:00
logWrite(locale("cleanup_exception", "console", locale=configGet("locale")).format(entry, exp))
2022-08-09 12:56:01 +03:00
jsonSave(index, jsonLoad(configGet("index", "locations")))
2022-08-10 14:08:15 +03:00
logWrite(locale("cleanup_completed", "console", locale=configGet("locale")))
2022-08-09 12:45:52 +03:00
else:
2022-08-10 14:08:15 +03:00
logWrite(locale("cleanup_unathorized", "console", locale=configGet("locale")))
2022-08-09 12:18:23 +03:00
2022-08-09 12:58:40 +03:00
if "--cleanup-index" in sys.argv:
if "--confirm" in sys.argv:
index = jsonLoad(configGet("index", "locations"))
index["sent"] = []
jsonSave(index, jsonLoad(configGet("index", "locations")))
2022-08-10 14:08:15 +03:00
logWrite(locale("cleanup_index_completed", "console", locale=configGet("locale")))
2022-08-09 12:58:40 +03:00
else:
2022-08-10 14:08:15 +03:00
logWrite(locale("cleanup_index_unathorized", "console", locale=configGet("locale")))
2022-08-09 12:58:40 +03:00
2022-08-09 12:18:23 +03:00
if "--norun" in sys.argv:
2022-08-10 14:08:15 +03:00
logWrite(locale("passed_norun", "console", locale=configGet("locale")))
2022-08-09 12:18:23 +03:00
sys.exit()
2022-08-09 14:02:52 +03:00
#===========================================================================================================================================
2022-08-09 12:18:23 +03:00
2022-08-09 14:02:52 +03:00
# Import ===================================================================================================================================
2022-08-08 15:53:26 +03:00
try:
2022-08-09 13:31:11 +03:00
import schedule # type: ignore
2022-08-08 15:53:26 +03:00
from pyrogram import Client, filters, idle # type: ignore
2022-08-09 11:01:02 +03:00
from pyrogram.types import ChatPermissions, ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton, BotCommand, BotCommandScopeChat # type: ignore
2022-08-08 15:53:26 +03:00
except ModuleNotFoundError:
2022-08-10 14:08:15 +03:00
print(locale("deps_missing", "console", locale=configGet("locale")), flush=True)
2022-08-08 15:53:26 +03:00
sys.exit()
2022-08-09 14:02:52 +03:00
#===========================================================================================================================================
2022-08-08 15:53:26 +03:00
2022-08-09 14:02:52 +03:00
pid = os.getpid()
2022-08-08 15:53:26 +03:00
app = Client("duptsiaposter", bot_token=configGet("bot_token", "bot"), api_id=configGet("api_id", "bot"), api_hash=configGet("api_hash", "bot"))
def send_content():
try:
list_sent = jsonLoad(configGet("index", "locations"))
list_queue = os.listdir(configGet("queue", "locations"))
for file in list_queue:
if not file in list_sent["sent"]:
ext_match = False
for ext in configGet("photo", "posting", "extensions"):
if file.endswith(ext):
ext_match = True
ext_type = "photo"
break
for ext in configGet("video", "posting", "extensions"):
if file.endswith(ext):
ext_match = True
ext_type = "video"
break
if not ext_match:
list_queue.remove(file)
else:
list_queue.remove(file)
if len(list_queue) > 0:
candidate_file = random.choice(list_queue)
candidate = configGet("queue", "locations")+os.sep+candidate_file
else:
2022-08-10 14:08:15 +03:00
logWrite(locale("post_empty", "console", locale=configGet("locale")))
2022-08-09 11:01:02 +03:00
if configGet("error", "reports"):
2022-08-11 11:24:57 +03:00
app.send_message(configGet("admin"), locale("post_empty", "message", locale=configGet("locale"))) # type: ignore
2022-08-08 15:53:26 +03:00
return
2022-08-11 11:10:35 +03:00
index = jsonLoad(configGet("index", "locations"))
if candidate_file in index["captions"]:
caption = index["captions"][candidate_file]
else:
caption = ""
if configGet("enabled", "caption"):
if configGet("link", "caption") != None:
caption = f"{caption}\n\n[{configGet('text', 'caption')}]({configGet('link', 'caption')})"
else:
caption = f"{caption}\n\n{configGet('text', 'caption')}"
else:
caption = caption
2022-08-08 15:53:26 +03:00
if ext_type == "photo": # type: ignore
if configGet("enabled", "caption"):
if configGet("link", "caption") != None:
2022-08-11 11:10:35 +03:00
sent = app.send_photo(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore
2022-08-08 15:53:26 +03:00
else:
2022-08-11 11:10:35 +03:00
sent = app.send_photo(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore
2022-08-08 15:53:26 +03:00
else:
2022-08-11 11:10:35 +03:00
sent = app.send_photo(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore
2022-08-08 15:53:26 +03:00
elif ext_type == "video": # type: ignore
if configGet("enabled", "caption"):
if configGet("link", "caption") != None:
2022-08-11 11:10:35 +03:00
sent = app.send_video(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore
2022-08-08 15:53:26 +03:00
else:
2022-08-11 11:10:35 +03:00
sent = app.send_video(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore
2022-08-08 15:53:26 +03:00
else:
2022-08-11 11:10:35 +03:00
sent = app.send_video(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore
2022-08-08 15:53:26 +03:00
2022-08-11 21:39:03 +03:00
else:
return
2022-08-08 15:53:26 +03:00
list_sent["sent"].append(candidate_file)
jsonSave(list_sent, configGet("index", "locations"))
if configGet("move_sent", "posting"):
shutil.move(candidate, configGet("sent", "locations")+os.sep+candidate_file)
2022-08-11 21:39:03 +03:00
logWrite(locale("post_sent", "console", locale=configGet("locale")).format(candidate, ext_type, str(configGet("channel", "posting")), caption.replace("\n", "%n"), str(configGet("silent", "posting")))) # type: ignore
2022-08-11 13:01:31 +03:00
2022-08-09 11:01:02 +03:00
if configGet("sent", "reports"):
2022-08-11 11:24:57 +03:00
app.send_message(configGet("admin"), f"Posted `{candidate_file}`", disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([
2022-08-11 13:01:31 +03:00
[InlineKeyboardButton(locale("post_view", "button", locale=configGet("locale")), url=sent.link)] # type: ignore
2022-08-09 11:01:02 +03:00
])) # type: ignore
2022-08-08 15:53:26 +03:00
except Exception as exp:
2022-08-11 13:01:31 +03:00
logWrite(locale("post_exception", "console", locale=configGet("locale")).format(str(exp), traceback.format_exc()))
2022-08-09 11:01:02 +03:00
if configGet("error", "reports"):
2022-08-11 11:24:57 +03:00
app.send_message(configGet("admin"), locale("post_exception", "message", locale=configGet("locale")).format(exp, traceback.format_exc())) # type: ignore
2022-08-11 13:01:31 +03:00
pass
2022-08-09 11:01:02 +03:00
2022-08-10 14:08:15 +03:00
@app.on_message(~ filters.scheduled & filters.command(["start"], prefixes="/"))
2022-08-11 13:01:31 +03:00
def cmd_start(app, msg):
2022-08-09 16:12:18 +03:00
if msg.from_user.id not in jsonLoad(configGet("blocked", "locations")):
2022-08-10 14:08:15 +03:00
msg.reply_text(locale("start", "message", locale=msg.from_user.language_code))
@app.on_message(~ filters.scheduled & filters.command(["rules", "help"], prefixes="/"))
2022-08-11 13:01:31 +03:00
def cmd_rules(app, msg):
2022-08-10 14:08:15 +03:00
if msg.from_user.id not in jsonLoad(configGet("blocked", "locations")):
msg.reply_text(locale("rules", "message", locale=msg.from_user.language_code))
2022-08-09 16:12:18 +03:00
2022-08-09 11:01:02 +03:00
@app.on_message(~ filters.scheduled & filters.command(["kill", "die", "reboot"], prefixes=["", "/"]))
2022-08-11 13:01:31 +03:00
def cmd_kill(app, msg):
2022-08-09 11:01:02 +03:00
2022-08-11 11:24:57 +03:00
if msg.from_user.id == configGet("admin"):
2022-08-11 13:01:31 +03:00
logWrite(locale("shutdown", "console", locale=configGet("locale")).format(str(pid)))
2022-08-10 14:08:15 +03:00
msg.reply_text(locale("shutdown", "message", locale=configGet("locale")).format(str(pid)))
killProc(pid)
2022-08-08 15:53:26 +03:00
2022-08-09 14:02:52 +03:00
# Submission =====================================================================================================================================
def subLimit(user):
submit = jsonLoad(configGet("submit", "locations"))
submit[str(user.id)] = time.time()
jsonSave(submit, configGet("submit", "locations"))
def subLimited(user):
2022-08-11 11:24:57 +03:00
if user.id == configGet("admin"):
2022-08-09 14:02:52 +03:00
return False
else:
submit = jsonLoad(configGet("submit", "locations"))
if str(user.id) in submit:
2022-08-09 15:44:06 +03:00
if (time.time() - submit[str(user.id)]) < configGet("timeout", "submission"):
2022-08-09 14:02:52 +03:00
return True
else:
return False
else:
return False
2022-08-09 15:44:06 +03:00
def subBlock(user):
blocked = jsonLoad(configGet("blocked", "locations"))
2022-08-09 16:12:18 +03:00
if user not in blocked:
blocked.append(user)
2022-08-09 15:44:06 +03:00
jsonSave(blocked, configGet("blocked", "locations"))
def subUnblock(user):
blocked = jsonLoad(configGet("blocked", "locations"))
2022-08-09 16:12:18 +03:00
if user in blocked:
blocked.remove(user)
2022-08-09 15:44:06 +03:00
jsonSave(blocked, configGet("blocked", "locations"))
2022-08-11 10:59:30 +03:00
@app.on_message(~ filters.scheduled & filters.photo | filters.video | filters.animation | filters.document)
2022-08-09 14:02:52 +03:00
def get_submission(_, msg):
2022-08-09 15:44:06 +03:00
if msg.from_user.id not in jsonLoad(configGet("blocked", "locations")):
2022-08-10 14:08:15 +03:00
user_locale = msg.from_user.language_code
2022-08-09 15:44:06 +03:00
if not subLimited(msg.from_user):
2022-08-09 16:12:18 +03:00
2022-08-11 10:59:30 +03:00
if msg.document != None:
if msg.document.mime_type not in configGet("mime_types", "submission"):
msg.reply_text(locale("mime_not_allowed", "message", locale=user_locale), quote=True)
return
2022-08-11 14:38:42 +03:00
if msg.document.file_size > configGet("file_size", "submission"):
msg.reply_text(locale("document_too_large", "message", locale=user_locale).format(str(configGet("file_size", "submission")/1024/1024)), quote=True)
return
if msg.video != None:
if msg.video.file_size > configGet("file_size", "submission"):
msg.reply_text(locale("document_too_large", "message", locale=user_locale).format(str(configGet("file_size", "submission")/1024/1024)), quote=True)
return
2022-08-11 10:59:30 +03:00
buttons = [
[
InlineKeyboardButton(text=locale("sub_yes", "button", locale=configGet("locale")), callback_data=f"sub_yes_{msg.from_user.id}_{msg.id}")
]
]
2022-08-09 16:12:18 +03:00
if msg.caption != None:
caption = str(msg.caption)
2022-08-11 10:59:30 +03:00
buttons[0].append(
2022-08-11 11:10:35 +03:00
InlineKeyboardButton(text=locale("sub_yes_caption", "button", locale=configGet("locale")), callback_data=f"sub_yes_{msg.from_user.id}_{msg.id}_caption")
)
buttons[0].append(
2022-08-11 10:59:30 +03:00
InlineKeyboardButton(text=locale("sub_no", "button", locale=configGet("locale")), callback_data=f"sub_no_{msg.from_user.id}_{msg.id}")
)
2022-08-09 16:12:18 +03:00
else:
caption = ""
2022-08-11 10:59:30 +03:00
buttons[0].append(
InlineKeyboardButton(text=locale("sub_no", "button", locale=configGet("locale")), callback_data=f"sub_no_{msg.from_user.id}_{msg.id}")
)
2022-08-09 16:12:18 +03:00
2022-08-10 14:08:15 +03:00
caption += locale("sub_by", "message", locale=locale(configGet("locale")))
2022-08-09 16:12:18 +03:00
if msg.from_user.first_name != None:
caption += f" {msg.from_user.first_name}"
if msg.from_user.last_name != None:
caption += f" {msg.from_user.last_name}"
if msg.from_user.username != None:
caption += f" (@{msg.from_user.username})"
if msg.from_user.phone_number != None:
caption += f" ({msg.from_user.phone_number})"
2022-08-11 11:24:57 +03:00
msg.copy(configGet("admin"), caption=caption, reply_markup=InlineKeyboardMarkup(buttons))
2022-08-11 11:24:57 +03:00
if msg.from_user.id != configGet("admin"):
buttons += [
[
InlineKeyboardButton(text=locale("sub_block", "button", locale=configGet("locale")), callback_data=f"sub_block_{msg.from_user.id}")
],
[
InlineKeyboardButton(text=locale("sub_unblock", "button", locale=configGet("locale")), callback_data=f"sub_unblock_{msg.from_user.id}")
]
]
msg.reply_text(locale("sub_sent", "message", locale=user_locale), quote=True)
subLimit(msg.from_user)
2022-08-11 11:24:57 +03:00
2022-08-09 15:44:06 +03:00
else:
2022-08-10 14:08:15 +03:00
msg.reply_text(locale("sub_cooldown", "message", locale=user_locale).format(str(configGet("timeout", "submission"))))
2022-08-09 14:50:59 +03:00
@app.on_callback_query(filters.regex("sub_yes_[\s\S]*_[\s\S]*")) # type: ignore
def callback_query_yes(app, clb): # type: ignore
fullclb = clb.data.split("_")
2022-08-10 14:08:15 +03:00
user_locale = clb.from_user.language_code
2022-08-09 14:50:59 +03:00
try:
2022-08-09 15:44:06 +03:00
submission = app.get_messages(int(fullclb[2]), int(fullclb[3]))
2022-08-09 14:50:59 +03:00
except:
2022-08-10 14:08:15 +03:00
clb.answer(text=locale("sub_msg_unavail", "message", locale=user_locale), show_alert=True)
2022-08-09 14:50:59 +03:00
return
try:
2022-08-11 10:59:30 +03:00
media = app.download_media(submission, file_name=configGet("queue", "locations")+os.sep)
if clb.data.endswith("_caption"):
2022-08-11 11:10:35 +03:00
index = jsonLoad(configGet("index", "locations"))
index["captions"][Path(media).name] = submission.caption
jsonSave(index, configGet("index", "locations"))
2022-08-09 14:50:59 +03:00
except:
2022-08-10 14:08:15 +03:00
clb.answer(text=locale("sub_media_unavail", "message", locale=user_locale), show_alert=True)
2022-08-09 14:50:59 +03:00
return
2022-08-10 14:08:15 +03:00
submission.reply_text(locale("sub_yes", "message", locale=submission.from_user.language_code), quote=True)
clb.answer(text=locale("sub_yes", "callback", locale=user_locale).format(fullclb[2]), show_alert=True)
2022-08-09 14:50:59 +03:00
@app.on_callback_query(filters.regex("sub_no_[\s\S]*_[\s\S]*")) # type: ignore
def callback_query_no(app, clb): # type: ignore
fullclb = clb.data.split("_")
2022-08-10 14:08:15 +03:00
user_locale = clb.from_user.language_code
2022-08-09 14:50:59 +03:00
try:
2022-08-09 15:44:06 +03:00
submission = app.get_messages(int(fullclb[2]), int(fullclb[3]))
2022-08-09 14:50:59 +03:00
except:
2022-08-10 14:08:15 +03:00
clb.answer(text=locale("sub_msg_unavail", "message", locale=user_locale), show_alert=True)
2022-08-09 14:50:59 +03:00
return
2022-08-10 14:08:15 +03:00
submission.reply_text(locale("sub_no", "message", locale=submission.from_user.language_code), quote=True)
clb.answer(text=locale("sub_no", "callback", locale=user_locale).format(fullclb[2]), show_alert=True)
2022-08-09 14:50:59 +03:00
@app.on_callback_query(filters.regex("sub_block_[\s\S]*")) # type: ignore
def callback_query_block(app, clb): # type: ignore
fullclb = clb.data.split("_")
2022-08-10 14:08:15 +03:00
user_locale = clb.from_user.language_code
app.send_message(int(fullclb[2]), locale("sub_msg_unavail", "message", locale=configGet("locale")))
2022-08-09 15:44:06 +03:00
subBlock(int(fullclb[2]))
2022-08-10 14:08:15 +03:00
clb.answer(text=locale("sub_block", "callback", locale=user_locale).format(fullclb[2]), show_alert=True)
2022-08-09 15:44:06 +03:00
@app.on_callback_query(filters.regex("sub_unblock_[\s\S]*")) # type: ignore
def callback_query_unblock(app, clb): # type: ignore
fullclb = clb.data.split("_")
2022-08-10 14:08:15 +03:00
user_locale = clb.from_user.language_code
app.send_message(int(fullclb[2]), locale("sub_msg_unavail", "message", locale=configGet("locale")))
2022-08-09 15:44:06 +03:00
subUnblock(int(fullclb[2]))
2022-08-10 14:08:15 +03:00
clb.answer(text=locale("sub_unblock", "callback", locale=user_locale).format(fullclb[2]), show_alert=True)
2022-08-09 14:02:52 +03:00
#===========================================================================================================================================
2022-08-08 15:53:26 +03:00
for entry in configGet("time", "posting"):
schedule.every().day.at(entry).do(send_content)
def background_task():
try:
while True:
try:
schedule.run_pending()
time.sleep(1)
except:
pass
except Exception as exp:
2022-08-10 14:08:15 +03:00
logWrite(locale("exception_occured", "console", locale=configGet("locale")).format(exp))
2022-08-08 15:53:26 +03:00
except KeyboardInterrupt:
2022-08-10 14:08:15 +03:00
logWrite(locale("keyboard_interrupt", "console", locale=configGet("locale")))
if configGet("shutdown", "reports"):
2022-08-11 11:24:57 +03:00
app.send_message(configGet("admin"), locale("shutdown", "message", locale=configGet("locale")).format(str(pid))) # type: ignore
2022-08-10 14:08:15 +03:00
killProc(pid)
2022-08-08 15:53:26 +03:00
if __name__ == "__main__":
2022-08-10 14:08:15 +03:00
logWrite(locale("startup", "console", locale=configGet("locale")).format(str(pid)))
2022-08-08 15:53:26 +03:00
app.start() # type: ignore
2022-08-10 14:08:15 +03:00
if configGet("startup", "reports"):
2022-08-11 11:24:57 +03:00
app.send_message(configGet("admin"), locale("startup", "message", locale=configGet("locale")).format(str(pid))) # type: ignore
2022-08-08 15:53:26 +03:00
t = Thread(target=background_task)
t.start()
2022-08-14 19:27:35 +03:00
# Registering user commands
2022-08-10 14:08:15 +03:00
for entry in os.listdir(configGet("locale", "locations")):
if entry.endswith(".json"):
commands_list = []
for command in configGet("commands"):
commands_list.append(BotCommand(command, locale(command, "commands", locale=entry.replace(".json", ""))))
2022-08-11 21:39:03 +03:00
app.set_bot_commands(commands_list, language_code=entry.replace(".json", "")) # type: ignore
2022-08-10 14:08:15 +03:00
2022-08-14 19:27:35 +03:00
# Registering user commands for fallback locale
2022-08-10 14:08:15 +03:00
commands_list = []
for command in configGet("commands"):
commands_list.append(BotCommand(command, locale(command, "commands", locale=configGet("locale_fallback"))))
2022-08-11 21:39:03 +03:00
app.set_bot_commands(commands_list) # type: ignore
2022-08-09 16:12:18 +03:00
2022-08-14 19:27:35 +03:00
# Registering admin commands
commands_admin_list = []
for command in configGet("commands"):
commands_admin_list.append(BotCommand(command, locale(command, "commands", locale=configGet("locale"))))
for command in configGet("commands_admin"):
commands_admin_list.append(BotCommand(command, locale(command, "commands_admin", locale=configGet("locale"))))
app.set_bot_commands(commands_admin_list, scope=BotCommandScopeChat(chat_id=configGet("admin"))) # type: ignore
2022-08-09 11:01:02 +03:00
2022-08-08 15:53:26 +03:00
idle()
2022-08-11 11:24:57 +03:00
app.send_message(configGet("admin"), locale("shutdown", "message", locale=configGet("locale")).format(str(pid))) # type: ignore
2022-08-10 14:08:15 +03:00
logWrite(locale("shutdown", "console", locale=configGet("locale")).format(str(pid)))
2022-08-08 15:53:26 +03:00
2022-08-10 14:08:15 +03:00
killProc(pid)