diff options
author | 2020-09-09 15:49:05 -0700 | |
---|---|---|
committer | 2020-09-09 15:49:05 -0700 | |
commit | 434e9a65529d77a0954255781c8792de60ab28d6 (patch) | |
tree | f534047a431b71b329f7699591c9fb1a11b4efb9 | |
parent | Removed logging. (diff) |
Added RandomCycle utility to jump between set indexes repeatedly.
-rw-r--r-- | bot/exts/evergreen/conversationstarters.py | 13 | ||||
-rw-r--r-- | bot/utils/randomization.py | 19 |
2 files changed, 22 insertions, 10 deletions
diff --git a/bot/exts/evergreen/conversationstarters.py b/bot/exts/evergreen/conversationstarters.py index 68790dca..ebefc53e 100644 --- a/bot/exts/evergreen/conversationstarters.py +++ b/bot/exts/evergreen/conversationstarters.py @@ -1,5 +1,3 @@ -import itertools -import random from pathlib import Path import yaml @@ -8,6 +6,7 @@ from discord.ext import commands from bot.constants import WHITELISTED_CHANNELS from bot.utils.decorators import override_in_channel +from bot.utils.randomization import RandomCycle SUGGESTION_FORM = 'https://forms.gle/zw6kkJqv8U43Nfjg9' @@ -25,14 +24,8 @@ with Path("bot/resources/evergreen/py_topics.yaml").open("r", encoding="utf8") a ALL_ALLOWED_CHANNELS = [channel_id for channel_id in PY_TOPICS.keys()] + list(WHITELISTED_CHANNELS) # Putting all topics into one dictionary and shuffling lists to reduce same-topic repetitions. -TOPICS = {} -for k, v in {**{'default': STARTERS}, **PY_TOPICS}.items(): - if len(v): - random.shuffle(v) - TOPICS[k] = itertools.cycle(v) - - else: - TOPICS[k] = False +all_topics = {'default': STARTERS, **PY_TOPICS} +TOPICS = {channel: RandomCycle(topics) if len(topics) else False for channel, topics in all_topics.items()} class ConvoStarters(commands.Cog): diff --git a/bot/utils/randomization.py b/bot/utils/randomization.py new file mode 100644 index 00000000..063d7e1f --- /dev/null +++ b/bot/utils/randomization.py @@ -0,0 +1,19 @@ +import itertools +import random +import typing as t + + +class RandomCycle: + """Cycling through jumping to random indexes in an iterable.""" + + def __init__(self, iterable: t.Iterable) -> None: + self.iterable = list(iterable) + self.index = itertools.cycle(range(len(iterable))) + + def __next__(self) -> t.Any: + idx = next(self.index) + + if idx == 0: + random.shuffle(self.iterable) + + return self.iterable[idx] |