|
| 1 | +import json |
| 2 | +import logging |
| 3 | +from random import choice |
| 4 | + |
| 5 | +from chatterbot import ChatBot |
| 6 | +from chatterbot.trainers import ChatterBotCorpusTrainer |
| 7 | +from PyMatcha import redis |
| 8 | +from PyMatcha.models.like import Like |
| 9 | +from PyMatcha.models.user import User |
| 10 | +from PyMatcha.models.view import View |
| 11 | +from PyMatcha.utils.recommendations import create_user_recommendations |
| 12 | +from PyMatcha.utils.static import BACKEND_ROOT |
| 13 | + |
| 14 | +# TODO: message new conversation, respond to unread message, send a new message in already started conversation |
| 15 | + |
| 16 | + |
| 17 | +def bot_response(bot_name, user_input): |
| 18 | + logging.debug(f"Starting chatbot with name {bot_name}") |
| 19 | + chatbot = ChatBot( |
| 20 | + bot_name, |
| 21 | + storage_adapter="chatterbot.storage.SQLStorageAdapter", |
| 22 | + database_uri=f"sqlite:///{BACKEND_ROOT}/../chatbot_database.sqlite3", |
| 23 | + ) |
| 24 | + |
| 25 | + trainer = ChatterBotCorpusTrainer(chatbot, show_training_progress=False) |
| 26 | + trainer.train( |
| 27 | + "chatterbot.corpus.english.conversations", |
| 28 | + "chatterbot.corpus.english.emotion", |
| 29 | + "chatterbot.corpus.english.greetings", |
| 30 | + "chatterbot.corpus.english.humor", |
| 31 | + "PyMatcha.utils.dating", |
| 32 | + ) |
| 33 | + return chatbot.get_response(user_input) |
| 34 | + |
| 35 | + |
| 36 | +def _get_recommendations(bot_user: User): |
| 37 | + recommendations = redis.get(f"user_recommendations:{str(bot_user.id)}") |
| 38 | + if not recommendations: |
| 39 | + create_user_recommendations(bot_user) |
| 40 | + recommendations = redis.get(f"user_recommendations:{str(bot_user.id)}") |
| 41 | + if not recommendations: |
| 42 | + raise ValueError("Recommendations could not be calculated") |
| 43 | + return json.loads(recommendations) |
| 44 | + |
| 45 | + |
| 46 | +def bot_like(bot_user: User, is_superlike: bool): |
| 47 | + recommendations = _get_recommendations(bot_user) |
| 48 | + liked_ids = [like.liked_id for like in bot_user.get_likes_sent()] |
| 49 | + for user in recommendations: |
| 50 | + if user["id"] in liked_ids: |
| 51 | + recommendations.remove(user) |
| 52 | + user_to_like = choice(recommendations) |
| 53 | + Like.create(liker_id=bot_user.id, liked_id=user_to_like["id"], is_superlike=is_superlike) |
| 54 | + |
| 55 | + |
| 56 | +def bot_unlike(bot_user: User): |
| 57 | + liked_ids = [like.liked_id for like in bot_user.get_likes_sent()] |
| 58 | + id_to_unlike = choice(liked_ids) |
| 59 | + Like.get_multi(liker_id=bot_user.id, liked_id=id_to_unlike).delete() |
| 60 | + |
| 61 | + |
| 62 | +def bot_view(bot_user: User): |
| 63 | + recommendations = _get_recommendations(bot_user) |
| 64 | + user_to_view = choice(recommendations) |
| 65 | + View.create(profile_id=user_to_view["id"], viewer_id=bot_user.id) |
0 commit comments