-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathvoting.py
More file actions
149 lines (119 loc) · 4.8 KB
/
voting.py
File metadata and controls
149 lines (119 loc) · 4.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import functools
import peewee
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import CommandHandler, CallbackQueryHandler
from pycamp_bot.commands.base import msg_to_active_pycamp_chat
from pycamp_bot.commands.auth import admin_needed
from pycamp_bot.commands.manage_pycamp import active_needed, get_active_pycamp
from pycamp_bot.models import Pycampista, Project, Vote
from pycamp_bot.logger import logger
VOTE_PATTERN = 'vote'
def vote_authorized(func):
@functools.wraps(func)
async def wrap(*args):
logger.info('Vote authorized wrapper')
update, context = args
is_active, pycamp = get_active_pycamp()
if pycamp.vote_authorized:
await func(update, context)
else:
await context.bot.send_message(
chat_id=update.message.chat_id,
text="La eleccion no está autorizada. Avisale a un admin (/admins)!")
return wrap
@admin_needed
@active_needed
async def start_voting(update, context):
logger.info("Empezando la seleccion.")
is_active, pycamp = get_active_pycamp()
if not pycamp.vote_authorized:
pycamp.vote_authorized = True
pycamp.save()
await update.message.reply_text("Autorizadx. \nSelección Abierta.")
await msg_to_active_pycamp_chat(context.bot, "La elección de proyectos esta abierta!")
else:
await update.message.reply_text("La eleccion ya estaba abierta.")
async def button(update, context):
'''Save user vote in the database'''
query = update.callback_query
username = query.from_user.username
chat_id = query.message.chat_id
user = Pycampista.get_or_create(username=username, chat_id=chat_id)[0]
project_name = query.message.text
# Get project from the database
project = Project.get(Project.name == project_name)
# create a new vote object
new_vote = Vote(
pycampista=user,
project=project,
_project_pycampista_id=f"{project.id}-{user.id}"
)
# Save vote in the database and confirm the chosen proyects.
if query.data.split(':')[1] == "si":
result = f"✅ Sumade a {project_name}!"
new_vote.interest = True
else:
new_vote.interest = False
result = f'❌ Proyecto {project_name} salteado.'
try:
new_vote.save()
await context.bot.edit_message_text(text=result,
chat_id=query.message.chat_id,
message_id=query.message.message_id)
except peewee.IntegrityError:
logger.warning(f"Error al guardar la eleccion de {username} en el proyecto {project_name}")
await context.bot.edit_message_text(
text=f"Ya te habías sumado al proyecto {project_name}!",
chat_id=query.message.chat_id,
message_id=query.message.message_id
)
@vote_authorized
async def vote(update, context):
logger.info("Vote message")
await update.message.reply_text(
'Te interesa el proyecto:'
)
# if there is not project in the database, create a new project
if not Project.select().exists():
user = Pycampista.get_or_create(
username=update.message.from_user.username,
chat_id=str(update.message.chat_id),
)[0]
Project.create(name='PROYECTO DE PRUEBA', owner=user)
# ask user for each project in the database
for project in Project.select():
keyboard = [[InlineKeyboardButton("Me Sumo!", callback_data=f"{VOTE_PATTERN}:si"),
InlineKeyboardButton("Paso", callback_data=f"{VOTE_PATTERN}:no")]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
text=project.name,
reply_markup=reply_markup
)
@admin_needed
@active_needed
@vote_authorized
async def end_voting(update, context):
is_active, pycamp = get_active_pycamp()
pycamp.vote_authorized = False
pycamp.save()
await update.message.reply_text("Selección cerrada")
await msg_to_active_pycamp_chat(context.bot, "La selección de proyectos ha finalizado.")
@admin_needed
async def vote_count(update, context):
votes = [vote.pycampista_id for vote in Vote.select()]
vote_count = len(set(votes))
await context.bot.send_message(
chat_id=update.message.chat_id,
text=f"Votaron: {vote_count}"
)
def set_handlers(application):
application.add_handler(
CallbackQueryHandler(button, pattern=f'{VOTE_PATTERN}:'))
application.add_handler(
CommandHandler('empezar_votacion_proyectos', start_voting))
application.add_handler(
CommandHandler('votar', vote))
application.add_handler(
CommandHandler('terminar_votacion_proyectos', end_voting))
application.add_handler(
CommandHandler('contar_votos', vote_count))