在电报机器人中发送长消息 python

Send long message in telegram bot python

我有一个电报机器人,我想发送消息
其中错误信息会返回给我

我的代码是:

            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),
                  
            )

我的错误是:

telegram.error.BadRequest: Message_too_long   

根据此代码模型,我如何将消息发送给机器人?

由于 Telegram 对每条消息有 4096 个字符的限制,一种解决方法是将您的消息分解为 4096 个字符,然后发送,重复直到结束。

您可以从以下内容开始:

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)))

此代码可能有效:

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)

它仍然是一个悬而未决的问题,但您可以将请求拆分为每次发送 4089 个字符

你有 2 个选择:

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)

msgs = [message[i:i + 4096] for i in range(0, len(message), 4096)]
for text in msgs:
     update.message.reply_text(text=text)