Send long message in telegram bot python
Asked Answered
W

3

6

I have a telegram bot and I want to send a message
in which the error message will be returned to me

my code is :

            path = 'C:\\Bot\\Log\\aaa\\*.log' 
            files = glob.glob(path) 
            nlines= 0
            data = "Servers :  \n"
            for name in files: 
                    with open(name) as f:
                        for line in f  :
                            nlines += 1
                            if (line.find("Total") >= 0):
                                data += line
                                for i in range(5):
                                    data += next(f)
                                data += f'\n{emoji.emojize(":blue_heart:")} ----------------------------------------------------{emoji.emojize(":blue_heart:")}\n'    
                            if (line.find("Source") >= 0):
                                data += line

            query.edit_message_text(
                text=f"{data}",
                reply_markup=build_keyboard(number_list),
                  
            )

my error is :

telegram.error.BadRequest: Message_too_long   

According to this code model, how can I send my message to the bot?

Westfall answered 23/1, 2022 at 5:58 Comment(1)
slice the text in 4096-character batchesMirador
P
7

its still an open issue, but you can split your request for 4089 chars per send

you have 2 options:

if len(info) > 4096:
    for x in range(0, len(info), 4096):
        bot.send_message(message.chat.id, info[x:x+4096])
    else:
        bot.send_message(message.chat.id, info)

or

msgs = [message[i:i + 4096] for i in range(0, len(message), 4096)]
for text in msgs:
     update.message.reply_text(text=text)
Perturb answered 23/1, 2022 at 9:30 Comment(0)
C
1

This code may works :

if len(info) > 4096:
    for x in range(0, len(info), 4096):
        bot.send_message(message.chat.id, info[x:x+4096])
    else:
        bot.send_message(message.chat.id, info)
Cupulate answered 23/1, 2022 at 7:11 Comment(0)
J
0

Since Telegram has limit of 4096 chars per message, one way to work around will be to break your message down into 4096 chars and then send it, and repeat till the end.

You can begin with something like:

def slice(val, start=1, stop=None):
    return val[start:stop]


limit = 4096
chars_arr = list(long_message)
length = len(chars_arr)
print(f"Long message length: {length} and limit is {limit}")

# Iterate for batches of 4096
print("".join(slice(chars_arr, 0, 4096)))
Juratory answered 23/1, 2022 at 6:26 Comment(1)
What would my code change if I wanted to use this model?Westfall

© 2022 - 2024 — McMap. All rights reserved.