Commit 54e907f
Changed files (8)
src/others/download_external.py
@@ -14,7 +14,7 @@ from config import ENABLE, MAX_FILE_BYTES, PREFIX
from message_utils import equal_prefix, modify_progress, send2tg, startswith_prefix
from multimedia import is_valid_video, validate_img
from networking import download_file
-from utils import https_url, readable_size
+from utils import https_url, readable_size, to_int
HELP = f"""
⏬**下载文件**
@@ -40,6 +40,7 @@ async def download_url_in_message(client: Client, message: Message, **kwargs):
message = message.reply_to_message
target_chat = kwargs["target_chat"] if kwargs.get("target_chat") else message.chat.id
+ target_chat = to_int(target_chat)
reply_msg_id = kwargs.get("reply_msg_id", 0)
if reply_msg_id == 0:
reply_to = message.id
src/others/extract_audio.py
@@ -9,6 +9,7 @@ from pyrogram.types import Message, ReplyParameters
from config import ENABLE, PREFIX, cache
from message_utils import equal_prefix, modify_progress, parse_msg, send2tg, startswith_prefix
from multimedia import convert_to_audio, parse_media_info
+from utils import to_int
# ruff: noqa: RUF001
@@ -71,7 +72,7 @@ async def extract_audio_file(client: Client, message: Message, **kwargs) -> None
else:
reply_to = reply_msg_id
reply_parameters = ReplyParameters(message_id=reply_to) # type: ignore
- await client.send_audio(target_chat, Path(path).as_posix(), duration=duration, reply_parameters=reply_parameters)
+ await client.send_audio(to_int(target_chat), Path(path).as_posix(), duration=duration, reply_parameters=reply_parameters)
Path(video).unlink(missing_ok=True)
path.unlink(missing_ok=True)
await modify_progress(del_status=True, **kwargs)
src/others/subtitle.py
@@ -16,6 +16,7 @@ from config import API, ENABLE, PREFIX, PROXY, TOKEN
from database import cache
from message_utils import equal_prefix, modify_progress, send2tg, startswith_prefix
from networking import hx_req, match_social_media_link
+from utils import to_int
HELP = f"""📃**提取字幕**
使用说明:
@@ -55,7 +56,7 @@ async def get_subtitle(client: Client, message: Message, **kwargs):
if subtitles := res.get("subtitle", ""):
length = len(subtitles)
with io.BytesIO(subtitles.encode("utf-8")) as f:
- await client.send_document(target_chat, f, file_name=f"{vid}.vtt-{length}字符.txt", caption=yt_url)
+ await client.send_document(to_int(target_chat), f, file_name=f"{vid}.vtt-{length}字符.txt", caption=yt_url)
elif error := res.get("error", ""):
await modify_progress(text=error, force_update=True, **kwargs)
await asyncio.sleep(3)
src/preview/ytdlp.py
@@ -1,7 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
-import contextlib
import re
import threading
import time
@@ -22,7 +21,7 @@ from message_utils import copy_messages_from_db, modify_progress, preprocess_med
from multimedia import generate_cover
from networking import hx_req
from others.emoji import emojify
-from utils import readable_size, readable_time, soup_to_text, true, ts_to_dt, unicode_to_ascii
+from utils import readable_size, readable_time, soup_to_text, to_int, true, ts_to_dt, unicode_to_ascii
class ProxyError(Exception):
@@ -206,11 +205,9 @@ async def preview_ytdlp(
for idx, video in enumerate(videos):
caption = texts.replace("📝[", f"📝[P{idx + 1}-") if len(videos) > 1 else texts
await modify_progress(text=f"⏫视频上传中-P{idx + 1}: {readable_size(path=video['video'])}\n🎬{Path(video['video']).name}", force_update=True, **kwargs)
- with contextlib.suppress(ValueError):
- target_chat = int(target_chat)
sent_messages.append(
await client.send_video(
- chat_id=target_chat,
+ chat_id=to_int(target_chat),
caption=caption[:CAPTION_LENGTH],
reply_parameters=ReplyParameters(message_id=kwargs.get("reply_msg_id", message.id)),
progress=telegram_uploading,
@@ -222,8 +219,7 @@ async def preview_ytdlp(
target_chat = target_chat if ytdlp_send_audio else TID.CHANNEL_YTDLP_BACKUP # backup to channel if not send audio, so we can save it to db
await modify_progress(text=f"⏫音频上传中: {readable_size(path=audio_path)}\n🎧{audio_path.name}", force_update=True, **kwargs)
thumb = generate_cover(final_path) # generate cover based on final_path
- with contextlib.suppress(ValueError):
- target_chat = int(target_chat)
+ target_chat = to_int(target_chat)
sent_messages.append(
await client.send_audio(
chat_id=target_chat,
src/handler.py
@@ -1,7 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-import contextlib
import re
from loguru import logger
@@ -24,7 +23,7 @@ from preview.twitter import preview_twitter
from preview.weibo import preview_weibo
from preview.xiaohongshu import preview_xhs
from preview.ytdlp import ProxyError, get_ytdlp_proxy, preview_ytdlp
-from utils import true
+from utils import to_int, true
@cache.memoize(ttl=60)
@@ -128,8 +127,7 @@ async def handle_social_media(
return
kwargs |= params_from_msg_text(this_texts) # merge the parameters from the message text
if true(kwargs.get("target_chat")):
- with contextlib.suppress(ValueError):
- kwargs["target_chat"] = int(kwargs["target_chat"])
+ kwargs["target_chat"] = to_int(kwargs["target_chat"])
# message only contains prefix command
if equal_prefix(this_texts, prefix=[*cmd_prefix, "/retry"], ignore_prefix=ignore_prefix):
# without reply, send docs if message only contains prefix command
src/main.py
@@ -24,7 +24,7 @@ from config import DAILY_MESSAGES, DEVICE_NAME, ENABLE, PROXY, TID, TOKEN, TZ, c
from handler import handle_social_media, handle_utilities
from message_utils import parse_msg
from others.raw_img_file import convert_raw_img_file
-from utils import cleanup_old_files, nowdt
+from utils import cleanup_old_files, nowdt, to_int
# ruff: noqa: RUF001
@@ -127,9 +127,8 @@ async def scheduling(client: Client):
logger.warning(f"Invalid DAILY_MESSAGES: {DAILY_MESSAGES}")
with contextlib.suppress(Exception):
for chat_id, msg in daliy.items():
- cid = int(chat_id)
- logger.info(f"Sending daily message to {cid}: {msg}")
- await client.send_message(cid, msg)
+ logger.info(f"Sending daily message to {chat_id}: {msg}")
+ await client.send_message(to_int(chat_id), msg)
if __name__ == "__main__":
src/message_utils.py
@@ -16,7 +16,7 @@ from pyrogram.types import InputMediaPhoto, InputMediaVideo, Message, ReplyParam
from config import CAPTION_LENGTH, DB, TEXT_LENGTH, cache
from database import del_db, get_db, set_db
from multimedia import fix_video_rotation, generate_cover, is_valid_video, parse_media_info, split_large_video, split_long_img, validate_img
-from utils import readable_size, smart_split
+from utils import readable_size, smart_split, to_int
# ruff: noqa: RUF001
@@ -290,14 +290,13 @@ async def send2tg(
if not target_chat:
target_chat = kwargs["target_chat"] if kwargs.get("target_chat") else message.chat.id
- with contextlib.suppress(ValueError):
- target_chat = int(target_chat)
- if reply_msg_id == 0:
+ target_chat = to_int(target_chat)
+ if str(reply_msg_id) == "0":
reply_to = message.id
- elif reply_msg_id == -1:
+ elif str(reply_msg_id).lower() in ["-1", "none", "null", "false"]:
reply_to = None
else:
- reply_to = reply_msg_id
+ reply_to = to_int(reply_msg_id)
reply_parameters = ReplyParameters(message_id=reply_to) # type: ignore
sent_messages: list[Message | None] = [] # save sent messages results
src/utils.py
@@ -66,6 +66,14 @@ def split_parts(first: int = 0, middle: int = 0, last: int = 0) -> dict:
return data
+def to_int(var: str | float) -> str | int:
+ """Convert a string or float to an integer."""
+ try:
+ return int(float(var))
+ except (ValueError, TypeError):
+ return str(var)
+
+
def rand_string(length: int = 48) -> str:
return "".join(random.choices(string.ascii_letters + string.digits, k=length))