Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add comments in wishlist #14

Merged
merged 4 commits into from
Nov 19, 2023
Merged
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
1 change: 0 additions & 1 deletion .github/workflows/pylint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,3 @@ jobs:
- name: Analysing code typing with mypy
run: |
mypy --install-types --non-interactive $(git ls-files '*.py')
mypy $(git ls-files '*.py')
79 changes: 38 additions & 41 deletions src/flantier/_commands_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@
from logging import getLogger

from telegram import (
ForceReply,
Update,
)
from telegram.ext import (
CallbackContext,
)

from flantier import _keyboards
from flantier._roulette import Roulette
from flantier._settings import SettingsManager
from flantier._users import UserManager
Expand Down Expand Up @@ -79,9 +77,44 @@ def close_registrations(update: Update, context: CallbackContext) -> None:
)


# bot.delete_message(
# chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
# )
def process(update: Update, context: CallbackContext) -> None:
"""Lance le tirage au sort et envoie les réponses en message privé."""
if not is_admin(update, context):
return

roulette = Roulette()

if not roulette.is_ready():
context.bot.send_message(
chat_id=update.message.chat_id,
text="⚠️ Les inscriptions ne sont pas encore terminées. ⚠️",
)
return

if roulette.tirage() != 0:
context.bot.send_message(
chat_id=update.message.chat_id,
text="⚠️ Le tirage au sort n'a pas pu être effectué. ⚠️",
)
return

# send results to everyone as private message
user_manager = UserManager()
for user in user_manager.users:
if not user.registered:
pass

giftee = user_manager.get_user(user.giftee)
logger.info("send result to %s: giftee is %d", user.name, giftee.tg_id)

context.bot.send_message(
user.tg_id,
text=f"🎅 Youpi tu offres à {giftee.name} 🎁\n",
)


# LEGACY
#########


def add_spouse(update: Update, context: CallbackContext) -> None:
Expand Down Expand Up @@ -169,39 +202,3 @@ def add_spouse(update: Update, context: CallbackContext) -> None:
),
)
logger.info("set spouse %s for %s", context.args[0], context.args[1]) # type: ignore


def process(update: Update, context: CallbackContext) -> None:
"""Lance le tirage au sort et envoie les réponses en message privé."""
if not is_admin(update, context):
return

roulette = Roulette()

if not roulette.is_ready():
context.bot.send_message(
chat_id=update.message.chat_id,
text="⚠️ Les inscriptions ne sont pas encore terminées. ⚠️",
)
return

if roulette.tirage() != 0:
context.bot.send_message(
chat_id=update.message.chat_id,
text="⚠️ Le tirage au sort n'a pas pu être effectué. ⚠️",
)
return

# send results to everyone as private message
user_manager = UserManager()
for user in user_manager.users:
if not user.registered:
pass

giftee = user_manager.get_user(user.giftee)
logger.info("send result to %s: giftee is %d", user.name, giftee.tg_id)

context.bot.send_message(
user.tg_id,
text=f"🎅 Youpi tu offres à {giftee.name} 🎁\n",
)
26 changes: 9 additions & 17 deletions src/flantier/_commands_santa.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ def wishes(update: Update, _: CallbackContext) -> None:
)


def comments(update: Update, _: CallbackContext) -> None:
"""Affiche la liste de cadeaux et les commentaires associés d'une personne."""
keyboard = build_people_inline_kb("comments")
update.message.reply_text(
"🤷 De qui veux tu consulter la liste de souhaits? 🤷", reply_markup=keyboard
)


def update_wishes_list(update: Update, context: CallbackContext) -> None:
"""Met à jour la liste des cadeaux."""
_santa.create_missing_users()
Expand All @@ -39,22 +47,6 @@ def update_wishes_list(update: Update, context: CallbackContext) -> None:
#########


def comments(update: Update, context: CallbackContext) -> None:
"""Affiche la liste de cadeaux et les commentaires associés d'une personne."""
if len(update.message.text.split(" ")) > 1:
name = update.message.text.split(" ")[1]

reply_del_kb = ReplyKeyboardRemove()
context.bot.send_message(
chat_id=update.message.chat_id,
text=_santa.find_wishes(update.message.from_user.id, name),
reply_markup=reply_del_kb,
)

