我有一个电报机器人,我想发送消息
其中错误信息将返回给我
我的代码是:
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
根据这个代码模型,我如何向机器人发送消息?
这仍然是一个悬而未决的问题,但您可以将请求拆分为每次发送 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)
此代码可能有效:
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)
由于 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)))
itertools.batched
:
for msg_batch in itertools.batched(long_message, 4096):
bot.send_message(message.chat.id, msg_batch)