mirror of
https://github.com/TheFunny/TelegramTwitterMediaBot.git
synced 2026-09-23 23:32:05 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae1f5a8c8c
|
||
|
|
38adbf0cb8
|
||
|
|
55ae73ee6b
|
||
|
|
d6589fec5b
|
||
|
|
91cad86325
|
||
|
|
cfdb05e476
|
||
|
|
6df6a950c8
|
||
|
|
78d185723b
|
@@ -2,6 +2,13 @@ import logging
|
||||
import os
|
||||
import re
|
||||
|
||||
try:
|
||||
import uvloop, asyncio
|
||||
|
||||
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
|
||||
except ImportError:
|
||||
uvloop = None
|
||||
|
||||
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
||||
ADMIN = [int(i) for i in os.getenv("BOT_ADMIN").split(",")]
|
||||
|
||||
@@ -23,4 +30,7 @@ logging.basicConfig(
|
||||
level=os.getenv("LOG_LEVEL", "WARNING"),
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_logger(name: str) -> logging.Logger:
|
||||
return logging.getLogger(name)
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
from functools import wraps
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from aiohttp import ClientSession
|
||||
from telegram import Chat, InlineKeyboardButton, InlineKeyboardMarkup, Message, Update
|
||||
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from telegram.constants import ChatAction, ChatType, ParseMode
|
||||
from telegram.ext import (Application, ApplicationBuilder, CallbackQueryHandler, CommandHandler, ContextTypes, Defaults,
|
||||
from telegram.ext import (ApplicationBuilder, CallbackQueryHandler, CommandHandler, Defaults,
|
||||
InlineQueryHandler, MessageHandler, PicklePersistence, filters)
|
||||
|
||||
import common
|
||||
from common import logger
|
||||
from tweet import TGTweet
|
||||
from tweet import TelegramTweet
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from telegram import Chat, Message, Update
|
||||
from telegram.ext import Application, ContextTypes
|
||||
|
||||
logger = common.get_logger(__name__)
|
||||
|
||||
|
||||
def send_action(action):
|
||||
@@ -29,7 +36,7 @@ async def inline_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
|
||||
if query == "":
|
||||
return
|
||||
logger.info(f"Query: {query}")
|
||||
async with TGTweet(query) as tweet:
|
||||
async with TelegramTweet(query) as tweet:
|
||||
result = list(tweet.inline_query_generator)
|
||||
await update.inline_query.answer(result)
|
||||
|
||||
@@ -38,8 +45,8 @@ async def inline_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
|
||||
async def url_media(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
url = update.message.text
|
||||
logger.info(f"Receiving url: {url}")
|
||||
async with TGTweet(url) as tweet:
|
||||
media = list(tweet.pm_media_generator)
|
||||
async with TelegramTweet(url) as tweet:
|
||||
media = list(tweet.message_media_generator)
|
||||
message_to_send = await update.effective_message.reply_media_group(
|
||||
media,
|
||||
caption=tweet.message_text,
|
||||
@@ -197,7 +204,7 @@ async def post_init(application: Application) -> None:
|
||||
DESCRIPTION = "A bot to fetch tweets from Twitter."
|
||||
await application.bot.set_my_description(DESCRIPTION)
|
||||
await application.bot.set_my_short_description(DESCRIPTION)
|
||||
TGTweet.set_session(ClientSession())
|
||||
TelegramTweet.init_client()
|
||||
|
||||
|
||||
async def post_stop(application: Application) -> None:
|
||||
@@ -205,7 +212,7 @@ async def post_stop(application: Application) -> None:
|
||||
|
||||
|
||||
async def post_shutdown(application: Application) -> None:
|
||||
await TGTweet.close_session()
|
||||
await TelegramTweet.close_client()
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
+2
-1
@@ -1,2 +1,3 @@
|
||||
python-telegram-bot[webhooks]~=21.3
|
||||
aiohttp[speedups]~=3.9.3
|
||||
httpx[http2]~=0.27.0
|
||||
uvloop~=0.19.0; sys_platform != 'win32'
|
||||
@@ -1,16 +1,30 @@
|
||||
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 aiohttp import ClientSession
|
||||
from telegram import (
|
||||
InlineQueryResultPhoto,
|
||||
InlineQueryResultVideo,
|
||||
InlineQueryResultMpeg4Gif,
|
||||
InputMediaPhoto,
|
||||
InputMediaVideo
|
||||
)
|
||||
from httpx import AsyncClient
|
||||
from telegram import (InlineQueryResultMpeg4Gif, InlineQueryResultPhoto, InlineQueryResultVideo, InputMediaPhoto,
|
||||
InputMediaVideo)
|
||||
|
||||
from common import get_logger, x_media_regex, x_tco_regex, x_url_regex
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import Generator, TypedDict
|
||||
|
||||
|
||||
class TweetInfo(TypedDict):
|
||||
tweetID: str
|
||||
user_name: str
|
||||
user_screen_name: str
|
||||
text: str
|
||||
media_extended: list[dict]
|
||||
possibly_sensitive: bool
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
from common import x_url_regex, x_media_regex, x_tco_regex, logger
|
||||
|
||||
twimg_url = 'https://pbs.twimg.com/'
|
||||
vx_api_url = 'https://api.vxtwitter.com/{0}/status/{1}'
|
||||
@@ -20,14 +34,24 @@ message_raw_text = """{url}
|
||||
"""
|
||||
|
||||
|
||||
async def fetch_json(session: ClientSession, url: str) -> dict:
|
||||
def create_client() -> AsyncClient:
|
||||
return AsyncClient(http2=True)
|
||||
|
||||
|
||||
async def close_client(_client: AsyncClient) -> None:
|
||||
await _client.aclose()
|
||||
|
||||
|
||||
async def fetch_json(_client: AsyncClient, url: str) -> dict:
|
||||
logger.info(f"Fetching {url}")
|
||||
async with session.get(url) as response:
|
||||
assert response.status == 200, f"Failed to fetch {url}, status code {response.status}"
|
||||
return await response.json()
|
||||
response = await _client.get(url)
|
||||
assert response.status_code == response.is_success, f"Failed to fetch {url}, status code {response.status_code}"
|
||||
return response.json()
|
||||
|
||||
|
||||
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
|
||||
@@ -36,14 +60,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":
|
||||
@@ -55,7 +79,7 @@ class TweetMedia:
|
||||
case _:
|
||||
return self._url
|
||||
|
||||
@property
|
||||
@cached_property
|
||||
def thumb(self) -> str:
|
||||
match self._type:
|
||||
case "image":
|
||||
@@ -73,6 +97,8 @@ class TweetMedia:
|
||||
|
||||
|
||||
class Tweet:
|
||||
__slots__ = ('_id', '_author', '_author_id', '_text', '_media', '_sensitive', '__dict__')
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tweet_id: str,
|
||||
@@ -93,7 +119,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}"
|
||||
|
||||
@@ -101,7 +127,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}"
|
||||
|
||||
@@ -118,8 +144,52 @@ class Tweet:
|
||||
return self._sensitive
|
||||
|
||||
|
||||
class TGTweet(Tweet):
|
||||
_session: ClientSession
|
||||
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(Tweet):
|
||||
_httpx_client: AsyncClient
|
||||
|
||||
def __init__(self, url: str):
|
||||
self._url: str = url
|
||||
@@ -136,15 +206,15 @@ class TGTweet(Tweet):
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def set_session(cls, session: ClientSession) -> None:
|
||||
cls._session = session
|
||||
def init_client(cls) -> None:
|
||||
cls._httpx_client = create_client()
|
||||
|
||||
@classmethod
|
||||
async def close_session(cls) -> None:
|
||||
await cls._session.close()
|
||||
async def close_client(cls) -> None:
|
||||
await close_client(cls._httpx_client)
|
||||
|
||||
async def _fetch_tweet(self, api_param: tuple[str]) -> dict:
|
||||
return await fetch_json(self._session, vx_api_url.format(*api_param))
|
||||
return await fetch_json(self._httpx_client, vx_api_url.format(*api_param))
|
||||
|
||||
@property
|
||||
def _tweet_id(self) -> tuple[str] | None:
|
||||
@@ -196,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,
|
||||
@@ -216,14 +286,14 @@ 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
|
||||
)
|
||||
|
||||
@property
|
||||
def pm_media_generator(self) -> Generator[InputMediaPhoto | InputMediaVideo | tuple[str, bool], None, None]:
|
||||
def message_media_generator(self) -> Generator[InputMediaPhoto | InputMediaVideo | tuple[str, bool], None, None]:
|
||||
for tweet_media in self.media:
|
||||
logger.info(str(tweet_media))
|
||||
if tweet_media.type == "image":
|
||||
|
||||
Reference in New Issue
Block a user