import sys
import os
import json
import requests
IS_COMPONENTS_V2 = 1 << 15
def load_components(path: str):
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict) and "components" in data:
return data["components"]
return data
def collect_and_fix_attachments(node, base_dir, files_to_upload, used_names):
if isinstance(node, dict):
for key, value in node.items():
if key in ("media", "file") and isinstance(value, dict) and "url" in value:
url = value["url"]
if not (
url.startswith("http://")
or url.startswith("https://")
or url.startswith("attachment://")
):
local_path = url if os.path.isabs(url) else os.path.join(base_dir, url)
filename = os.path.basename(url)
original_filename = filename
counter = 1
while filename in used_names:
name, ext = os.path.splitext(original_filename)
filename = f"{name}_{counter}{ext}"
counter += 1
used_names.add(filename)
value["url"] = f"attachment://{filename}"
files_to_upload.append((filename, local_path))
else:
collect_and_fix_attachments(value, base_dir, files_to_upload, used_names)
elif isinstance(node, list):
for item in node:
collect_and_fix_attachments(item, base_dir, files_to_upload, used_names)
def post_to_webhook(webhook_url: str, components: list, base_dir: str, thread_id: str = None):
files_to_upload = []
used_names = set()
collect_and_fix_attachments(components, base_dir, files_to_upload, used_names)
payload = {
"flags": IS_COMPONENTS_V2,
"components": components,
}
separator = "&" if "?" in webhook_url else "?"
webhook_url = f"{webhook_url}{separator}with_components=true"
if thread_id:
webhook_url = f"{webhook_url}&thread_id={thread_id}"
print("--- Отправляемый payload ---")
print(json.dumps(payload, ensure_ascii=False))
if files_to_upload:
print("--- Прикреплённые файлы ---")
for fname, path in files_to_upload:
print(f" {fname} <- {path}")
print("----------------------------")
if files_to_upload:
open_files = []
try:
multipart_files = {}
for i, (fname, path) in enumerate(files_to_upload):
if not os.path.isfile(path):
print(f"Ошибка: файл не найден: {path}")
return
fh = open(path, "rb")
open_files.append(fh)
multipart_files[f"files[{i}]"] = (fname, fh)
data = {"payload_json": json.dumps(payload, ensure_ascii=False)}
resp = requests.post(webhook_url, data=data, files=multipart_files)
finally:
for fh in open_files:
fh.close()
else:
headers = {
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) DiscordWebhookPoster/1.0",
}
resp = requests.post(webhook_url, headers=headers, json=payload)
if resp.ok:
print(f"OK: статус {resp.status_code}")
else:
print(f"Ошибка {resp.status_code}: {resp.text}")
def main():
if len(sys.argv) < 2:
print("Использование: python main.py <WEBHOOK_URL> [config.json] [thread_id]")
sys.exit(1)
webhook_url = sys.argv[1]
config_path = sys.argv[2] if len(sys.argv) > 2 else "config.json"
thread_id = sys.argv[3] if len(sys.argv) > 3 else None
base_dir = os.path.dirname(os.path.abspath(config_path)) or "."
components = load_components(config_path)
post_to_webhook(webhook_url, components, base_dir, thread_id)
if __name__ == "__main__":
main()