telegram_bots/bots/modules/robot.py

116 lines
5.3 KiB
Python
Raw Normal View History

2021-03-15 18:59:34 +00:00
import os
2021-04-12 11:47:33 +00:00
import re
2021-03-17 09:55:54 +00:00
import time
2021-03-15 18:59:34 +00:00
from tempfile import TemporaryDirectory
import boto3
2021-03-17 10:05:54 +00:00
import filetype
import requests
2021-04-12 11:47:33 +00:00
import twitter
from TikTokApi import TikTokApi
2021-03-15 18:59:34 +00:00
from django.db import models
2021-04-12 11:55:54 +00:00
# from qrtools import QR
2021-04-12 11:47:33 +00:00
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton, MessageEntity
2021-04-23 21:29:03 +00:00
from telegram.error import BadRequest
2021-03-15 18:59:34 +00:00
from telegram.ext import CallbackContext, Dispatcher, MessageHandler, Filters
from djconfig import config
from bots.models import TelegramBotModuleConfig, BotUser
class RobotBotModuleConfig(TelegramBotModuleConfig):
users = models.ManyToManyField(BotUser)
MODULE_NAME = 'RoBOT'
def build_dispatcher(self, dispatcher: Dispatcher):
dispatcher.add_handler(MessageHandler(Filters.audio | Filters.photo | Filters.video | Filters.document,
self.save_file))
2021-04-12 11:47:33 +00:00
dispatcher.add_handler(MessageHandler(Filters.text & (Filters.entity(MessageEntity.URL) |
Filters.entity(MessageEntity.TEXT_LINK)),
self.document_downloader))
2021-03-15 18:59:34 +00:00
return dispatcher
def save_file(self, update: Update, ctx: CallbackContext):
2021-03-15 19:07:45 +00:00
config._reload_maybe()
2021-03-15 18:59:34 +00:00
if self.users.count() and not self.users.filter(user_id=update.effective_user.id).count():
update.effective_message.reply_text('GTFO')
return
markup = InlineKeyboardMarkup([])
if update.message.photo:
file_id = update.message.photo[-1].file_id
elif update.message.audio:
file_id = update.message.audio.file_id
elif update.message.video:
file_id = update.message.video.file_id
elif update.message.document:
file_id = update.message.document.file_id
else:
return
file = ctx.bot.get_file(file_id)
2021-03-17 09:55:54 +00:00
filename = str(int(time.time())) + '-' + os.path.basename(file.file_path)
2021-04-12 11:47:33 +00:00
text = ''
2021-03-15 18:59:34 +00:00
with TemporaryDirectory() as d:
file_path = os.path.join(d, filename)
file.download(file_path)
2021-03-17 10:05:54 +00:00
tp = filetype.guess(file_path)
2021-03-15 18:59:34 +00:00
s3 = boto3.client('s3', aws_access_key_id=config.aws_access_key_id, aws_secret_access_key=config.aws_secret_access_key)
2021-03-17 10:05:54 +00:00
s3.upload_file(file_path, config.s3_bucket, filename, ExtraArgs={'ACL': 'public-read', 'ContentType': tp.mime})
2021-04-12 11:55:54 +00:00
# if update.message.text == 'qr':
# qr = QR(filename=file_path)
# qr.decode()
# text = f'QR:\n{qr.data}'
2021-03-15 18:59:34 +00:00
file_url = f'https://{config.s3_bucket}.s3.amazonaws.com/{filename}'
2021-04-12 11:47:33 +00:00
text += f'\n\n{file_url}'
2021-03-15 18:59:34 +00:00
if update.message.photo:
markup.inline_keyboard = [[
2022-12-14 11:08:49 +00:00
InlineKeyboardButton('Google IS', f'https://lens.google.com/uploadbyurl?url={file_url}'),
2021-03-15 18:59:34 +00:00
InlineKeyboardButton('Yandex IS', f'https://yandex.ru/images/search?rpt=imageview&url={file_url}'),
InlineKeyboardButton('SauceNao', f'https://saucenao.com/search.php?url={file_url}')
]]
2021-04-12 11:47:33 +00:00
update.message.reply_text(text, disable_web_page_preview=True, reply_markup=markup)
def document_downloader(self, update: Update, ctx: CallbackContext):
config._reload_maybe()
if self.users.count() and not self.users.filter(user_id=update.effective_user.id).count():
update.effective_message.reply_text('GTFO')
return
links = update.effective_message.parse_entities([MessageEntity.URL, MessageEntity.TEXT_LINK]).values()
for link in links:
try:
twitter_matches = re.match(r'https?://twitter.com/[A-Za-z0-9_]{1,15}/status/(\d+).*', link)
tiktok_matches = re.match(r'https?://vm.tiktok.com/.*', link)
2021-04-12 11:47:33 +00:00
if link.endswith('.gif'):
update.message.reply_document(link)
elif twitter_matches:
api = twitter.Api(config.twitter_consumer_api_key, config.twitter_consumer_api_secret,
config.twitter_access_token, config.twitter_access_token_secret)
tweet = api.GetStatus(twitter_matches.group(1))
try:
2021-04-23 21:29:03 +00:00
for media in tweet.media:
2021-04-23 21:30:14 +00:00
if media.type == 'video':
2021-04-12 11:47:33 +00:00
max_bitrate = -1
max_bitrate_link = None
2021-04-23 21:31:45 +00:00
for variant in media.video_info['variants']:
2021-04-12 11:47:33 +00:00
if variant['content_type'] == 'video/mp4' and variant['bitrate'] > max_bitrate:
max_bitrate = variant['bitrate']
max_bitrate_link = variant['url']
if max_bitrate_link is not None:
update.message.reply_video(max_bitrate_link)
except KeyError:
update.message.reply_text('Unable to retrieve video info from tweet')
elif tiktok_matches:
api = TikTokApi()
vid = api.video(link)
2021-04-12 11:47:33 +00:00
else:
update.message.reply_text('Can\'t detect link type')
except BadRequest:
update.message.reply_text('Unable to retrieve file')