Source code for my personal quote bot project.
1#!/usr/bin/env python3
2
3import time
4import random
5import os
6import logging
7import hashlib
8import copy
9
10from glob import iglob
11from typing import Optional
12from pathlib import Path
13
14import redis
15import typer
16
17def main(source_key, destination_key, rename_key: bool = False, password: str = "", host: str = "localhost", port: int = 16379, quotes_pattern: str = "quotes/**/*.txt", log_level: str = "INFO") -> None:
18 logging.getLogger().setLevel(os.getenv("LOGGING") or log_level)
19
20 new_quotes = tuple(iglob(quotes_pattern, recursive=True))
21 r = redis.Redis(host=host, port=port, decode_responses=True, password=password)
22
23 logging.info("Fetching existing list at key `%s`.", source_key)
24 current_list = r.lrange(source_key, "0", "-1")
25 logging.info("Found list of length %d.", len(current_list))
26
27 new_list = copy.deepcopy(current_list)
28 new_list.extend(Path(p).read_text().strip() for p in new_quotes)
29 random.shuffle(new_list)
30
31 if (actual_len := r.llen(destination_key)) > 0:
32 logging.error("Attempted to push result to non-empty key `%s` (length: %d). Aborting.", destination_key, actual_len)
33 return
34
35 r.lpush(destination_key, *new_list)
36 logging.info("Pushed new, shuffled list (length: %d) successfully to key `%s`.", len(new_list), destination_key)
37
38 if rename_key:
39 logging.info("Renaming `%s` to `%s`.", destination_key, source_key)
40 r.rename(destination_key, source_key)
41
42
43if __name__ == '__main__':
44 random.seed(time.monotonic())
45 typer.run(main)