Skip to content

Commit

Permalink
split long tweet to multiple messages (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
Travis Lee committed Sep 8, 2023
1 parent 0edece9 commit 011197c
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 18 deletions.
23 changes: 23 additions & 0 deletions lib/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,26 @@ async def url_get_redirect(self, url: str, max_times: int) -> str:
except Exception as e:
logger.error(e)
return url


def split_long_string(input_string: str, max_length: int = 4096) -> list:
if len(input_string) <= max_length:
return [input_string]

result_strings = []
temp_lines = []
temp_length = 0

lines = input_string.splitlines()
for line in lines:
if temp_length + len(line) <= max_length:
temp_lines.append(line)
temp_length += len(line) + 1
else:
result_strings.append('\n'.join(temp_lines))
temp_lines = [line]
temp_length = len(line) + 1

result_strings.append('\n'.join(temp_lines))

return result_strings
9 changes: 9 additions & 0 deletions lib/version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# -*- coding: utf-8 -*-

version = '0.2.3'
message = ('*Tweet forward Bot*',
f'Version: {version}\n',
'*Usage:*',
'`/down <url>`: Grab tweet and send to telegram.',
'`/start`: Show this message.',
'`/help`: Show this message.',)
39 changes: 22 additions & 17 deletions telebot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,10 @@
from telegram.ext import Application, CommandHandler, MessageHandler, ContextTypes, filters

from lib.logger import logger
from lib.utils import Session
from lib.utils import Session, split_long_string
from lib import version
from twitterclient.twitter import TwitterClient

version = '0.2'
message = ('*Tweet forward Bot*',
f'Version: {version}\n',
'*Usage:*',
'`/down <url>`: Grab tweet and send to telegram.',
'`/start`: Show this message.',
'`/help`: Show this message.',)


class TelegramBot(object):
def __init__(self, ):
Expand All @@ -30,12 +23,13 @@ def __init__(self, ):
self.set_bot_handler()

def run(self):
_interval = os.environ.get('INTERVAL', 30.0)
interval_default = 30.0
_interval = os.environ.get('INTERVAL', interval_default)
try:
interval = float(_interval)
except ValueError:
self.logger.warning('INTERVAL is not a number, use default value 30')
interval = 30.0
interval = interval_default
self.logger.warning('INTERVAL is not a number, use default value %s', interval)

self.application.run_polling(allowed_updates=Update.ALL_TYPES, poll_interval=interval)

Expand Down Expand Up @@ -82,7 +76,7 @@ async def help(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""
Send a message when the command /help is issued.
"""
text = '\n'.join(message)
text = '\n'.join(version.message)
(text.replace('_', '\\_')
.replace('*', '\\*')
.replace('[', '\\[')
Expand All @@ -93,7 +87,7 @@ async def help(update: Update, context: ContextTypes.DEFAULT_TYPE):
async def download(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
urls = await self.get_urls(update.message.text)
if not urls:
await update.message.reply_text('Can\'t find any Twitter url in your message.', quote=True)
await self.reply_text(update, "Can't find any Twitter url in your message.")
for url in urls:
await self.download_twitter(update, url)

Expand All @@ -102,9 +96,20 @@ async def download_twitter(self, update: Update, url: str):
if len(images_path) + len(videos_path) > 0:
await self.send_media(update=update, images_path=images_path, videos_path=videos_path, text=text)
elif text:
await update.message.reply_text(text, quote=True, disable_web_page_preview=True)
await self.reply_text(update, text)
else:
await self.reply_text(update, 'Download failed.')

@staticmethod
async def reply_text(update: Update, text: str):
quote = True
if len(text) <= 4096:
await update.message.reply_text(text, quote=quote, disable_web_page_preview=True)
else:
await update.message.reply_text('Download failed.', quote=True)
text_split = split_long_string(text)
for text_part in text_split:
await update.message.reply_text(text_part, quote=quote, disable_web_page_preview=True)
quote = False

async def send_media(self, update: Update, images_path: [str], videos_path: [str], text: str = ''):
medias = []
Expand All @@ -117,7 +122,7 @@ async def send_media(self, update: Update, images_path: [str], videos_path: [str

if len(text) > 1024:
await update.message.reply_media_group(media=medias, quote=True)
await update.message.reply_text(text, quote=True, disable_web_page_preview=True)
await self.reply_text(update, text)
else:
await update.message.reply_media_group(media=medias, caption=text, quote=True)

Expand Down
3 changes: 2 additions & 1 deletion web/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
import uvicorn
from quart import Quart, Response, request, jsonify

from telebot.bot import TelegramBot, version
from telebot.bot import TelegramBot
from lib.logger import logger
from lib.version import version


async def webserver() -> None:
Expand Down

0 comments on commit 011197c

Please sign in to comment.