import vk_api
import time
from PIL import Image
import requests
from bs4 import BeautifulSoup
from io import BytesIO
def get_new_images(url):
session = requests.Session()
response = session.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.content, "html.parser")
images = soup.find_all("img")
corrected_image_urls = []
for image in images:
image_url = image.get("src")
if image_url and image_url.startswith("https://topmemas.top/img/b_img/"):
corrected_image_urls.append(image_url)
return corrected_image_urls
def is_valid_image(image_url):
response = requests.get(image_url)
if response.status_code == 200:
image = Image.open(BytesIO(response.content))
return image.format in ("JPEG", "PNG")
return False
def download_image(image_url):
response = requests.get(image_url)
response.raise_for_status()
image_data = response.content
image = Image.open(BytesIO(image_data))
return image
def send_message(image, message, vk_token):
image_path = str(image.filename)
file_id = image_path
params = {
"group_id": -77611508,
"message": message,
"attachments": file_id,
"access_token": vk_token,
}
response = vk_api.VkApi(token=vk_token).method("messages.send", params)
if response.response():
print("Сообщение с картинкой отправлено успешно.")
else:
print("Ошибка при отправке сообщения с картинкой.")
def main(vk_token):
url = "https://topmemas.top/"
message_count = 0
if vk_token:
print("VK Access Token находится в переменной vk_token.")
else:
print("VK Access Token не найден в переменной vk_token.")
return
while message_count < 10:
try:
image_urls = get_new_images(url)
for image_url in image_urls:
try:
if is_valid_image(image_url):
image = download_image(image_url)
send_message(image, f"Сообщение с картинкой №{message_count}", vk_token)
break
except Exception as e:
print(f"Ошибка при загрузке изображения: {e}")
except Exception as e:
print(f"Ошибка при получении изображений: {e}")
except Exception as e:
print(f"Ошибка при получении изображений: {e}")
time.sleep(1900)
message_count += 1
print("Функция main выполнена.")
if __name__ == "__main__":