mirror of
https://github.com/TheFunny/TelegramTwitterMediaBot.git
synced 2026-09-23 23:32:05 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
817b44c7bb
|
||
|
|
55ae73ee6b
|
||
|
|
d6589fec5b
|
@@ -1,3 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
from functools import wraps
|
||||
from typing import TYPE_CHECKING
|
||||
@@ -8,7 +10,7 @@ from telegram.ext import (ApplicationBuilder, CallbackQueryHandler, CommandHandl
|
||||
InlineQueryHandler, MessageHandler, PicklePersistence, filters)
|
||||
|
||||
import common
|
||||
from tweet import TGTweet
|
||||
from tweet import TelegramTweet
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from telegram import Chat, Message, Update
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
from typing import Generator
|
||||
from functools import cached_property
|
||||
from typing import TYPE_CHECKING
|
||||
from uuid import uuid4
|
||||
|
||||
from httpx import AsyncClient
|
||||
from telegram import (InlineQueryResultMpeg4Gif, InlineQueryResultPhoto, InlineQueryResultVideo, InputMediaPhoto,
|
||||
@@ -7,6 +11,9 @@ from telegram import (InlineQueryResultMpeg4Gif, InlineQueryResultPhoto, InlineQ
|
||||
|
||||
from common import get_logger, x_media_regex, x_tco_regex, x_url_regex
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import Generator, TypedDict
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
@@ -18,15 +25,15 @@ message_raw_text = """{url}
|
||||
"""
|
||||
|
||||
|
||||
def create_client() -> 'AsyncClient':
|
||||
def create_client() -> AsyncClient:
|
||||
return AsyncClient(http2=True)
|
||||
|
||||
|
||||
async def close_client(_client: 'AsyncClient') -> None:
|
||||
async def close_client(_client: AsyncClient) -> None:
|
||||
await _client.aclose()
|
||||
|
||||
|
||||
async def fetch_json(_client: 'AsyncClient', url: str) -> dict:
|
||||
async def fetch_json(_client: AsyncClient, url: str) -> dict:
|
||||
logger.info(f"Fetching {url}")
|
||||
response = await _client.get(url)
|
||||
assert response.status_code == response.is_success, f"Failed to fetch {url}, status code {response.status_code}"
|
||||
@@ -34,6 +41,8 @@ async def fetch_json(_client: 'AsyncClient', url: str) -> dict:
|
||||
|
||||
|
||||
class TweetMedia:
|
||||
__slots__ = ('_url', '_thumb', '_type', '__dict__')
|
||||
|
||||
def __init__(self, url: str, thumb: str, media_type: str):
|
||||
self._url: str = url
|
||||
self._thumb: str = thumb
|
||||
@@ -42,14 +51,14 @@ class TweetMedia:
|
||||
def __str__(self):
|
||||
return f"Media[url: {self.url} thumb: {self.thumb} type: {self.type}]"
|
||||
|
||||
@property
|
||||
@cached_property
|
||||
def _uri(self) -> str | None:
|
||||
match = x_media_regex.match(self._url)
|
||||
if match:
|
||||
return match.group(2).removesuffix('.jpg').removesuffix('.png')
|
||||
return None
|
||||
|
||||
@property
|
||||
@cached_property
|
||||
def url(self) -> str:
|
||||
match self._type:
|
||||
case "image":
|
||||
@@ -61,7 +70,7 @@ class TweetMedia:
|
||||
case _:
|
||||
return self._url
|
||||
|
||||
@property
|
||||
@cached_property
|
||||
def thumb(self) -> str:
|
||||
match self._type:
|
||||
case "image":
|
||||
@@ -79,6 +88,8 @@ class TweetMedia:
|
||||
|
||||
|
||||
class Tweet:
|
||||
__slots__ = ('_id', '_author', '_author_id', '_text', '_media', '_sensitive', '__dict__')
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tweet_id: str,
|
||||
@@ -99,7 +110,7 @@ class Tweet:
|
||||
def id(self) -> str:
|
||||
return self._id
|
||||
|
||||
@property
|
||||
@cached_property
|
||||
def url(self) -> str:
|
||||
return f"https://twitter.com/{self._author_id}/status/{self._id}"
|
||||
|
||||
@@ -107,7 +118,7 @@ class Tweet:
|
||||
def author(self) -> str:
|
||||
return self._author
|
||||
|
||||
@property
|
||||
@cached_property
|
||||
def author_url(self) -> str:
|
||||
return f"https://twitter.com/{self._author_id}"
|
||||
|
||||
@@ -125,7 +136,60 @@ class Tweet:
|
||||
|
||||
|
||||
class TGTweet(Tweet):
|
||||
_httpx_client: AsyncClient
|
||||
class TweetInfo(TypedDict):
|
||||
tweetID: str
|
||||
user_name: str
|
||||
user_screen_name: str
|
||||
text: str
|
||||
media_extended: list[dict]
|
||||
possibly_sensitive: bool
|
||||
|
||||
|
||||
class ProcessTweet:
|
||||
__slots__ = ('_httpx_client', '_url', '_tweet')
|
||||
|
||||
def __init__(self, httpx_client: AsyncClient, url: str):
|
||||
self._httpx_client: AsyncClient = httpx_client
|
||||
self._url: str = url
|
||||
|
||||
async def __aenter__(self):
|
||||
self._tweet = await self._fetch_tweet()
|
||||
return Tweet(
|
||||
tweet_id=self._tweet["tweetID"],
|
||||
author=self._tweet["user_name"],
|
||||
author_id=self._tweet["user_screen_name"],
|
||||
text=self._tweet_text,
|
||||
media=self._tweet_media,
|
||||
sensitive=self._tweet["possibly_sensitive"]
|
||||
)
|
||||
|
||||
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||
pass
|
||||
|
||||
async def _fetch_tweet(self) -> TweetInfo:
|
||||
match = x_url_regex.match(self._url)
|
||||
assert match, f"Invalid URL: {self._url}"
|
||||
auther_id, tweet_id = match.group()
|
||||
return await fetch_json(self._httpx_client, vx_api_url.format(auther_id, tweet_id))
|
||||
|
||||
@property
|
||||
def _tweet_text(self) -> str:
|
||||
match = x_tco_regex.search(self._tweet['text'])
|
||||
return self._tweet['text'][:match.start()].strip(" ") if match else self._tweet['text']
|
||||
|
||||
@property
|
||||
def _tweet_media(self) -> list[TweetMedia]:
|
||||
return [
|
||||
TweetMedia(
|
||||
url=tweet_media['url'],
|
||||
thumb=tweet_media['thumbnail_url'],
|
||||
media_type=tweet_media['type']
|
||||
)
|
||||
for tweet_media in self._tweet['media_extended']
|
||||
]
|
||||
|
||||
|
||||
class TelegramTweet:
|
||||
|
||||
def __init__(self, url: str):
|
||||
self._url: str = url
|
||||
@@ -202,18 +266,18 @@ class TGTweet(Tweet):
|
||||
def inline_query_generator(self) -> Generator[
|
||||
InlineQueryResultPhoto | InlineQueryResultVideo | InlineQueryResultMpeg4Gif, None, None
|
||||
]:
|
||||
for i, tweet_media in enumerate(self.media):
|
||||
for tweet_media in self.media:
|
||||
logger.info(str(tweet_media))
|
||||
if tweet_media.type == "image":
|
||||
yield InlineQueryResultPhoto(
|
||||
id=str(i),
|
||||
id=str(uuid4()),
|
||||
photo_url=tweet_media.url,
|
||||
thumbnail_url=tweet_media.thumb,
|
||||
caption=self.message_text
|
||||
)
|
||||
elif tweet_media.type == "video":
|
||||
yield InlineQueryResultVideo(
|
||||
id=str(i),
|
||||
id=str(uuid4()),
|
||||
video_url=tweet_media.url,
|
||||
mime_type="video/mp4",
|
||||
thumbnail_url=tweet_media.thumb,
|
||||
@@ -222,7 +286,7 @@ class TGTweet(Tweet):
|
||||
)
|
||||
elif tweet_media.type == "gif":
|
||||
yield InlineQueryResultMpeg4Gif(
|
||||
id=str(i),
|
||||
id=str(uuid4()),
|
||||
mpeg4_url=tweet_media.url,
|
||||
thumbnail_url=tweet_media.thumb,
|
||||
caption=self.message_text
|
||||
|
||||
Reference in New Issue
Block a user