Загрузка...

Скрипт Авто-поднятие темы

Тема в разделе Python создана пользователем деньгинеденьга 17 апр 2025. 90 просмотров

Загрузка...
  1. деньгинеденьга
    Скрипт при запуске не бежит сразу поднимать темы, в конфиге нужно оставить свой токен, время, когда будет подниматься тема, айди всех тем скрипт работает 24\7
    autobump py:
    Python
    import json
    import time
    from datetime import datetime
    import pytz
    import logging
    import requests
    from threading import Thread
    import re

    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    def load_config(config_path):
    with open(config_path, 'r') as f:
    config = json.load(f)
    required_keys = ['token', 'times', 'threads']
    for key in required_keys:
    if key not in config:
    raise ValueError(f"отсутствует токен API: {key}")
    return config

    def get_thread_title(thread_id, token):
    url = f"https://prod-api.zelenka.guru/threads/{thread_id}"
    headers = {"Authorization": f"Bearer {token}"}
    try:
    response = requests.get(url, headers=headers, timeout=10)
    if response.ok:
    return response.json().get('thread', {}).get('thread_title', 'неизвестный заголовок')
    return "неизвестный заголовок"
    except Exception as e:
    logger.error(f"ошибка при получении заголовка: {str(e)}")
    return "неизвестный заголовок"

    def bump_thread(thread_id, token):
    url = f"https://prod-api.zelenka.guru/threads/{thread_id}/bump"
    headers = {
    "Authorization": f"Bearer {token}",
    "accept": "application/json"
    }

    try:
    response = requests.post(url, headers=headers, timeout=15)
    logger.info(f"Response for thread {thread_id}: {response.text}")

    if response.status_code == 200:
    try:
    data = response.json()
    if "errors" in data:
    error_message = data["errors"][0]
    time_match = re.search(r'(\d+)\s+часов\s+(\d+)\s+минут\s+(\d+)\s+секунд', error_message)
    if time_match:
    hours, minutes, seconds = map(int, time_match.groups())
    return False, (f"Вы можете поднимать тему раз в 48 часов. "
    f"Подождите {hours}ч {minutes}м {seconds}с")
    return False, error_message
    return True, "Тема успешно поднята"
    except (IndexError, KeyError, ValueError):
    return True, "не удалось разобрать ответ"
    return False, f"ошибка HTTP: поднять еще нельзя"
    except requests.exceptions.RequestException as e:
    return False, f"ошибка сети: {str(e)}"

    def bumping(threads, token):
    for thread_id in threads:
    title = get_thread_title(thread_id, token)
    success, error = bump_thread(thread_id, token)
    if success:
    print(f"Тема поднята! Заголовок: {title}")
    else:
    print(f"thread/{thread_id} | Не удалось поднять | Ошибка: {error}")
    time.sleep(10)

    def main():
    config = load_config('config.json')
    moscow_tz = pytz.timezone('Europe/Moscow')
    processed_times = set()
    current_date = None

    print("доброе утро. смотрю часы")

    while True:
    now = datetime.now(moscow_tz)
    today = now.date()
    current_time = now.strftime('%H:%M')

    # сброс при новом дне
    if today != current_date:
    current_date = today
    processed_times.clear()

    # проверка time
    if current_time in config['times'] and current_time not in processed_times:
    print(f"Время {current_time}: начинаю поднятие тем")
    processed_times.add(current_time)
    Thread(target=bumping, args=(config['threads'], config['token'])).start()

    time.sleep(10)

    if __name__ == "__main__":
    main()
    config.json:
    Python
    {
    "token": "ыыыыы",
    "times": ["17:38", "20:00"],
    "threads": ["8590606", "5252"]
    }
     
    17 апр 2025 Изменено
Top