irctest/irctest/irc_utils/junkdrawer.py

47 lines
1.3 KiB
Python
Raw Normal View History

2020-02-28 04:00:37 +00:00
import datetime
2020-09-13 10:38:15 +00:00
import re
2020-10-21 15:08:14 +00:00
import secrets
import socket
from typing import Dict, Tuple
2020-02-28 04:00:37 +00:00
# thanks jess!
IRCV3_FORMAT_STRFTIME = "%Y-%m-%dT%H:%M:%S.%f%z"
2021-02-22 18:02:13 +00:00
def ircv3_timestamp_to_unixtime(timestamp: str) -> float:
2020-02-28 04:00:37 +00:00
return datetime.datetime.strptime(timestamp, IRCV3_FORMAT_STRFTIME).timestamp()
2020-09-13 10:38:15 +00:00
2021-02-22 18:02:13 +00:00
def random_name(base: str) -> str:
return base + "-" + secrets.token_hex(5)
2021-02-22 18:02:13 +00:00
2020-10-21 15:08:14 +00:00
def find_hostname_and_port() -> Tuple[str, int]:
"""Find available hostname/port to listen on."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 0))
(hostname, port) = s.getsockname()
s.close()
return (hostname, port)
2020-09-13 10:38:15 +00:00
"""
Stolen from supybot:
"""
2021-02-22 18:02:13 +00:00
2020-09-13 10:38:15 +00:00
class MultipleReplacer:
"""Return a callable that replaces all dict keys by the associated
value. More efficient than multiple .replace()."""
# We use an object instead of a lambda function because it avoids the
# need for using the staticmethod() on the lambda function if assigning
# it to a class in Python 3.
def __init__(self, dict_: Dict[str, str]):
2020-09-13 10:38:15 +00:00
self._dict = dict_
2021-02-22 18:02:13 +00:00
dict_ = dict([(re.escape(key), val) for key, val in dict_.items()])
self._matcher = re.compile("|".join(dict_.keys()))
def __call__(self, s: str) -> str:
2020-09-13 10:38:15 +00:00
return self._matcher.sub(lambda m: self._dict[m.group(0)], s)