Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,22 @@
CallbackQueryHandler, ConversationHandler, ContextTypes,
)

from telegram_bot.actions.confirmation import process_confirmation
from telegram_bot.actions.start_date import process_meeting_start_date
from telegram_bot.actions.start_time import process_meeting_start_time
from telegram_bot.constants import ENTER_START_TIME, ENTER_MEETING_TYPE, ENTER_START_DATE, MEETING_NAME, \
MEETING_DESCRIPTION, ENTER_NUM_PLAYERS
MEETING_DESCRIPTION, ENTER_NUM_PLAYERS, ENTER_CONFIRMATION
from utils.logger import logger
from telegram_bot.quedada_entry import quedada
from telegram_bot.message_handler import first_answer, second_answer, process_num_players
from telegram_bot.actions.action_handler import action_handler
from telegram_bot.actions.meeting_type import process_meeting_type
from telegram_bot.actions.attendance import attendance_button_handler
import tracemalloc
from dotenv import load_dotenv
import os

tracemalloc.start()





def main():
logger.info("Starting the bot application")

Expand All @@ -42,9 +41,10 @@ def main():
MEETING_NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, first_answer)],
MEETING_DESCRIPTION: [MessageHandler(filters.TEXT & ~filters.COMMAND, second_answer)],
ENTER_NUM_PLAYERS: [CallbackQueryHandler(process_num_players)],
ENTER_START_TIME: [CallbackQueryHandler(action_handler)],
ENTER_START_DATE: [CallbackQueryHandler(action_handler)],
ENTER_MEETING_TYPE: [CallbackQueryHandler(action_handler)],
ENTER_START_DATE: [CallbackQueryHandler(process_meeting_start_date)],
ENTER_START_TIME: [CallbackQueryHandler(process_meeting_start_time)],
ENTER_MEETING_TYPE: [CallbackQueryHandler(process_meeting_type)],
ENTER_CONFIRMATION: [CallbackQueryHandler(process_confirmation)],
},
fallbacks=[CommandHandler("cancel", cancel)],
)
Expand Down
Binary file modified requirements.txt
Binary file not shown.
48 changes: 0 additions & 48 deletions telegram_bot/actions/action_handler.py

This file was deleted.

