yt-dlp-bot/app_bot/bot/core/utils.py

68 lines
1.7 KiB
Python
Raw Normal View History

2022-02-04 06:21:27 +08:00
"""Utils module."""
import asyncio
import random
import string
from datetime import datetime
from uuid import uuid4
2023-03-30 03:51:49 +08:00
from pyrogram.enums import ChatType
2022-06-11 04:35:48 +08:00
from pyrogram.types import Message
2022-02-04 06:21:27 +08:00
async def shallow_sleep_async(sleep_time: float = 0.1) -> None:
await asyncio.sleep(sleep_time)
def gen_uuid() -> str:
return uuid4().hex
def gen_random_str(length=4) -> str:
return ''.join(
2022-06-11 04:35:48 +08:00
random.SystemRandom().choice(string.ascii_lowercase + string.digits)
for _ in range(length)
)
2022-02-04 06:21:27 +08:00
def format_ts(ts: float, time_format: str = '%a %b %d %H:%M:%S %Y') -> str:
return datetime.fromtimestamp(ts).strftime(time_format)
def bold(text: str) -> str:
"""Wrap input string in HTML bold tag."""
return f'<b>{text}</b>'
def code(text: str) -> str:
"""Wrap input string in HTML code tag."""
return f'<code>{text}</code>'
def get_user_info(message: Message) -> str:
"""Return user information who interacts with bot."""
chat = message.chat
2022-06-11 04:35:48 +08:00
return (
f'Request from user_id: {chat.id}, username: {chat.username}, '
f'full name: {chat.first_name} {chat.last_name}'
)
2022-02-04 06:21:27 +08:00
2023-03-30 03:51:49 +08:00
def get_user_id(message: Message) -> int:
"""Make explicit selection to not forget how this works since we just can return
`message.chat.id` for all cases.
"""
match message.chat.type:
case ChatType.PRIVATE:
return message.from_user.id
case ChatType.GROUP:
return message.chat.id
case _:
return message.chat.id
2022-02-04 06:21:27 +08:00
def build_command_presentation(commands: dict[str, list]) -> str:
groups = []
for desc, cmds in commands.items():
2022-06-11 04:35:48 +08:00
groups.append('{0}\n{1}'.format(desc, '\n'.join(['/' + c for c in cmds])))
2022-02-04 06:21:27 +08:00
return '\n\n'.join(groups)