I’m working on a Telegram bot using Python and trying to send an error message, but I keep hitting a snag. Here’s the approach I’m using:
import glob
import emoji
def send_long_message(query):
log_files = glob.glob('C:\\Bot\\Log\\aaa\\*.log')
message = 'Servers:\n'
for file in log_files:
with open(file) as f:
for line in f:
if 'Total' in line:
message += line
message += ''.join([next(f) for _ in range(5)])
message += f'\n{emoji.emojize(":star:")} -------------------- {emoji.emojize(":star:")}\n'
if 'Source' in line:
message += line
query.edit_message_text(
text=message,
reply_markup=create_buttons(some_list)
)
# When running the code, I get:
# telegram.error.BadRequest: Message_too_long
# How can I adjust this so my long message sends properly?
Any suggestions on resolving this issue would be appreciated. Thanks!
In my experience with Telegram bots, a robust solution for handling long messages is to implement pagination instead of trying to send a single, lengthy message. You can break your log data into manageable segments, each containing about 3000 characters. Send the first segment as the initial message and incorporate navigation buttons like ‘Next’ and ‘Previous’ to let users browse through the remaining text. Although this may require some changes to your existing code, it offers a more user-friendly method to display extensive logs while avoiding the message length error.
yo dude, ive had this problem too. it’s a pain in the butt. what i did was split the message into smaller bits. like, make a function that breaks it up into chunks of like 3000 characters or so. then send each chunk as a seperate message. works like a charm! good luck man
I’ve faced a similar challenge with long messages in Telegram bots. The key is to split your message into smaller chunks. Telegram has a limit of about 4096 characters per message.
Here’s an approach that worked for me:
- Create a function to split your message into chunks of, say, 3000 characters.
- Iterate through these chunks and send them as separate messages.
You can modify your code like this:
def send_long_message(query, message):
max_length = 3000
messages = [message[i:i+max_length] for i in range(0, len(message), max_length)]
for i, chunk in enumerate(messages):
if i == 0:
query.edit_message_text(text=chunk)
else:
query.message.reply_text(text=chunk)
# Send buttons separately if needed
query.message.reply_text(text='Options:', reply_markup=create_buttons(some_list))
This approach worked well in my projects. Remember to handle any potential errors and adjust the max_length as needed. Hope this helps!