diff --git a/helpers/jokes.py b/helpers/jokes.py index 70d7711..1f0784d 100644 --- a/helpers/jokes.py +++ b/helpers/jokes.py @@ -1,4 +1,5 @@ import logging +import random from time import sleep from requests import get @@ -27,6 +28,13 @@ def fetch_jokes(): i += 1 +def get_random() -> str: + count_docs = mongo.jokes_collection.count_documents({}) + rnd = random.randrange(1, count_docs + 1) + anek = mongo.jokes_collection.aggregate([{"$sample": {"size": 1}}])[0] + return anek['text'] + + def poll_jokes(): while True: logging.info("start fetching jokes") diff --git a/processor.py b/processor.py index 22df65a..e03e12c 100644 --- a/processor.py +++ b/processor.py @@ -1,7 +1,6 @@ -import random from functools import cached_property -from helpers.mongo import mongo +from helpers.jokes import get_random class Processor: @@ -14,11 +13,8 @@ class Processor: self.message = data['request']['original_utterance'].lower() def next(self): - count_docs = mongo.jokes_collection.count_documents({}) - rnd = random.randrange(1, count_docs + 1) - anek = mongo.jokes_collection.find_one({"id": rnd}) return { - "text": anek['text'] + "text": get_random() } def save(self): @@ -52,6 +48,8 @@ class Processor: if self.data['session']['new']: return { "text": "Привет! Сейчас мы с тобой пошутим! Чтобы услышать смешную шутеечку, скажи \"следующий\" или \"дальше\". Если ты устал и хочешь закончить, скажи \"закончить\" или \"хватит\"." + "Держи первый анекдот:" + f"{get_random()}" } action = None for key, value in self.handlers.items():