62 changes: 26 additions & 36 deletions telegram_bot/actions/attendance.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,53 +15,43 @@ async def attendance_button_handler(update: Update, context: ContextTypes.DEFAUL
alert, response_msg = handle_meeting_action(event_id, action, username,context)
await query.answer(response_msg, show_alert=alert)
logger.info(response_msg)

message = build_final_message(context.chat_data[event_id])
message = "¿Desea confirmar creación de la partida?\n" + message
reply_markup = build_attendance_keyboard(event_id)

with suppress(telegram.error.BadRequest):
await query.edit_message_text(message, reply_markup=reply_markup, parse_mode='Markdown')

def handle_meeting_action(event_id, action, username, context):
alert = False
response_msg = ''

# We handle the event of user joining, leaving, adding or removing a guest
found = any(username in user for user in context.chat_data[event_id]["players"])
#We check if the user is already present on the list
if found:
#We get the index of the person already present on the list
if action == "join":
if is_fullgame(context, event_id) and action in ('join', '+1'):
response_msg = "Partida sin sitios disponibles"
elif action == "join":
if username in context.chat_data[event_id]["players"]:
response_msg = "Usuario ya agregado en la lista"
elif action == "+1":
if is_fullgame(context, event_id):
response_msg = "Partida sin sitios disponibles"
else:
#We add +1 to the guest field
context.chat_data[event_id]["players"][username] += 1
response_msg = f"{username} +1!"
elif action == "leave":
#We remove the user from the list
else:
context.chat_data[event_id]["players"][username] = 0
response_msg = f"{username} joined!"
elif action == "leave":
if username in context.chat_data[event_id]["players"]:
del context.chat_data[event_id]["players"][username]
response_msg = "Usuario quitado de la quedada"
elif action == "-1":
#We verify if the user has guests
if context.chat_data[event_id]["players"][username] > 0:
context.chat_data[event_id]["players"][username] -= 1
else:
response_msg = "Sin invitados que quitar"
alert = True
else:
if action == 'join':
if is_fullgame(context, event_id):
response_msg = "Partida sin sitios disponibles"
else:
context.chat_data[event_id]["players"][username] = 0
response_msg = f"{username} joined!"
elif action == "+1":
if is_fullgame(context, event_id):
response_msg = "Partida sin sitios disponibles"
else:
context.chat_data[event_id]["players"][username] += 0
response_msg = f"{username} +1!"
elif action == '-1':
elif action == "+1":
if username in context.chat_data[event_id]["players"]:
# We add +1 to the guest field
context.chat_data[event_id]["players"][username] += 1
else:
context.chat_data[event_id]["players"][username] = 0
response_msg = f"{username} +1!"
elif action == '-1':
if username not in context.chat_data[event_id]["players"]:
response_msg = "El usuario no está en la lista"
elif context.chat_data[event_id]["players"][username] > 0:
context.chat_data[event_id]["players"][username] -= 1
else:
response_msg = "Sin invitados que quitar"
alert = True
return alert, response_msg
36 changes: 36 additions & 0 deletions telegram_bot/actions/confirmation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from telegram import Update
from telegram.ext import ConversationHandler, CallbackContext

from telegram_bot.final_message_builder import build_final_message
from telegram_bot.keyboards.keyboard_builder import build_attendance_keyboard
from utils.logger import logger
from telegram_bot.apis.gcalendar import create_event


async def process_confirmation(update: Update, context: CallbackContext) -> None:
query = update.callback_query
action = query.data
if str(query.from_user.id) != str(context.chat_data["current"]["creator_id"]):
return

if action == "submit":
event_message_id = context.chat_data["current_event_id"]

# Persists the collected game info and creates the GCalendar event
context.chat_data[event_message_id] = context.chat_data["current"]

logger.info("Summary keyboard about to show")
message = build_final_message(context.chat_data["current"])
reply_markup = build_attendance_keyboard(context.chat_data["current_event_id"])
await query.edit_message_text(message, reply_markup=reply_markup, parse_mode='Markdown')

create_event(context.chat_data[event_message_id])
else:
await query.edit_message_text(f"Creación de partida '{context.chat_data['current']['meeting_name']}' cancelada", parse_mode='Markdown')

# Cleans the draft game info so that another game could be created
del context.chat_data["current_event_id"]
del context.chat_data["current"]

result = ConversationHandler.END
return result
33 changes: 17 additions & 16 deletions telegram_bot/actions/meeting_type.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
from utils.logger import logger
from ..keyboards.keyboard_builder import build_attendance_keyboard
from ..constants import ENTER_CONFIRMATION
from ..keyboards.confirm_keyboard import build_confirm_keyboard
from ..final_message_builder import build_final_message
import re
from datetime import datetime
from telegram.ext import ContextTypes
from telegram import InlineKeyboardMarkup
from telegram.ext import ContextTypes, ConversationHandler
from telegram import Update


async def process_meeting_type(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
action = query.data
if str(query.from_user.id) != str(context.chat_data["current"]["creator_id"]):
return

def process_meeting_type(action: str,context: ContextTypes.DEFAULT_TYPE) -> (str, InlineKeyboardMarkup):
"""
We mark the event as open or closed in the shared dictionary
:param action:
:param context:
:return:
"""
context.chat_data["current"]["meeting_type"] = str(action)
message = build_final_message(context.chat_data["current"])
reply_markup = build_attendance_keyboard(context.chat_data["current_event_id"])
logger.info("Summary keyboard about to show")
return message, reply_markup
reply_markup = build_confirm_keyboard()

result = ENTER_CONFIRMATION

await query.edit_message_text(message, reply_markup=reply_markup, parse_mode='Markdown')
return result
46 changes: 34 additions & 12 deletions telegram_bot/actions/start_date.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,39 @@
from utils.logger import logger
from ..constants import ENTER_START_TIME, ENTER_START_DATE
from ..keyboards.calendar_keyboard import create_calendar_keyboard
from ..keyboards.time_keyboard_builder import build_time_keyboard
import re
from datetime import datetime
from telegram.ext import ContextTypes
from telegram import InlineKeyboardMarkup
from telegram.ext import ContextTypes, ConversationHandler
from telegram import InlineKeyboardMarkup, Update

def process_meeting_start_date(action: str,context: ContextTypes.DEFAULT_TYPE) -> (str, InlineKeyboardMarkup):
# We trim the 'CALENDAR;start_date;' string to insert the date into the context_data dictionary
start_date = re.sub('CALENDAR;start_date;', '', str(action))
start_date = datetime.strptime(start_date, '%Y;%m;%d').date()
context.chat_data["current"]["start_date"] = start_date
message = "Indique la hora de inicio"
reply_markup = build_time_keyboard('start_time')
log_message = "Start time keyboard about to show"
logger.info(log_message)
return message, reply_markup
async def process_meeting_start_date(update: Update, context: ContextTypes.DEFAULT_TYPE) -> ConversationHandler:
query = update.callback_query
action = query.data
if str(query.from_user.id) != str(context.chat_data["current"]["creator_id"]):
return

if any(x in action for x in ("PREV-MONTH", "NEXT-MONTH")):
arguments = action.split(';')
year = arguments[2]
month = arguments[3]
date_type = "start_date"

reply_markup = create_calendar_keyboard(date_type, year, month)
message="Indique la fecha de inicio"
result = ENTER_START_DATE
else:
# We trim the 'CALENDAR;start_date;' string to insert the date into the context_data dictionary
start_date = re.sub('CALENDAR;start_date;', '', str(action))
start_date = datetime.strptime(start_date, '%Y;%m;%d').date()
context.chat_data["current"]["start_date"] = start_date

log_message = "Start time keyboard about to show"
logger.info(log_message)

reply_markup = build_time_keyboard('start_time')
message = "Indique la hora de inicio"
result = ENTER_START_TIME

await query.edit_message_text(message, reply_markup=reply_markup, parse_mode='Markdown')
return result
22 changes: 16 additions & 6 deletions telegram_bot/actions/start_time.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
from utils.logger import logger
from ..constants import ENTER_MEETING_TYPE
from ..keyboards.status_keyboard import build_meeting_type_keyboard
import re
from datetime import datetime
from telegram.ext import ContextTypes
from telegram import InlineKeyboardMarkup
from telegram.ext import ContextTypes, ConversationHandler
from telegram import InlineKeyboardMarkup, Update


def process_meeting_start_time(action: str,context: ContextTypes.DEFAULT_TYPE) -> (str, InlineKeyboardMarkup):
message = "Indique si la quedada es abierta o cerrada"
async def process_meeting_start_time(update: Update, context: ContextTypes.DEFAULT_TYPE) -> ConversationHandler:
query = update.callback_query
if str(query.from_user.id) != str(context.chat_data["current"]["creator_id"]):
return


action = query.data
# We trim the 'Start-' string to insert the hour into the context_data dictionary
context.chat_data["current"]["start_time"] = re.sub('start_time-', '', str(action))
# We build the keyboard asking for meeting status
reply_markup = build_meeting_type_keyboard()
logger.info("Meeting type keyboad about to show")
return message, reply_markup

reply_markup = build_meeting_type_keyboard()
message = "Indique si la quedada es abierta o cerrada"
await query.edit_message_text(message, reply_markup=reply_markup, parse_mode='Markdown')
result = ENTER_MEETING_TYPE
return result
Empty file added telegram_bot/apis/__init__.py
Empty file.
44 changes: 44 additions & 0 deletions telegram_bot/apis/gcalendar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from googleapiclient.discovery import build
import pickle
import datetime as dt

from utils.logger import logger

service = None

try:
with open("desktop_token.pkl", "rb") as token:
creds = pickle.load(token)
service = build("calendar", "v3", credentials=creds)
except FileNotFoundError:
logger.info("Could not create GCalendar API service: No token.pkl found")

def create_event(game_info):
global service

if service is None:
logger.info('Could not create calendar event due to the lack of a token')
return

start_time = dt.time.fromisoformat(game_info['start_time'])
start_dt = dt.datetime.combine(game_info['start_date'], start_time)

end_dt = start_dt + dt.timedelta(minutes=120)

event = {
'summary': game_info['meeting_name'],
'location': 'Asociación Draco Rúa Merced, 59, 15009 A Coruña',
'description': game_info['meeting_description'],
'start': {
'dateTime': start_dt.isoformat(),
'timeZone': 'Europe/Madrid',
},
'end': {
'dateTime': end_dt.isoformat(),
'timeZone': 'Europe/Madrid',
},
}

calendar_id = "primary" # or your shared calendar's ID
created_event = service.events().insert(calendarId=calendar_id, body=event).execute()
return created_event['htmlLink']
Loading