else:
_keyboards.build_people_keyboard("/commentaires")


def add_gifter(tg_id: int, message: list) -> str:
"""Ajoute un offrant à un cadeau.
vérifie que la personne existe et la disponiblité du cadeau
Expand All @@ -64,7 +56,7 @@ def add_gifter(tg_id: int, message: list) -> str:

# trouve le destinataire dans la liste des participants
if any(qqun.name == name for qqun in participants):
_wishes = _santa.find_wishes(tg_id, name, table=True)
_wishes = UserManager().get_user(qqun.tg_id).wishes

if len(_wishes) > 0 and len(_wishes) >= cadeau_index:
receiver_index = next(
Expand Down
11 changes: 7 additions & 4 deletions src/flantier/_keyboards.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
CallbackContext,
)

from flantier._santa import user_wishes_message
from flantier._santa import user_wishes_message,user_comments_message
from flantier._users import UserManager

logger = getLogger("flantier")
Expand All @@ -34,17 +34,17 @@ def build_people_inline_kb(
Créer le clavier avec les noms des participants. Ajoute la commande en prefix
/offrir, /cadeaux, /commentaires, /exclude
"""
keyboard = [
tkeyboard = [
InlineKeyboardButton(
user.name,
callback_data=command + " " + str(user.tg_id) + " " + str(user.name),
)
for user in UserManager().users
if (not filter_registered or user.registered)
]
keyboard.append(InlineKeyboardButton("Annuler", callback_data="cancel 0 cancel"))
tkeyboard.append(InlineKeyboardButton("Annuler", callback_data="cancel 0 cancel"))
# split keyboard in two columns
keyboard = [keyboard[i : i + COLUMNS] for i in range(0, len(keyboard), COLUMNS)]
keyboard = [tkeyboard[i : i + COLUMNS] for i in range(0, len(tkeyboard), COLUMNS)]
return InlineKeyboardMarkup(keyboard)


Expand Down Expand Up @@ -90,6 +90,9 @@ def user_button(update: Update, _: CallbackContext) -> None:
if command == "wishes":
text = user_wishes_message(user_name)

if command == "comments":
text = user_comments_message(user_name)

# TODO "/offrir" text = "À qui veux-tu offrir ?"
# TODO "/commentaires, /exclude"
logger.info("response: %s", text)
Expand Down
35 changes: 32 additions & 3 deletions src/flantier/_santa.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from apiclient.discovery import build

from flantier._settings import SettingsManager
from flantier._users import User, UserManager
from flantier._users import User, UserManager, Wish

logger = getLogger("flantier")

Expand Down Expand Up @@ -62,22 +62,51 @@ def update_wishes_list() -> None:
for column in range(0, len(values), 2):
name = values[column][0]
gifts = values[column][1:]
comments = values[column + 1][1:]
logger.debug("mise à jour des cadeaux de %s", name)

user = user_manager.search_user(name)
if not user:
pass
user.wishes = gifts

# user.wishes = list(zip(gifts, comments))

wishes = []
for i, j in zip(gifts, comments):
logger.info("adding wish \"%s\" with comment \"%s\"", i, j)
wishes.append(Wish(wish=i, comment=j))

user.wishes = wishes
user_manager.update_user(user)


def get_wish_list(user: User) -> str:
"""Récupère la liste des souhaits d'un participant avec son nom."""
return "\n".join(w for w in user.wishes)
return "\n".join(w.wish for w in user.wishes)


def get_comment_list(user: User) -> str:
"""Récupère la liste des commentaires d'un participant avec son nom."""
return "\n".join(w.comment for w in user.wishes)


# called by the people inline keyboard
def user_wishes_message(user_name: str) -> str:
"""Generates the text to send as message with all wishes
from the given user
"""
wishes = get_wish_list(UserManager().search_user(user_name))
text = f"🎅 {user_name} voudrait pour Noël:\n" + wishes
if not wishes:
text = f"🎅 {user_name} ne veut rien pour Noël 🫥"

return text


def user_comments_message(user_name: str) -> str:
"""Generates the text to send as message with all wishes and associated comments
from the given user
"""
wishes = get_wish_list(UserManager().search_user(user_name))
text = f"🎅 {user_name} voudrait pour Noël:\n" + wishes
if not wishes:
Expand Down
43 changes: 32 additions & 11 deletions src/flantier/_users.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,33 @@
#!/usr/bin/python3
"""Gère les utilisateurs stockés dans le fichier de configuration users.json
We are using dataclass to represent Users and wishes (gifts)
source https://www.delftstack.com/howto/python/dataclass-to-json-in-python/
"""

import json
from dataclasses import asdict, dataclass, field, is_dataclass
from logging import getLogger
from pathlib import Path
from typing import Any

DEFAULT_USERS_DB = Path.home() / ".cache/flantier/users.json"

logger = getLogger("flantier")


# @dataclass
# class Wish:
# wish: str # cadeaux qui viennent du google doc
# comment: str # commentaires qui viennent du google doc
# giver: str # la personne qui offre ce cadeau
@dataclass
class Wish:
"""Represents a wish from a user."""

wish: str # cadeaux qui viennent du google doc
comment: str # commentaires qui viennent du google doc
giver: int = 0 # la personne qui offre ce cadeau

def __dict__(self):
return asdict(self)

def __str__(self):
return json.dumps(self.__dict__, ensure_ascii=False)


@dataclass
Expand All @@ -29,27 +40,37 @@ class User:
giftee: int = 0 # telegram id of the person to offer a gift
last_giftee: int = 0 # telegram id of the person who recieved the gift last year
registered: bool = False # is the user registered for secret santa
# TODO use Wish dataclass instead of dict
wishes: list = field(default_factory=list) # list of wishes as tuple (wish, comment)
wishes: list[Wish] = field(
default_factory=list[Wish]
) # list of wishes as Wish objects


class UserJSONEncoder(json.JSONEncoder):
"""JSON encoder for User class."""
"""JSON encoder for User and Wish classes."""

def default(self, o):
if is_dataclass(o):
return asdict(o)
return super().default(o)

# pylint: disable=C0103,R1710
def UserJSONDecoder(json_dict: dict) -> Any:
"""JSON decoder function for User and Wish classes."""
if "tg_id" in json_dict:
return User(**json_dict)
if "wish" in json_dict:
return Wish(**json_dict)


def user_list_to_json(users: list) -> str:
"""Convertit la liste des utilisateurs en JSON."""
"""Convert """
return json.dumps(users, cls=UserJSONEncoder, indent=4, ensure_ascii=False)


def json_to_user_list(data: str) -> list:
"""Convertit le JSON en liste d'utilisateurs."""
return json.loads(data, object_hook=lambda d: User(**d))
# return json.loads(data, object_hook=lambda d: User(**d))
return json.loads(data, object_hook=UserJSONDecoder)


class UserManager:
Expand Down Expand Up @@ -110,7 +131,7 @@ def add_user(self, tg_id: int, name: str) -> bool:
logger.info("updating user %s: %d", name, tg_id)
user.tg_id = tg_id
else:
logger.info("Aadding user %s: %d", name, tg_id)
logger.info("adding user %s: %d", name, tg_id)
self.users.append(User(tg_id, name))

logger.debug("users: %s", self.users)
Expand Down
2 changes: 1 addition & 1 deletion src/flantier/settings_template.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ administrator = 0 # Telegram user id of the bot administrator
api_key = '' # Google API Token to access Google Sheets API for gift list
spreadsheet_id = ''
sheet_id = ''
data_range = 'A1:AB30' # select the area where to search for whishes in sheet
data_range = 'A1:AK30' # select the area where to search for whishes in sheet
4 changes: 1 addition & 3 deletions src/oss117audio/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@
SITE = "https://zonesons.com"
# pylint: disable=C0301
OSS1 = "/repliques-cultes-de-films-d-espionnage/phrases-cultes-de-oss-117-le-caire-nid-d-espions"
OSS2 = (
"/repliques-cultes-de-films-d-espionnage/phrases-cultes-de-oss-117-rio-ne-repond-plus"
)
OSS2 = "/repliques-cultes-de-films-d-espionnage/phrases-cultes-de-oss-117-rio-ne-repond-plus"
FILMS = [OSS1, OSS2]
AUDIO_BASE_FOLDER = Path.home() / ".cache/flantier/"

Expand Down
Loading