Телеграм бот с автопостингом отказывается работать. Помогите
Понадобился бот для автопостинга в ТГ. Логика такая: бот должен брать из папки 4 штуки jpg в алфавитном порядке, класть к ним строку из txt и публиковать в ТГ с интервалом и расписанием. После этого кропать jpg из исходной в архивную папку и строку тоже кропать со сдвигом вверх из txt и дописывать в архивный. Исход один. Командная строка открывает .py и молчит. Не ругается. Публикаций в канале не происходит. Токен, ID, пути перепроверены. Оба txt, тестовые строки в одном из них и папки созданы. Бот в канал добавлен, правами наделён. Код раза 3 переписывал. Ни один не начал публиковать посты. Уже даже не знаю какой из вариантов лучше. Подскажите, куда копать? pyTelegramBotAPI==4.12.0 \ Python 3.10.6
Попытка №1
import os
import telebot
import schedule
import random
import time
import datetime
TOKEN = 'изменёт'
CHANNEL_ID = '-10019196321'
IMAGES_FOLDER = 'C:/Users/eremi/Desktop/BOT_TELEGA/out/out'
TEXT_FILE = 'C:/Users/eremi/Desktop/BOT_TELEGA/out/message.txt'
PUBLISHED_TEXT_FILE = 'C:/Users/eremi/Desktop/BOT_TELEGA/out/message_archive.txt'
ARCHIVE_FOLDER = 'C:/Users/eremi/Desktop/BOT_TELEGA/out/out_archive'
bot = telebot.TeleBot(TOKEN)
def get_next_image():
files = sorted(os.listdir(IMAGES_FOLDER))
for file in files:
if file.endswith('.jpg') or file.endswith('.png'):
return file
return None
def use_next_text():
with open(TEXT_FILE, 'r') as file:
lines = file.readlines()
if lines:
next_line = lines[0].strip()
lines = lines[1:]
else:
next_line = None
with open(TEXT_FILE, 'w') as file:
file.writelines(lines)
with open(PUBLISHED_TEXT_FILE, 'a') as file:
file.write(next_line + '\n')
return next_line
def publish_images():
for _ in range(4):
image = get_next_image()
if image is not None:
caption = use_next_text()
with open(os.path.join(IMAGES_FOLDER, image), 'rb') as photo:
bot.send_photo(CHANNEL_ID, photo, caption=caption)
os.rename(os.path.join(IMAGES_FOLDER, image), os.path.join(ARCHIVE_FOLDER, image))
else:
break
schedule_next_publish()
def schedule_next_publish():
interval = random.randint(120, 150)
schedule.every(interval).seconds.do(publish_images)
def check_and_publish():
now = time.localtime()
hour = now.tm_hour
if 10 <= hour < 23: # Публикация только с 10:00 до 23:00
publish_images()
schedule_next_check()
def schedule_next_check():
# Расписание для следующей проверки времени
schedule.every().hour.at(':00').do(check_and_publish)
schedule_next_check()
while True:
schedule.run_pending()
time.sleep(1)
Попытка №2
import os
import telebot
import schedule
import random
import time
import datetime
TOKEN = 'изменён'
CHANNEL_ID = '-изменён'
IMAGES_FOLDER = 'C:/Users/eremi/Desktop/BOT_TELEGA/out/out'
TEXT_FILE = 'C:/Users/eremi/Desktop/BOT_TELEGA/out/message.txt'
PUBLISHED_TEXT_FILE = 'C:/Users/eremi/Desktop/BOT_TELEGA/out/message_archive.txt'
ARCHIVE_FOLDER = 'C:/Users/eremi/Desktop/BOT_TELEGA/out/out_archive'
bot = telebot.TeleBot(TOKEN)
def get_next_image():
files = sorted(os.listdir(IMAGES_FOLDER))
for file in files:
if file.endswith('.jpg') or file.endswith('.png'):
return file
return None
def use_next_text():
with open(TEXT_FILE, 'r') as file:
lines = file.readlines()
if lines:
next_line = lines[0].strip()
lines = lines[1:]
else:
next_line = None
with open(TEXT_FILE, 'w') as file:
file.writelines(lines)
with open(PUBLISHED_TEXT_FILE, 'a') as file:
file.write(next_line + '\n')
return next_line
def publish_images():
print("Publishing images...")
for _ in range(4):
image = get_next_image()
if image is not None:
caption = use_next_text()
print("Publishing image:", image)
print("Caption:", caption)
with open(os.path.join(IMAGES_FOLDER, image), 'rb') as photo:
bot.send_photo(CHANNEL_ID, photo, caption=caption)
os.rename(os.path.join(IMAGES_FOLDER, image), os.path.join(ARCHIVE_FOLDER, image))
print("Image moved to archive:", image)
else:
break
schedule_next_publish()
def schedule_next_publish():
interval = random.randint(120, 150)
print("Scheduling next publish in", interval, "seconds.")
schedule.every(interval).seconds.do(publish_images)
def check_and_publish():
now = time.localtime()
hour = now.tm_hour
if 10 <= hour < 23: # Публикация только с 10:00 до 23:00
publish_images()
schedule_next_check()
def schedule_next_check():
# Расписание для следующей проверки времени
schedule.every().hour.at(':00').do(check_and_publish)
schedule_next_check()
while True:
schedule.run_pending()
time.sleep(1)