Files
VK_autolike_bot/main.py
2024-02-28 00:06:43 +03:00

78 lines
3.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
import threading
import time
TARGET_GROUP_ID = ''
ACCESS_TOKEN = ''
DELAY_BETWEEN_CHECKS = 90
# Переменная для хранения ID последнего просмотренного поста
last_viewed_post_id = None
def like_post(event, vk):
global last_viewed_post_id
try:
# Проверяем, является ли пост новым
if event.wall_id > last_viewed_post_id:
# Лайкаем пост
vk.likes.add(type='post', owner_id=event.group_id, item_id=event.wall_id)
print("Пост от {} успешно лайкнут.".format(event.group_id))
# Обновляем last_viewed_post_id
last_viewed_post_id = event.wall_id
except vk_api.exceptions.ApiError as e:
print("Ошибка VK API при лайке поста:", e)
except Exception as e:
print("Необработанная ошибка при лайке поста:", e)
def process_events(vk, longpoll):
print("Бот запущен. Лайкать новые посты из сообщества {}.".format(TARGET_GROUP_ID))
for event in longpoll.listen():
if event.type == VkEventType.WALL_POST_NEW and str(event.group_id) == TARGET_GROUP_ID:
like_post(event, vk)
def check_new_posts(vk):
global last_viewed_post_id
while True:
try:
# Получаем информацию о сообществе, включая последний пост
group_info_response = vk.groups.getById(group_id=TARGET_GROUP_ID, fields='wall')
# Проверяем, успешно ли получены данные
if 'groups' in group_info_response and len(group_info_response['groups']) > 0:
group_info = group_info_response['groups'][0]
# Получаем ID последнего поста
wall_info = group_info.get('wall')
if wall_info and 'from_id' in wall_info:
last_post_id = wall_info['from_id']
# Проверяем, является ли последний пост новым
if last_post_id > last_viewed_post_id:
last_viewed_post_id = last_post_id
print("Новый пост в сообществе {}: {}".format(TARGET_GROUP_ID, last_post_id))
except vk_api.exceptions.ApiError as e:
print("Ошибка VK API при получении информации о сообществе:", e)
except Exception as e:
print("Необработанная ошибка при проверке новых постов:", e)
# Добавляем задержку перед следующей проверкой
time.sleep(DELAY_BETWEEN_CHECKS)
def main():
vk_session = vk_api.VkApi(token=ACCESS_TOKEN)
vk = vk_session.get_api()
longpoll = VkLongPoll(vk_session)
# Запуск потока для проверки новых постов
new_posts_thread = threading.Thread(target=check_new_posts, args=(vk,))
new_posts_thread.start()
# Обработка событий от longpoll
process_events(vk, longpoll)
if __name__ == '__main__':
main()