import pyautogui as pag
import subprocess
from time import sleep
import pyperclip as pc
import pygetwindow as gw
import ctypes
import datetime
import os
from datetime import date
import json
pag.FAILSAFE = True
pag.PAUSE = 0.8
SEARCH_X, SEARCH_Y = 140, 46
CLEAR_X, CLEAR_Y = 273, 44
GROUP_X, GROUP_Y = 108, 204
PHOTO_X, PHOTO_Y = 328, 990
DATA_FILE = r'F:\програмирование\python\viber рассылка\ads.json'
HISTORY_FILE = r'F:\програмирование\python\viber рассылка\sending_history.json'
def click_at(x, y):
pag.moveTo(x, y, duration=0.2)
pag.click()
def press_ctrl_v():
VK_CONTROL = 0x11
VK_V = 0x56
KEYEVENTF_KEYUP = 0x0002
ctypes.windll.user32.keybd_event(VK_CONTROL, 0, 0, 0)
ctypes.windll.user32.keybd_event(VK_V, 0, 0, 0)
ctypes.windll.user32.keybd_event(VK_V, 0, KEYEVENTF_KEYUP, 0)
ctypes.windll.user32.keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0)
def write(message, send=True):
pc.copy(message)
sleep(0.3)
press_ctrl_v()
sleep(0.3)
if send:
pag.press("enter")
def go_to(name):
click_at(SEARCH_X, SEARCH_Y)
write(name, send=False)
sleep(1)
click_at(GROUP_X, GROUP_Y)
sleep(0.5)
click_at(CLEAR_X, CLEAR_Y)
def send_photo(path):
click_at(PHOTO_X, PHOTO_Y)
sleep(1)
write(rf"{path}")
def send_ad(ad):
if ad["text"].strip():
write(ad["text"])
sleep(1)
send_photo(ad["photo"])
sleep(1)
def load_sending_history():
if os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
return {}
def save_sending_history(history):
with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
json.dump(history, f, ensure_ascii=False, indent=4)
def update_sending_history(history, group_id, ad_id, sent_date):
group_id_str = str(group_id)
ad_id_str = str(ad_id)
if group_id_str not in history:
history[group_id_str] = {}
history[group_id_str][ad_id_str] = sent_date
def should_send_today(history, group_id, ad_id, frequency, today):
group_id_str = str(group_id)
ad_id_str = str(ad_id)
if group_id_str not in history or ad_id_str not in history[group_id_str]:
return True
last_sent_str = history[group_id_str][ad_id_str]
last_sent_date = datetime.datetime.strptime(last_sent_str, "%Y-%m-%d").date()
days_since_last = (today - last_sent_date).days
if frequency == 0:
return days_since_last >= 1
else:
return days_since_last > frequency
def get_ads_for_today(group_ads, group_id, today, max_ads_per_day=1):
sorted_ads = sorted(group_ads, key=lambda x: x["id"])
total_ads = len(sorted_ads)
if total_ads <= max_ads_per_day:
return sorted_ads
cycle_length = (total_ads + max_ads_per_day - 1) // max_ads_per_day
day_in_cycle = ((today - date(2020, 1, 1)).days) % cycle_length
start_index = day_in_cycle * max_ads_per_day
end_index = min(start_index + max_ads_per_day, total_ads)
return sorted_ads[start_index:end_index]
def main():
with open(DATA_FILE, 'r', encoding='utf-8') as file:
data = json.load(file)
ads = data["ads"]
groups = data["groups"]
history = load_sending_history()
today = date.today()
groups_to_send = []
ads_to_send_by_group = {}
for group in groups:
group_id = group["id"]
group_name = group["name"]
frequency = group["frequency"]
group_ads = [ad for ad in ads if group_id in ad["groups"]]
potential_ads = get_ads_for_today(group_ads, group_id, today, 4)
ads_to_send = []
for ad in potential_ads:
if should_send_today(history, group_id, ad["id"], frequency, today):
ads_to_send.append(ad)
if ads_to_send:
groups_to_send.append(group)
ads_to_send_by_group[group_id] = ads_to_send
if not groups_to_send:
print("Сегодня нечего отправлять!")
return
print(f"Найдено групп для отправки: {len(groups_to_send)}")
subprocess.Popen(r'C:\Users\Artem\AppData\Local\Viber\Viber.exe')
sleep(10)
viber_windows = gw.getWindowsWithTitle('Viber')
if viber_windows:
viber_window = viber_windows[0]
viber_window.maximize()
for group in groups_to_send:
group_id = group["id"]
group_name = group["name"]
print(f"Обрабатываем группу: {group_name} (ID: {group_id})")
ads_to_send = ads_to_send_by_group[group_id]
print(f"Отправляем {len(ads_to_send)} объявлений в группу {group_name}")
go_to(group_name)
sleep(0.5)
for ad in ads_to_send:
send_ad(ad)
update_sending_history(history, group_id, ad["id"], today.strftime("%Y-%m-%d"))
sleep(0.5)
print(f"Успешно отправлено в группу {group_name}")
save_sending_history(history)
print("Рассылка завершена!")
if __name__ == "__main__":
main()