mirror of
https://github.com/TheFunny/TelegramTwitterMediaBot.git
synced 2026-09-23 23:32:05 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02abcd899e
|
||
|
|
ebb48d2bb5
|
||
|
|
be77a33e9d
|
||
|
|
0439adefa0
|
||
|
|
81e5d2dbd1
|
||
|
|
e7ccd70e56
|
||
|
|
23128af96a
|
||
|
|
fe1724aca4
|
||
|
|
0433650563
|
||
|
|
a617a7e1a0
|
||
|
|
e35e3895ba
|
||
|
|
a4a9f2eaa0
|
||
|
|
1c779e98a8
|
||
|
|
4a5aa296ce
|
||
|
|
c1c1d42892
|
||
|
|
cade370538
|
||
|
|
a6325d5bc8
|
||
|
|
6c0e581135
|
||
|
|
494fc50446
|
||
|
|
a4e568667c
|
||
|
|
8231eeb20e
|
||
|
|
74f42a2df3
|
||
|
|
ae1f5a8c8c
|
||
|
|
38adbf0cb8
|
||
|
|
55ae73ee6b
|
||
|
|
d6589fec5b
|
||
|
|
91cad86325
|
||
|
|
cfdb05e476
|
||
|
|
6df6a950c8
|
||
|
|
78d185723b
|
||
|
|
1252ec8804
|
||
|
|
cde1091c85
|
||
|
|
8b2b6b49ab
|
||
|
|
86b4a972c9
|
||
|
|
483a3de649
|
||
|
|
48bc81898d
|
||
|
|
f660bc2c5e
|
||
|
|
7747dab4a3
|
||
|
|
f2fac6a9e0
|
||
|
|
e3dcb6e59b
|
||
|
|
a1d1dc5ea3
|
||
|
|
e629899a72
|
||
|
|
d079271ef9
|
||
|
|
1526c7900c
|
||
|
|
79d68b2e82
|
||
|
|
e700ae65ae
|
||
|
|
9ac6065366
|
||
|
|
40877b52eb
|
||
|
|
0ca9b55ea8
|
||
|
|
ef17b05c14
|
||
|
|
85d0257c51
|
||
|
|
7f90670f1c
|
||
|
|
755c405196
|
||
|
|
0ffa9903c4
|
||
|
|
248e7d48e0
|
||
|
|
e915cd13de
|
||
|
|
a7d144f2ee
|
||
|
|
081ee595b1
|
||
|
|
4272454f9a
|
||
|
|
7d289c9db7
|
||
|
|
500ba14565
|
||
|
|
1cb64b64e2
|
||
|
|
8ad9078c5e
|
||
|
|
ebfaaad75a
|
||
|
|
fdd21e22ed
|
||
|
|
ee92b8d8aa
|
||
|
|
50161243ea
|
||
|
|
7846873b9c
|
||
|
|
6d06e28598
|
||
|
|
4083b09093
|
||
|
|
8fb53e8412
|
||
|
|
5c0ee8b491
|
||
|
|
af561ed0a0
|
||
|
|
985fe3fbfe
|
||
|
|
19fb5b9822
|
||
|
|
1185d4bc5f
|
||
|
|
c3faecf640
|
||
|
|
76e0ffe58c
|
||
|
|
a38c1b05b4
|
||
|
|
b3c9b1ace7
|
||
|
|
6a7ab11148
|
||
|
|
18f1f00259
|
||
|
|
04da6eb3d9
|
||
|
|
7a35b06d4e
|
||
|
|
a5ae2321c5
|
||
|
|
d263071946
|
||
|
|
0491d8c3fc
|
||
|
|
3afea136a4
|
||
|
|
87108b2ac8
|
||
|
|
4613e4c825
|
||
|
|
eb1016f137
|
||
|
|
5059a4d04a
|
||
|
|
c85c6191ad
|
+1
-1
@@ -27,5 +27,5 @@
|
|||||||
.python-version
|
.python-version
|
||||||
LICENSE
|
LICENSE
|
||||||
README.md
|
README.md
|
||||||
pers_data
|
data/
|
||||||
cert/
|
cert/
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ on:
|
|||||||
push:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- v*
|
- v*
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
|
||||||
env:
|
env:
|
||||||
APP_NAME: telegram-twitter-media-bot
|
APP_NAME: telegram-twitter-media-bot
|
||||||
@@ -13,6 +15,17 @@ jobs:
|
|||||||
docker:
|
docker:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
- name: Docker meta
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: ${{ env.DOCKERHUB_REPO }}
|
||||||
|
tags: |
|
||||||
|
type=semver,pattern={{version}}
|
||||||
|
type=semver,pattern={{major}}.{{minor}}.{{patch}}
|
||||||
|
type=semver,pattern={{major}}.{{minor}}
|
||||||
|
type=semver,pattern={{major}}
|
||||||
|
type=sha
|
||||||
-
|
-
|
||||||
name: Set up QEMU
|
name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v3
|
uses: docker/setup-qemu-action@v3
|
||||||
@@ -25,18 +38,12 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
- name: Generate APP Version
|
|
||||||
run: echo APP_VERSION=`git describe --tags --always` >> $GITHUB_ENV
|
|
||||||
-
|
-
|
||||||
name: Build and push
|
name: Build and push
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v5
|
||||||
with:
|
with:
|
||||||
push: true
|
push: true
|
||||||
platforms: |
|
|
||||||
linux/amd64
|
|
||||||
build-args: |
|
build-args: |
|
||||||
APP_NAME=${{ env.APP_NAME }}
|
APP_NAME=${{ env.APP_NAME }}
|
||||||
APP_VERSION=${{ env.APP_VERSION }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
tags: |
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
${{ env.DOCKERHUB_REPO }}:latest
|
|
||||||
${{ env.DOCKERHUB_REPO }}:${{ env.APP_VERSION }}
|
|
||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
**/.idea
|
**/.idea
|
||||||
__pycache__/
|
__pycache__/
|
||||||
cert/
|
cert/
|
||||||
pers_data
|
data/
|
||||||
docker-compose.yml
|
docker-compose.yml
|
||||||
x.py
|
utils/x.py
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@ ENV PYTHONUNBUFFERED=1
|
|||||||
|
|
||||||
RUN set -eux; \
|
RUN set -eux; \
|
||||||
apt-get update; \
|
apt-get update; \
|
||||||
apt-get install -y gosu; \
|
apt-get install -y git gosu; \
|
||||||
rm -rf /var/lib/apt/lists/*; \
|
rm -rf /var/lib/apt/lists/*; \
|
||||||
# verify that the binary works
|
# verify that the binary works
|
||||||
gosu nobody true
|
gosu nobody true
|
||||||
|
|||||||
@@ -1,9 +1,17 @@
|
|||||||
import logging
|
|
||||||
import re
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
try:
|
||||||
|
import uvloop
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
|
||||||
|
except ImportError:
|
||||||
|
uvloop = None
|
||||||
|
|
||||||
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
||||||
ADMIN = os.getenv("ADMIN").split(",")
|
ADMIN = [int(i) for i in os.getenv("BOT_ADMIN").split(",")]
|
||||||
|
|
||||||
|
PIXIV_REFRESH_TOKEN = os.getenv("PIXIV_REFRESH_TOKEN")
|
||||||
|
|
||||||
WEBHOOK = os.getenv("WEBHOOK", False)
|
WEBHOOK = os.getenv("WEBHOOK", False)
|
||||||
if WEBHOOK:
|
if WEBHOOK:
|
||||||
@@ -13,13 +21,3 @@ if WEBHOOK:
|
|||||||
WEBHOOK_KEY = os.getenv("WEBHOOK_KEY", "cert/private.key")
|
WEBHOOK_KEY = os.getenv("WEBHOOK_KEY", "cert/private.key")
|
||||||
WEBHOOK_CERT = os.getenv("WEBHOOK_CERT", "cert/cert.pem")
|
WEBHOOK_CERT = os.getenv("WEBHOOK_CERT", "cert/cert.pem")
|
||||||
WEBHOOK_SECRET_TOKEN = os.getenv("WEBHOOK_SECRET_TOKEN")
|
WEBHOOK_SECRET_TOKEN = os.getenv("WEBHOOK_SECRET_TOKEN")
|
||||||
|
|
||||||
x_url_regex = re.compile(r"^(?:https?://)(?:www\.|mobile\.|)(x|twitter)\.com/.+/status/(\d+)")
|
|
||||||
x_media_regex = re.compile(r"^(?:https?://)(pbs|video)\.twimg\.com/(.*)")
|
|
||||||
x_tco_regex = re.compile(r"(?:https?://)t\.co/.+$", re.M)
|
|
||||||
|
|
||||||
logging.basicConfig(
|
|
||||||
level=os.getenv("LOG_LEVEL", "WARNING"),
|
|
||||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
||||||
)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
version: '3.7'
|
|
||||||
services:
|
services:
|
||||||
tgxmb: image: yoursfunny/telegram-twitter-media-bot: latest
|
tgxmb: image: yoursfunny/telegram-twitter-media-bot: latest
|
||||||
restart: always
|
restart: always
|
||||||
ports:
|
# ports:
|
||||||
- "8443:8443"
|
# - "8443:8443"
|
||||||
environment:
|
environment:
|
||||||
LOCAL_USER_ID: '1000'
|
LOCAL_USER_ID: '1000'
|
||||||
BOT_TOKEN: ''
|
BOT_TOKEN: ''
|
||||||
BOT_ADMIN: ''
|
BOT_ADMIN: ''
|
||||||
|
PIXIV_REFRESH_TOKEN: ''
|
||||||
WEBHOOK: false
|
WEBHOOK: false
|
||||||
WEBHOOK_LISTEN: '127.0.0.1'
|
WEBHOOK_LISTEN: '127.0.0.1'
|
||||||
WEBHOOK_PORT: 8443
|
WEBHOOK_PORT: 8443
|
||||||
@@ -16,6 +16,7 @@ services:
|
|||||||
WEBHOOK_CERT: './cert/cert.pem'
|
WEBHOOK_CERT: './cert/cert.pem'
|
||||||
WEBHOOK_SECRET_TOKEN: 'secret-token'
|
WEBHOOK_SECRET_TOKEN: 'secret-token'
|
||||||
# LOG_LEVEL: 'WARNING'
|
# LOG_LEVEL: 'WARNING'
|
||||||
# volumes:
|
volumes:
|
||||||
|
- ./data: /app/data
|
||||||
# - ./cert:/app/cert
|
# - ./cert:/app/cert
|
||||||
container_name: tgxmb
|
container_name: tgxmb
|
||||||
|
|||||||
@@ -1,77 +1,172 @@
|
|||||||
from aiohttp import ClientSession
|
from __future__ import annotations
|
||||||
from telegram import Update, Chat
|
|
||||||
from telegram.constants import ParseMode, ChatAction
|
import html
|
||||||
from telegram.ext import (
|
from functools import wraps
|
||||||
Application,
|
from typing import TYPE_CHECKING
|
||||||
ApplicationBuilder,
|
|
||||||
ContextTypes,
|
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
|
||||||
Defaults,
|
from telegram.constants import ChatAction, ChatType, ParseMode
|
||||||
filters,
|
from telegram.ext import (ApplicationBuilder, CallbackQueryHandler, CommandHandler, Defaults,
|
||||||
InlineQueryHandler,
|
InlineQueryHandler, MessageHandler, PicklePersistence, filters)
|
||||||
PicklePersistence,
|
|
||||||
MessageHandler, CommandHandler
|
|
||||||
)
|
|
||||||
|
|
||||||
import common
|
import common
|
||||||
from tweet import TGTweet
|
import utils.regex as regex
|
||||||
|
from utils.logger import get_logger
|
||||||
|
from utils.net import NetClient
|
||||||
|
from utils.pixiv import ProcessPixiv
|
||||||
|
from utils.telegram import Telegram
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from telegram import Message, Update
|
||||||
|
from telegram.ext import Application, ContextTypes
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def send_action(action):
|
||||||
|
def decorator(func):
|
||||||
|
@wraps(func)
|
||||||
|
async def command_func(update: Update, context: ContextTypes.DEFAULT_TYPE, *args, **kwargs):
|
||||||
|
await update.effective_chat.send_action(action)
|
||||||
|
return await func(update, context, *args, **kwargs)
|
||||||
|
|
||||||
|
return command_func
|
||||||
|
|
||||||
|
return decorator
|
||||||
|
|
||||||
|
|
||||||
async def inline_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def inline_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
query = update.inline_query.query
|
query = update.inline_query.query
|
||||||
if query == "":
|
if query == "":
|
||||||
return
|
return
|
||||||
async with TGTweet(context.bot_data['client'], query) as tweet:
|
logger.info(f"Query: {query}")
|
||||||
result = list(tweet.inline_query_generator)
|
async with Telegram(query) as tweet:
|
||||||
await update.inline_query.answer(result)
|
if not tweet:
|
||||||
|
return
|
||||||
|
await update.inline_query.answer(tweet.inline_query_result())
|
||||||
|
|
||||||
|
|
||||||
async def reply_media(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
@send_action(ChatAction.UPLOAD_PHOTO)
|
||||||
await update.effective_chat.send_action(ChatAction.UPLOAD_PHOTO)
|
async def url_media(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
# url = update.message.text.split(" ")[0]
|
|
||||||
url = update.message.text
|
url = update.message.text
|
||||||
async with TGTweet(context.bot_data['client'], url) as tweet:
|
logger.info(f"Receiving url: {url}")
|
||||||
media = list(tweet.pm_media_generator)
|
async with Telegram(url) as tweet:
|
||||||
message_sent = await update.effective_message.reply_media_group(
|
media = tweet.message_media_result()
|
||||||
media, caption=tweet.message_text,
|
if not media:
|
||||||
# reply_to_message_id=update.message.message_id
|
await update.effective_message.reply_text("No media found or media type is not supported.")
|
||||||
|
return
|
||||||
|
message_to_send = await update.effective_message.reply_media_group(
|
||||||
|
media,
|
||||||
|
caption=tweet.message_text,
|
||||||
|
reply_to_message_id=update.message.message_id,
|
||||||
|
) if not isinstance(media[0], tuple) else await update.effective_message.reply_animation(
|
||||||
|
media[0][0],
|
||||||
|
caption=tweet.message_text,
|
||||||
|
reply_to_message_id=update.message.message_id,
|
||||||
|
has_spoiler=media[0][1]
|
||||||
)
|
)
|
||||||
|
if not isinstance(message_to_send, tuple):
|
||||||
|
message_to_send = (message_to_send,)
|
||||||
|
url = tweet.url
|
||||||
|
if context.user_data.get('edit_before_forward', False):
|
||||||
|
message_reply = await update.effective_message.reply_text(
|
||||||
|
"Reply to edit message. [URL]",
|
||||||
|
reply_markup=InlineKeyboardMarkup.from_button(
|
||||||
|
InlineKeyboardButton("↩️ Confirm", callback_data="forward")
|
||||||
|
),
|
||||||
|
reply_to_message_id=update.message.message_id,
|
||||||
|
)
|
||||||
|
context.user_data['message_reply'] = message_reply
|
||||||
|
context.user_data['message_to_send'] = message_to_send
|
||||||
|
context.user_data['message_url'] = url
|
||||||
|
return
|
||||||
if 'forward_channel_id' in context.user_data:
|
if 'forward_channel_id' in context.user_data:
|
||||||
try:
|
await forward_message(update, context, message_to_send)
|
||||||
await update.effective_chat.copy_messages(
|
|
||||||
chat_id=context.user_data['forward_channel_id'],
|
|
||||||
message_ids=[m.id for m in message_sent],
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
await update.effective_message.reply_text(str(e))
|
|
||||||
|
|
||||||
|
|
||||||
|
async def forward_message(
|
||||||
|
update: Update,
|
||||||
|
context: ContextTypes.DEFAULT_TYPE,
|
||||||
|
message_to_send: tuple[Message, ...],
|
||||||
|
) -> None:
|
||||||
|
try:
|
||||||
|
await update.effective_chat.copy_messages(
|
||||||
|
context.user_data['forward_channel_id'],
|
||||||
|
[m.id for m in message_to_send]
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
await update.effective_message.reply_text(str(e))
|
||||||
|
|
||||||
|
|
||||||
|
async def edit_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
|
if 'message_reply' not in context.user_data:
|
||||||
|
return
|
||||||
|
if update.message.reply_to_message != context.user_data['message_reply']:
|
||||||
|
return
|
||||||
|
template = context.user_data.get('template', None)
|
||||||
|
message_url = '<a href="{0}">{1}</a>'
|
||||||
|
url = context.user_data['message_url']
|
||||||
|
if template:
|
||||||
|
update_text = template.replace("[]", message_url.format(
|
||||||
|
url,
|
||||||
|
html.escape(update.message.text)
|
||||||
|
))
|
||||||
|
else:
|
||||||
|
update_text = html.escape(update.message.text)
|
||||||
|
match = regex.message_url.search(update_text)
|
||||||
|
if match:
|
||||||
|
match = match.span()
|
||||||
|
update_text = update_text[:match[0]] + message_url.format(
|
||||||
|
url,
|
||||||
|
update_text[match[0] + 1:match[1] - 1]
|
||||||
|
) + update_text[match[1]:]
|
||||||
|
message_to_send = context.user_data['message_to_send']
|
||||||
|
await message_to_send[0].edit_caption(update_text)
|
||||||
|
|
||||||
|
|
||||||
|
async def query_forward_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
|
message_to_send = context.user_data['message_to_send']
|
||||||
|
await forward_message(update, context, message_to_send)
|
||||||
|
await update.callback_query.answer('✅ Forwarded')
|
||||||
|
await update.callback_query.delete_message()
|
||||||
|
del context.user_data['message_reply']
|
||||||
|
del context.user_data['message_to_send']
|
||||||
|
del context.user_data['message_url']
|
||||||
|
|
||||||
|
|
||||||
|
@send_action(ChatAction.TYPING)
|
||||||
async def cmd_set_forward_channel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def cmd_set_forward_channel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
await update.effective_chat.send_action(ChatAction.TYPING)
|
|
||||||
if not context.args:
|
if not context.args:
|
||||||
await update.effective_message.reply_text("Please provide a channel username or id.")
|
await update.effective_message.reply_text("Please provide a channel username or id.")
|
||||||
return
|
return
|
||||||
channel = context.args[0]
|
channel = context.args[0]
|
||||||
try:
|
try:
|
||||||
channel: Chat = context.bot.get_chat(channel)
|
channel = await context.bot.get_chat(channel)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await update.effective_message.reply_text(str(e))
|
await update.effective_message.reply_text(str(e))
|
||||||
return
|
return
|
||||||
if channel.type != "CHANNEL":
|
if channel.type != ChatType.CHANNEL:
|
||||||
await update.effective_message.reply_text("That is not a channel.")
|
await update.effective_message.reply_text("That is not a channel.")
|
||||||
return
|
return
|
||||||
channel_admin = await channel.get_administrators()
|
try:
|
||||||
|
channel_admin = await channel.get_administrators()
|
||||||
|
except Exception as e:
|
||||||
|
await update.effective_message.reply_text(str(e) + "\nPlease add the bot to the channel and set as admin")
|
||||||
|
return
|
||||||
|
user = filter(lambda x: x.user.id == update.effective_user.id, channel_admin)
|
||||||
|
user = next(user, None)
|
||||||
|
if not user:
|
||||||
|
await update.effective_message.reply_text("You are not an admin of the channel.")
|
||||||
|
return
|
||||||
user_bot = filter(lambda x: x.user.id == context.bot.id, channel_admin)
|
user_bot = filter(lambda x: x.user.id == context.bot.id, channel_admin)
|
||||||
user_bot = next(user_bot, None)
|
user_bot = next(user_bot, None)
|
||||||
if not user_bot:
|
|
||||||
await update.effective_message.reply_text("I am not an admin in that channel.")
|
|
||||||
return
|
|
||||||
if user_bot.can_post_messages:
|
if user_bot.can_post_messages:
|
||||||
context.user_data['forward_channel_id'] = channel.id
|
context.user_data['forward_channel_id'] = channel.id
|
||||||
await update.effective_message.reply_text("Add successfully.")
|
await update.effective_message.reply_text("Add successfully.")
|
||||||
|
|
||||||
|
|
||||||
|
@send_action(ChatAction.TYPING)
|
||||||
async def cmd_remove_forward_channel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def cmd_remove_forward_channel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
await update.effective_chat.send_action(ChatAction.TYPING)
|
|
||||||
if 'forward_channel_id' in context.user_data:
|
if 'forward_channel_id' in context.user_data:
|
||||||
del context.user_data['forward_channel_id']
|
del context.user_data['forward_channel_id']
|
||||||
await update.effective_message.reply_text("Remove successfully.")
|
await update.effective_message.reply_text("Remove successfully.")
|
||||||
@@ -79,6 +174,41 @@ async def cmd_remove_forward_channel(update: Update, context: ContextTypes.DEFAU
|
|||||||
await update.effective_message.reply_text("No channel to remove.")
|
await update.effective_message.reply_text("No channel to remove.")
|
||||||
|
|
||||||
|
|
||||||
|
@send_action(ChatAction.TYPING)
|
||||||
|
async def cmd_edit_before_forward(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
|
if context.user_data.get('forward_channel_id', None) is None:
|
||||||
|
await update.effective_message.reply_text("Please enable forward channel first.")
|
||||||
|
return
|
||||||
|
ebf_status = context.user_data.get('edit_before_forward', False)
|
||||||
|
if ebf_status:
|
||||||
|
context.user_data['edit_before_forward'] = False
|
||||||
|
context.user_data.pop('message_reply', None)
|
||||||
|
context.user_data.pop('message_to_send', None)
|
||||||
|
context.user_data.pop('message_url', None)
|
||||||
|
await update.effective_message.reply_text("Disable edit before forward.")
|
||||||
|
return
|
||||||
|
context.user_data['edit_before_forward'] = True
|
||||||
|
await update.effective_message.reply_text("Enable edit before forward.")
|
||||||
|
|
||||||
|
|
||||||
|
@send_action(ChatAction.TYPING)
|
||||||
|
async def cmd_set_template(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
|
reply = update.effective_message.reply_to_message
|
||||||
|
if not reply:
|
||||||
|
await update.effective_message.reply_text("Please reply to a message to set as template.")
|
||||||
|
return
|
||||||
|
if '[]' not in reply.text_html:
|
||||||
|
await update.effective_message.reply_text("Please reply to a message with [] to set as template.")
|
||||||
|
return
|
||||||
|
context.user_data['template'] = reply.text_html
|
||||||
|
await update.effective_message.reply_text("Template set.")
|
||||||
|
|
||||||
|
|
||||||
|
@send_action(ChatAction.TYPING)
|
||||||
|
async def cmd_user_dict(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
|
await update.effective_message.reply_text(str(context.user_data))
|
||||||
|
|
||||||
|
|
||||||
async def post_init(application: Application) -> None:
|
async def post_init(application: Application) -> None:
|
||||||
# commands = [
|
# commands = [
|
||||||
# BotCommand('start', CMD_START),
|
# BotCommand('start', CMD_START),
|
||||||
@@ -87,7 +217,9 @@ async def post_init(application: Application) -> None:
|
|||||||
DESCRIPTION = "A bot to fetch tweets from Twitter."
|
DESCRIPTION = "A bot to fetch tweets from Twitter."
|
||||||
await application.bot.set_my_description(DESCRIPTION)
|
await application.bot.set_my_description(DESCRIPTION)
|
||||||
await application.bot.set_my_short_description(DESCRIPTION)
|
await application.bot.set_my_short_description(DESCRIPTION)
|
||||||
application.bot_data['client'] = ClientSession()
|
NetClient.init_client()
|
||||||
|
if common.PIXIV_REFRESH_TOKEN:
|
||||||
|
await ProcessPixiv.init_client(common.PIXIV_REFRESH_TOKEN)
|
||||||
|
|
||||||
|
|
||||||
async def post_stop(application: Application) -> None:
|
async def post_stop(application: Application) -> None:
|
||||||
@@ -95,13 +227,12 @@ async def post_stop(application: Application) -> None:
|
|||||||
|
|
||||||
|
|
||||||
async def post_shutdown(application: Application) -> None:
|
async def post_shutdown(application: Application) -> None:
|
||||||
await application.bot_data['client'].close()
|
await NetClient.close_client()
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
defaults = Defaults(parse_mode=ParseMode.HTML, allow_sending_without_reply=True)
|
defaults = Defaults(parse_mode=ParseMode.HTML, allow_sending_without_reply=True)
|
||||||
persistence = PicklePersistence(filepath='pers_data')
|
persistence = PicklePersistence(filepath='data/pers.pkl')
|
||||||
# proxy_url = 'http://127.0.0.1:10809'
|
|
||||||
application = (ApplicationBuilder()
|
application = (ApplicationBuilder()
|
||||||
.token(common.BOT_TOKEN)
|
.token(common.BOT_TOKEN)
|
||||||
.defaults(defaults)
|
.defaults(defaults)
|
||||||
@@ -109,20 +240,25 @@ def main():
|
|||||||
.post_init(post_init)
|
.post_init(post_init)
|
||||||
.post_stop(post_stop)
|
.post_stop(post_stop)
|
||||||
.post_shutdown(post_shutdown)
|
.post_shutdown(post_shutdown)
|
||||||
# .proxy(proxy_url)
|
.concurrent_updates(True)
|
||||||
# .get_updates_proxy(proxy_url)
|
.http_version('2')
|
||||||
.build()
|
.build()
|
||||||
)
|
)
|
||||||
|
|
||||||
# user_filter = filters.User()
|
user_filter = filters.User()
|
||||||
# user_filter.add_user_ids(common.admin)
|
user_filter.add_user_ids(common.ADMIN)
|
||||||
|
|
||||||
handlers = [
|
handlers = [
|
||||||
MessageHandler(filters.Regex(common.x_url_regex) & filters.ChatType.PRIVATE, reply_media),
|
InlineQueryHandler(inline_query),
|
||||||
# MessageHandler(None, reply_media),
|
MessageHandler((filters.Regex(regex.x_url) | filters.Regex(regex.pixiv_url)) & filters.ChatType.PRIVATE,
|
||||||
InlineQueryHandler(inline_query, common.x_url_regex),
|
url_media),
|
||||||
CommandHandler("set_forward_channel", cmd_set_forward_channel),
|
CommandHandler("set_forward_channel", cmd_set_forward_channel),
|
||||||
CommandHandler("remove_forward_channel", cmd_remove_forward_channel),
|
CommandHandler("remove_forward_channel", cmd_remove_forward_channel),
|
||||||
|
CommandHandler("edit_before_forward", cmd_edit_before_forward),
|
||||||
|
CommandHandler("set_template", cmd_set_template),
|
||||||
|
MessageHandler(~filters.COMMAND & filters.ChatType.PRIVATE, edit_message),
|
||||||
|
CallbackQueryHandler(query_forward_message, pattern="forward"),
|
||||||
|
CommandHandler("bot_dict", cmd_user_dict, filters=user_filter),
|
||||||
]
|
]
|
||||||
|
|
||||||
application.add_handlers(handlers)
|
application.add_handlers(handlers)
|
||||||
|
|||||||
+4
-2
@@ -1,2 +1,4 @@
|
|||||||
python-telegram-bot[webhooks]~=21.0.1
|
python-telegram-bot[webhooks]~=21.3
|
||||||
aiohttp[speedups]~=3.9.3
|
httpx[http2]~=0.27
|
||||||
|
uvloop~=0.19.0; sys_platform != 'win32'
|
||||||
|
async-pixiv @ git+https://github.com/TheFunny/async-pixiv@main
|
||||||
@@ -1,201 +0,0 @@
|
|||||||
from typing import Generator
|
|
||||||
|
|
||||||
from aiohttp import ClientSession
|
|
||||||
from telegram import (
|
|
||||||
InlineQueryResultPhoto,
|
|
||||||
InlineQueryResultVideo,
|
|
||||||
InputMediaPhoto,
|
|
||||||
InputMediaVideo
|
|
||||||
)
|
|
||||||
from common import x_url_regex, x_media_regex, x_tco_regex
|
|
||||||
|
|
||||||
twimg_url = 'https://pbs.twimg.com/'
|
|
||||||
vx_api_url = 'https://api.vxtwitter.com/status/'
|
|
||||||
|
|
||||||
message_raw_text = """{url}
|
|
||||||
<a href="{author_url}">{author}</a>: {text}
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
async def fetch_json(session: ClientSession, url: str) -> dict:
|
|
||||||
async with session.get(url) as response:
|
|
||||||
assert response.status == 200
|
|
||||||
return await response.json()
|
|
||||||
|
|
||||||
|
|
||||||
class TweetMedia:
|
|
||||||
def __init__(self, url: str, thumb: str, media_type: str):
|
|
||||||
self._url: str = url
|
|
||||||
self._thumb: str = thumb
|
|
||||||
self._type: str = media_type
|
|
||||||
|
|
||||||
@property
|
|
||||||
def _uri(self) -> str | None:
|
|
||||||
match = x_media_regex.match(self._url)
|
|
||||||
if match:
|
|
||||||
return match.group(2).removesuffix('.jpg')
|
|
||||||
return None
|
|
||||||
|
|
||||||
@property
|
|
||||||
def url(self) -> str:
|
|
||||||
match self._type:
|
|
||||||
case "image":
|
|
||||||
return f"{twimg_url}{self._uri}?format=jpg&name=orig"
|
|
||||||
case "video":
|
|
||||||
return self._url
|
|
||||||
|
|
||||||
@property
|
|
||||||
def thumb(self) -> str:
|
|
||||||
match self._type:
|
|
||||||
case "image":
|
|
||||||
return f"{twimg_url}{self._uri}?format=jpg&name=thumb"
|
|
||||||
case "video":
|
|
||||||
return self._thumb
|
|
||||||
|
|
||||||
@property
|
|
||||||
def type(self) -> str:
|
|
||||||
return self._type
|
|
||||||
|
|
||||||
|
|
||||||
class Tweet:
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
tweet_id: str,
|
|
||||||
author: str,
|
|
||||||
author_id: str,
|
|
||||||
text: str,
|
|
||||||
media: list[TweetMedia],
|
|
||||||
sensitive: bool = False
|
|
||||||
):
|
|
||||||
self._id: str = tweet_id
|
|
||||||
self._author: str = author
|
|
||||||
self._author_id: str = author_id
|
|
||||||
self._text: str = text
|
|
||||||
self._media: list[TweetMedia] = media
|
|
||||||
self._sensitive: bool = sensitive
|
|
||||||
|
|
||||||
@property
|
|
||||||
def id(self) -> str:
|
|
||||||
return self._id
|
|
||||||
|
|
||||||
@property
|
|
||||||
def url(self) -> str:
|
|
||||||
return f"https://twitter.com/{self._author_id}/status/{self._id}"
|
|
||||||
|
|
||||||
@property
|
|
||||||
def author(self) -> str:
|
|
||||||
return self._author
|
|
||||||
|
|
||||||
@property
|
|
||||||
def author_url(self) -> str:
|
|
||||||
return f"https://twitter.com/{self._author_id}"
|
|
||||||
|
|
||||||
@property
|
|
||||||
def text(self) -> str:
|
|
||||||
return self._text
|
|
||||||
|
|
||||||
@property
|
|
||||||
def media(self) -> list[TweetMedia]:
|
|
||||||
return self._media
|
|
||||||
|
|
||||||
@property
|
|
||||||
def sensitive(self) -> bool:
|
|
||||||
return self._sensitive
|
|
||||||
|
|
||||||
|
|
||||||
class TGTweet(Tweet):
|
|
||||||
def __init__(self, session: ClientSession, url: str):
|
|
||||||
self._session: ClientSession = session
|
|
||||||
self._url: str = url
|
|
||||||
self._id: str = self._tweet_id
|
|
||||||
assert self._id
|
|
||||||
|
|
||||||
async def __aenter__(self):
|
|
||||||
self._tweet: dict = await self._fetch_tweet(self._id)
|
|
||||||
super().__init__(*self._init_properties)
|
|
||||||
return self
|
|
||||||
|
|
||||||
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
||||||
pass
|
|
||||||
|
|
||||||
async def _fetch_tweet(self, tweet_id: str) -> dict:
|
|
||||||
return await fetch_json(self._session, vx_api_url + tweet_id)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def _tweet_id(self) -> str | None:
|
|
||||||
match = x_url_regex.match(self._url)
|
|
||||||
if match:
|
|
||||||
return match.group(1).strip('/')
|
|
||||||
return None
|
|
||||||
|
|
||||||
@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=x['url'],
|
|
||||||
thumb=x['thumbnail_url'],
|
|
||||||
media_type=x['type']
|
|
||||||
)
|
|
||||||
for x in self._tweet['media_extended']
|
|
||||||
]
|
|
||||||
|
|
||||||
@property
|
|
||||||
def _init_properties(self) -> tuple:
|
|
||||||
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']
|
|
||||||
return self._id, author, author_id, text, media, sensitive
|
|
||||||
|
|
||||||
@property
|
|
||||||
def message_text(self) -> str:
|
|
||||||
return message_raw_text.format(
|
|
||||||
url=self.url,
|
|
||||||
author_url=self.author_url,
|
|
||||||
author=self.author,
|
|
||||||
text=self.text
|
|
||||||
)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def inline_query_generator(self) -> Generator[InlineQueryResultPhoto | InlineQueryResultVideo, None, None]:
|
|
||||||
for i, tweet_media in enumerate(self.media):
|
|
||||||
if tweet_media.type == "image":
|
|
||||||
yield InlineQueryResultPhoto(
|
|
||||||
id=self.id,
|
|
||||||
photo_url=tweet_media.url,
|
|
||||||
thumbnail_url=tweet_media.thumb,
|
|
||||||
title=self.url,
|
|
||||||
description=self.text,
|
|
||||||
caption=self.message_text if not i else None
|
|
||||||
)
|
|
||||||
elif tweet_media.type == "video":
|
|
||||||
yield InlineQueryResultVideo(
|
|
||||||
id=self.id,
|
|
||||||
video_url=tweet_media.url,
|
|
||||||
mime_type="video/mp4",
|
|
||||||
thumbnail_url=tweet_media.thumb,
|
|
||||||
title=self.url,
|
|
||||||
description=self.text,
|
|
||||||
caption=self.message_text if not i else None
|
|
||||||
)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def pm_media_generator(self) -> Generator[InputMediaPhoto | InputMediaVideo, None, None]:
|
|
||||||
for tweet_media in self.media:
|
|
||||||
if tweet_media.type == "image":
|
|
||||||
yield InputMediaPhoto(
|
|
||||||
media=tweet_media.url,
|
|
||||||
has_spoiler=self.sensitive
|
|
||||||
)
|
|
||||||
elif tweet_media.type == "video":
|
|
||||||
yield InputMediaVideo(
|
|
||||||
media=tweet_media.url,
|
|
||||||
has_spoiler=self.sensitive,
|
|
||||||
thumbnail=tweet_media.thumb
|
|
||||||
)
|
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import logging
|
||||||
|
import os
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=os.getenv("LOG_LEVEL", "WARNING"),
|
||||||
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_logger(name: str) -> logging.Logger:
|
||||||
|
return logging.getLogger(name)
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
|
||||||
|
def create_client() -> AsyncClient:
|
||||||
|
return AsyncClient(http2=True)
|
||||||
|
|
||||||
|
|
||||||
|
async def close_client(_client: AsyncClient) -> None:
|
||||||
|
return await _client.aclose()
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch_json(_client: AsyncClient, url: str) -> dict:
|
||||||
|
response = await _client.get(url)
|
||||||
|
assert response.is_success, f"Failed to fetch {url}, status code {response.status_code}"
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
class NetClient:
|
||||||
|
_httpx_client: AsyncClient
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def init_client(cls) -> None:
|
||||||
|
cls._httpx_client = create_client()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def close_client(cls) -> None:
|
||||||
|
await close_client(cls._httpx_client)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_client(cls) -> AsyncClient:
|
||||||
|
return cls._httpx_client
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def fetch_json(cls, url: str) -> dict:
|
||||||
|
return await fetch_json(cls._httpx_client, url)
|
||||||
+212
@@ -0,0 +1,212 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import html
|
||||||
|
from typing import Generator, Literal, TYPE_CHECKING
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from async_pixiv import PixivClient
|
||||||
|
from async_pixiv.error import ApiError
|
||||||
|
from telegram import InlineQueryResultPhoto, InputMediaPhoto
|
||||||
|
|
||||||
|
from utils.logger import get_logger
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from async_pixiv.model.illust import Illust
|
||||||
|
from utils.types import TypeInlineQueryResult, TypeMessageMediaResult
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
message_raw_text = """<a href="{url}">{text}</a> / <a href="{author_url}">{author}</a>
|
||||||
|
{tags}
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class PixivMedia:
|
||||||
|
__slots__ = ('_url', '_thumb')
|
||||||
|
|
||||||
|
def __init__(self, url: str, thumb: str):
|
||||||
|
self._url: str = url
|
||||||
|
self._thumb: str = thumb
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return f"PixivMedia(url={self.url}, thumb={self.thumb}, large={self.large})"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def url(self) -> str:
|
||||||
|
return self._url
|
||||||
|
|
||||||
|
@property
|
||||||
|
def thumb(self) -> str:
|
||||||
|
return self._thumb
|
||||||
|
|
||||||
|
@property
|
||||||
|
def large(self) -> str:
|
||||||
|
url = self._url.replace("img-original", "img-master").removesuffix(".jpg").removesuffix(".png")
|
||||||
|
return url + "_master1200.jpg"
|
||||||
|
|
||||||
|
|
||||||
|
class Pixiv:
|
||||||
|
__slots__ = ('_illust',)
|
||||||
|
|
||||||
|
def __init__(self, illust: Illust):
|
||||||
|
self._illust: Illust = illust
|
||||||
|
|
||||||
|
@property
|
||||||
|
def url(self) -> str:
|
||||||
|
return str(self._illust.link).rstrip('/')
|
||||||
|
|
||||||
|
@property
|
||||||
|
def type(self) -> Literal["illust", "manga", "ugoira"]:
|
||||||
|
return self._illust.type.value
|
||||||
|
|
||||||
|
@property
|
||||||
|
def title(self) -> str:
|
||||||
|
return self._illust.title
|
||||||
|
|
||||||
|
@property
|
||||||
|
def author(self) -> str:
|
||||||
|
return self._illust.user.name
|
||||||
|
|
||||||
|
@property
|
||||||
|
def author_url(self) -> str:
|
||||||
|
return str(self._illust.user.link).rstrip('/')
|
||||||
|
|
||||||
|
@property
|
||||||
|
def description(self) -> str:
|
||||||
|
return self._illust.caption
|
||||||
|
|
||||||
|
@property
|
||||||
|
def tags(self) -> list[str]:
|
||||||
|
return [tag.name for tag in self._illust.tags]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_multiple_pages(self) -> bool:
|
||||||
|
return self._illust.page_count > 1
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_nsfw(self) -> bool:
|
||||||
|
return self._illust.is_nsfw
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_ai(self) -> bool:
|
||||||
|
return self._illust.ai_type.value == 2
|
||||||
|
|
||||||
|
@property
|
||||||
|
def images(self) -> list[PixivMedia]:
|
||||||
|
if self.is_multiple_pages:
|
||||||
|
return [
|
||||||
|
PixivMedia(
|
||||||
|
url=page.image_urls.original,
|
||||||
|
thumb=page.image_urls.medium
|
||||||
|
)
|
||||||
|
for page in self._illust.meta_pages
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
return [
|
||||||
|
PixivMedia( # should observe if image_url.original is always None for single page
|
||||||
|
url=self._illust.image_urls.original or self._illust.meta_single_page.original,
|
||||||
|
thumb=self._illust.image_urls.medium
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class ProcessPixiv:
|
||||||
|
_client: PixivClient
|
||||||
|
|
||||||
|
__slots__ = ('_url', '_illust')
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def init_client(cls, token: str) -> None:
|
||||||
|
cls._client = PixivClient()
|
||||||
|
await cls._client.login_with_token(token)
|
||||||
|
cls._token = token
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def close_client(cls) -> None:
|
||||||
|
await cls._client.close()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def refresh_token(cls):
|
||||||
|
await cls._client.login_with_token(cls._token)
|
||||||
|
|
||||||
|
def __init__(self, url: str):
|
||||||
|
self._url: str = url
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
self._illust = await self._fetch_illust()
|
||||||
|
return Pixiv(self._illust)
|
||||||
|
|
||||||
|
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def _fetch_illust(self) -> Illust:
|
||||||
|
illust_id = self._parse_illust_id()
|
||||||
|
try:
|
||||||
|
return (await self._client.ILLUST.detail(illust_id)).illust
|
||||||
|
except ApiError:
|
||||||
|
await self.refresh_token()
|
||||||
|
return (await self._client.ILLUST.detail(illust_id)).illust # TODO use retry here
|
||||||
|
|
||||||
|
def _parse_illust_id(self) -> int:
|
||||||
|
return int(self._url.split("/")[-1])
|
||||||
|
|
||||||
|
|
||||||
|
class TelegramPixiv:
|
||||||
|
__slots__ = ('_url', '_pixiv')
|
||||||
|
|
||||||
|
def __init__(self, url: str):
|
||||||
|
self._url = url
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
async with ProcessPixiv(self._url) as pixiv:
|
||||||
|
self._pixiv = pixiv
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def url(self) -> str:
|
||||||
|
return self._url
|
||||||
|
|
||||||
|
@property
|
||||||
|
def message_text(self) -> str:
|
||||||
|
pixiv = self._pixiv
|
||||||
|
return message_raw_text.format(
|
||||||
|
url=pixiv.url,
|
||||||
|
author_url=pixiv.author_url,
|
||||||
|
author=html.escape(pixiv.author),
|
||||||
|
text=html.escape(pixiv.title),
|
||||||
|
tags=html.escape(" ".join(f"#{name}" for name in pixiv.tags))
|
||||||
|
)
|
||||||
|
|
||||||
|
def inline_query_result(self) -> tuple[TypeInlineQueryResult, ...]:
|
||||||
|
return tuple(self.inline_query_generator())
|
||||||
|
|
||||||
|
def message_media_result(self) -> tuple[TypeMessageMediaResult, ...]:
|
||||||
|
return tuple(self.message_media_generator())
|
||||||
|
|
||||||
|
def inline_query_generator(self) -> Generator[TypeInlineQueryResult, None, None]:
|
||||||
|
pixiv = self._pixiv
|
||||||
|
for media in pixiv.images:
|
||||||
|
logger.info(str(media))
|
||||||
|
if pixiv.type in ("illust", "manga"):
|
||||||
|
yield InlineQueryResultPhoto(
|
||||||
|
id=str(uuid4()),
|
||||||
|
photo_url=media.large,
|
||||||
|
thumbnail_url=media.thumb,
|
||||||
|
caption=self.message_text
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
yield
|
||||||
|
|
||||||
|
def message_media_generator(self) -> Generator[TypeMessageMediaResult, None, None]:
|
||||||
|
pixiv = self._pixiv
|
||||||
|
for media in pixiv.images:
|
||||||
|
logger.info(str(media))
|
||||||
|
if pixiv.type in ("illust", "manga"):
|
||||||
|
yield InputMediaPhoto(
|
||||||
|
media=media.large,
|
||||||
|
has_spoiler=pixiv.is_nsfw
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
yield
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import re
|
||||||
|
|
||||||
|
x_url = re.compile(r"^(?:https?://)?(?:www\.|mobile\.)?(?:x|twitter|fixvx|vxtwitter)\.com/(.+)/status/(\d+)")
|
||||||
|
x_media_url = re.compile(r"^(?:https?://)(pbs|video)\.twimg\.com/(.*)")
|
||||||
|
x_tco_url = re.compile(r"(?:https?://)t\.co/.+$", re.M)
|
||||||
|
message_url = re.compile(r"\[.+]", re.S)
|
||||||
|
|
||||||
|
pixiv_url = re.compile(r"^(?:https?://)?(?:www\.)?pixiv\.net/(?:en/)?(?:artworks/|i/)(\d+)")
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from common import PIXIV_REFRESH_TOKEN
|
||||||
|
from .pixiv import TelegramPixiv
|
||||||
|
from .regex import pixiv_url, x_url
|
||||||
|
from .tweet import TelegramTweet
|
||||||
|
|
||||||
|
|
||||||
|
class Telegram:
|
||||||
|
def __init__(self, url: str):
|
||||||
|
self._url = url
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
if x_url.match(self._url):
|
||||||
|
async with TelegramTweet(self._url) as tweet:
|
||||||
|
return tweet
|
||||||
|
elif PIXIV_REFRESH_TOKEN and pixiv_url.match(self._url):
|
||||||
|
async with TelegramPixiv(self._url) as pixiv:
|
||||||
|
return pixiv
|
||||||
|
else:
|
||||||
|
return None # TODO add raise and catch
|
||||||
|
|
||||||
|
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||||
|
pass
|
||||||
+250
@@ -0,0 +1,250 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import html
|
||||||
|
from functools import cached_property
|
||||||
|
from typing import Generator, TYPE_CHECKING
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from telegram import (InlineQueryResultMpeg4Gif, InlineQueryResultPhoto, InlineQueryResultVideo, InputMediaPhoto,
|
||||||
|
InputMediaVideo)
|
||||||
|
|
||||||
|
from .logger import get_logger
|
||||||
|
from .net import NetClient
|
||||||
|
from .regex import x_media_url, x_tco_url, x_url
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from .types import TweetInfo, TypeInlineQueryResult, TypeMessageMediaResult
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
twimg_url = 'https://pbs.twimg.com/'
|
||||||
|
vx_api_url = 'https://api.vxtwitter.com/{0}/status/{1}'
|
||||||
|
|
||||||
|
message_raw_text = """{url}
|
||||||
|
<a href="{author_url}">{author}</a>: {text}
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
self._type: str = media_type
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return f"TweetMedia(url={self.url}, thumb={self.thumb}, type={self.type})"
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def _uri(self) -> str | None:
|
||||||
|
if match := x_media_url.match(self._url):
|
||||||
|
return match.group(2).removesuffix('.jpg').removesuffix('.png')
|
||||||
|
return None
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def url(self) -> str:
|
||||||
|
match self._type:
|
||||||
|
case "image":
|
||||||
|
return f"{twimg_url}{self._uri}?format=jpg&name=4096x4096"
|
||||||
|
case "video":
|
||||||
|
return self._url
|
||||||
|
case "gif":
|
||||||
|
return self._url
|
||||||
|
case _:
|
||||||
|
return self._url
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def thumb(self) -> str:
|
||||||
|
match self._type:
|
||||||
|
case "image":
|
||||||
|
return f"{twimg_url}{self._uri}?format=jpg&name=thumb"
|
||||||
|
case "video":
|
||||||
|
return self._thumb
|
||||||
|
case "gif":
|
||||||
|
return self._thumb
|
||||||
|
case _:
|
||||||
|
return self._thumb
|
||||||
|
|
||||||
|
@property
|
||||||
|
def type(self) -> str:
|
||||||
|
return self._type
|
||||||
|
|
||||||
|
|
||||||
|
class Tweet:
|
||||||
|
__slots__ = ('_id', '_author', '_author_id', '_text', '_media', '_sensitive', '__dict__')
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
tweet_id: str,
|
||||||
|
author: str,
|
||||||
|
author_id: str,
|
||||||
|
text: str,
|
||||||
|
media: list[TweetMedia],
|
||||||
|
sensitive: bool = False
|
||||||
|
):
|
||||||
|
self._id: str = tweet_id
|
||||||
|
self._author: str = author
|
||||||
|
self._author_id: str = author_id
|
||||||
|
self._text: str = text
|
||||||
|
self._media: list[TweetMedia] = media
|
||||||
|
self._sensitive: bool = sensitive
|
||||||
|
|
||||||
|
@property
|
||||||
|
def id(self) -> str:
|
||||||
|
return self._id
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def url(self) -> str:
|
||||||
|
return f"https://twitter.com/{self._author_id}/status/{self._id}"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def author(self) -> str:
|
||||||
|
return self._author
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def author_url(self) -> str:
|
||||||
|
return f"https://twitter.com/{self._author_id}"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def text(self) -> str:
|
||||||
|
return self._text
|
||||||
|
|
||||||
|
@property
|
||||||
|
def media(self) -> list[TweetMedia]:
|
||||||
|
return self._media
|
||||||
|
|
||||||
|
@property
|
||||||
|
def sensitive(self) -> bool:
|
||||||
|
return self._sensitive
|
||||||
|
|
||||||
|
|
||||||
|
class ProcessTweet:
|
||||||
|
__slots__ = ('_url', '_tweet')
|
||||||
|
|
||||||
|
def __init__(self, url: str):
|
||||||
|
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.match(self._url)
|
||||||
|
assert match, f"Invalid URL: {self._url}"
|
||||||
|
auther_id, tweet_id = match.groups()
|
||||||
|
return await NetClient.fetch_json(vx_api_url.format(auther_id, tweet_id))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def _tweet_text(self) -> str:
|
||||||
|
match = x_tco_url.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:
|
||||||
|
__slots__ = ('_url', '_tweet', '__dict__')
|
||||||
|
|
||||||
|
def __init__(self, url: str):
|
||||||
|
self._url: str = url
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
async with ProcessTweet(self._url) as tweet:
|
||||||
|
self._tweet = tweet
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||||
|
pass
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def url(self) -> str:
|
||||||
|
return self._tweet.url
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def message_text(self) -> str:
|
||||||
|
tweet = self._tweet
|
||||||
|
return message_raw_text.format(
|
||||||
|
url=tweet.url,
|
||||||
|
author_url=tweet.author_url,
|
||||||
|
author=html.escape(tweet.author),
|
||||||
|
text=html.escape(tweet.text)
|
||||||
|
)
|
||||||
|
|
||||||
|
def inline_query_result(self) -> tuple[TypeInlineQueryResult, ...]:
|
||||||
|
return tuple(self.inline_query_generator())
|
||||||
|
|
||||||
|
def message_media_result(self) -> tuple[TypeMessageMediaResult, ...]:
|
||||||
|
return tuple(self.message_media_generator())
|
||||||
|
|
||||||
|
def inline_query_generator(self) -> Generator[TypeInlineQueryResult, None, None]:
|
||||||
|
tweet = self._tweet
|
||||||
|
for tweet_media in tweet.media:
|
||||||
|
logger.info(str(tweet_media))
|
||||||
|
if tweet_media.type == "image":
|
||||||
|
yield InlineQueryResultPhoto(
|
||||||
|
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(uuid4()),
|
||||||
|
video_url=tweet_media.url,
|
||||||
|
mime_type="video/mp4",
|
||||||
|
thumbnail_url=tweet_media.thumb,
|
||||||
|
title=tweet.text,
|
||||||
|
caption=self.message_text
|
||||||
|
)
|
||||||
|
elif tweet_media.type == "gif":
|
||||||
|
yield InlineQueryResultMpeg4Gif(
|
||||||
|
id=str(uuid4()),
|
||||||
|
mpeg4_url=tweet_media.url,
|
||||||
|
thumbnail_url=tweet_media.thumb,
|
||||||
|
caption=self.message_text
|
||||||
|
)
|
||||||
|
|
||||||
|
def message_media_generator(self) -> Generator[TypeMessageMediaResult, None, None]:
|
||||||
|
tweet = self._tweet
|
||||||
|
for tweet_media in tweet.media:
|
||||||
|
logger.info(str(tweet_media))
|
||||||
|
if tweet_media.type == "image":
|
||||||
|
yield InputMediaPhoto(
|
||||||
|
media=tweet_media.url,
|
||||||
|
has_spoiler=tweet.sensitive
|
||||||
|
)
|
||||||
|
elif tweet_media.type == "video":
|
||||||
|
yield InputMediaVideo(
|
||||||
|
media=tweet_media.url,
|
||||||
|
has_spoiler=tweet.sensitive,
|
||||||
|
thumbnail=tweet_media.thumb
|
||||||
|
)
|
||||||
|
elif tweet_media.type == "gif":
|
||||||
|
if len(tweet.media) == 1:
|
||||||
|
yield tweet_media.url, tweet.sensitive
|
||||||
|
yield InputMediaVideo(
|
||||||
|
media=tweet_media.url,
|
||||||
|
has_spoiler=tweet.sensitive,
|
||||||
|
thumbnail=tweet_media.thumb
|
||||||
|
)
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
from typing import TypedDict
|
||||||
|
|
||||||
|
from telegram import InlineQueryResultMpeg4Gif, InlineQueryResultPhoto, InlineQueryResultVideo, InputMediaPhoto, \
|
||||||
|
InputMediaVideo
|
||||||
|
|
||||||
|
TypeInlineQueryResult = InlineQueryResultMpeg4Gif | InlineQueryResultPhoto | InlineQueryResultVideo
|
||||||
|
InputMediaAnimation = tuple[str, bool]
|
||||||
|
TypeMessageMediaResult = InputMediaPhoto | InputMediaVideo | InputMediaAnimation
|
||||||
|
|
||||||
|
|
||||||
|
class TweetInfo(TypedDict):
|
||||||
|
tweetID: str
|
||||||
|
user_name: str
|
||||||
|
user_screen_name: str
|
||||||
|
text: str
|
||||||
|
media_extended: list[dict]
|
||||||
|
possibly_sensitive: bool
|
||||||
Reference in New Issue
Block a user