FMN_bot/src/fmn_poll.py

94 lines
3.5 KiB
Python

from src.fedi_api import get_status, post_status, upload_attachment
from src.fmn_states_db import add_state, get_state, clear_all_states
from src.fmn_database import get_movies_for_poll, write_votes, read_votes, mark_as_watched_movie, get_already_watched, rewrite_db, reset_poll
from collections import Counter
from loguru import logger
import time
text_create_poll = '''Друзья, голосование за следующий Fediverse Movie Night объявляю открытым!
Ставки сделаны, ставок больше нет
'''.replace('\t', '')
def create_poll_movies(text=text_create_poll, poll_expires=345600):
formated_poll_options = []
raw_poll = get_movies_for_poll()
for i in raw_poll:
acct = i[0]
orig_name = i[1]
ru_name = i[2]
year = i[3]
poll_option_string = f"{ru_name} / {orig_name}, {year} ({acct})"
if ru_name is None:
poll_option_string = f"{orig_name}, {year} ({acct})"
if orig_name is None:
poll_option_string = f"{ru_name}, {year} ({acct})"
formated_poll_options.append(poll_option_string)
poll_status_id = post_status(text, None, formated_poll_options,
poll_expires=poll_expires, attachments=[upload_attachment('src/FMN.png')])
logger.info('Голосовалка создана')
add_state('poll_expires_at', int(time.time()) + poll_expires)
add_state('poll_status_id', poll_status_id['id'])
return poll_status_id
def get_winner_movie(poll_status_id=str):
'''Отмечаем победивший фильм на голосовании как просмотренный или постим tie breaker'''
votes_counters = []
status_with_poll = get_status(poll_status_id)
poll = status_with_poll['poll']
votes_counter = Counter()
for option in poll['options']:
votes_count = option['votes_count']
votes_counters.append(votes_count)
write_votes(votes_counters)
voted_movies = read_votes()
max_vote = voted_movies[0][4]
winned_movies = []
for i in voted_movies:
if max_vote == i[4]:
winned_movies.append(i)
if len(winned_movies) > 1:
logger.warning('Будет создан tie breaker')
rewrite_db(winned_movies)
if get_state('tie_breaker'):
create_tie_breaker(2)
else:
create_tie_breaker()
else:
movie = winned_movies[0]
mark_as_watched_movie(movie[1], movie[2], movie[3])
acct_suggested = movie[0]
orig_name = movie[1]
ru_name = movie[2]
year = movie[3]
win_variant = f"{orig_name} / {ru_name}, {year}"
if ru_name is None:
win_variant = f"{orig_name}, {year}"
if orig_name is None:
win_variant = f"{ru_name}, {year}"
text_winned = f'''Голосование завершилось! Победил вариант предложенный @{acct_suggested}:
{win_variant}
'''.replace('\t', '')
logger.warning("Победил " + str(movie))
post_status(text_winned, attachments=[upload_attachment('src/FMN.png')])
clear_all_states()
reset_poll()
def create_tie_breaker(count_tie=1):
'''Создание tie breaker'''
if count_tie == 1:
add_state('tie_breaker', 1)
poll_expires = 8*60*60
else:
poll_expires = 4*60*60
tie_poll = create_poll_movies("TIE BREAKER!!!\n\nВыбираем из победителей!", poll_expires)