在做我的项目时,代码中出现了一个问题。我正在开展我的学校项目,发现了一个问题,即当其他较大的消息正在悄悄发送时,电报 API 不允许发送一部分消息。
我的错误完全是这样的-
2024-03-17 00:01:25,850(init.py:1147 MainThread)错误 - TeleBot:“线程轮询异常:对 Telegram API 的请求失败。错误代码:400。描述:错误请求:消息标题太长” 2024-03-17 00:01:25,852(init.py:1149 MainThread)错误 - TeleBot:“异常回溯: 回溯(最近一次调用最后一次): 文件“C:\Users\Василий\AppData\Roaming\Python\Python311\site-packages elebot_init_.py”,第 1141 行,位于 _threaded_polling self.worker_pool.raise_exceptions() 文件“C:\Users\Василий\AppData\Roaming\Python\Python311\site-packages elebot\util.py”,第 149 行,在 raise_exceptions 中 引发 self.exception_info 文件“C:\Users\Василий\AppData\Roaming\Python\Python311\site-packages elebot\util.py”,第 92 行,运行中 任务(*args,**kwargs) 文件“c:\project\project_code\main.py”,第 178 行,位于 list_of_legs_exercises 中 bot.send_photo(message.chat.id,exercise_image,exercise_description) 文件“C:\Users\Василий\AppData\Roaming\Python\Python311\site-packages elebot_init.py”,第 2125 行,在 send_photo 中 apihelper.send_photo( 文件“C:\Users\Василий\AppData\Roaming\Python\Python311\site-packages elebot pihelper.py”,第 496 行,在 send_photo 中 return _make_request(token, method_url, params=payload, files=files, method='post') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 文件“C:\Users\Василий\AppData\Roaming\Python\Python311\site-packages elebot pihelper.py”,第 164 行,在 _make_request 中 json_result = _check_result(方法名称, 结果) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 文件“C:\Users\Василий\AppData\Roaming\Python\Python311\site-packages elebot pihelper.py”,第 191 行,位于 _check_result 中 引发 ApiTelegramException(方法名称,结果,结果 json) telebot.apihelper.ApiTelegramException:对 Telegram API 的请求失败。错误代码:400。描述:错误请求:消息标题太长
这是我的完整代码-
import telebot
from telebot import types
import sqlite3
from PIL import Image
import io
class Exercise:
def __init__(self, db_path):
self.conn = sqlite3.connect(db_path, check_same_thread=False)
self.cur = self.conn.cursor()
def get_legs_exercise_image_by_id(self, exercise_id):
self.cur.execute("SELECT image FROM exercises_legs WHERE id=?", (exercise_id))
exercise_image = self.cur.fetchone()
if exercise_image is not None:
image_data = exercise_image[0]
image = Image.open(io.BytesIO(image_data))
return image
else:
return None
def get_back_exercise_image_by_id(self, exercise_id):
self.cur.execute("SELECT image FROM exercises_back WHERE id=?", (exercise_id))
exercise_image = self.cur.fetchone()
if exercise_image is not None:
image_data = exercise_image[0]
image = Image.open(io.BytesIO(image_data))
return image
else:
return None
def get_legs_exercise_description_by_id(self, exercise_id):
self.cur.execute("SELECT description FROM exercises_legs WHERE id=?", (exercise_id))
description = self.cur.fetchone()
return description
def get_back_exercise_description_by_id(self, exercise_id):
self.cur.execute("SELECT description FROM exercises_back WHERE id=?", (exercise_id))
description = self.cur.fetchone()
return description
def get_legs_exercise_image_by_availability(self, exercise_availability):
self.cur.execute("SELECT image FROM exercises_legs WHERE availability == ?", (exercise_availability))
exercise_images = self.cur.fetchall()
if exercise_images is not None:
return exercise_images
else:
return None
def get_back_exercise_image_by_availability(self, exercise_availability):
self.cur.execute("SELECT image FROM exercises_back WHERE availability == ?", (exercise_availability))
exercise_images = self.cur.fetchall()
if exercise_images is not None:
return exercise_images
else:
return None
def get_legs_exercise_description_by_availability(self, exercise_availability):
self.cur.execute("SELECT description FROM exercises_legs WHERE availability == ?", (exercise_availability))
descriptions = self.cur.fetchall()
return descriptions
def get_back_exercise_description_by_availability(self, exercise_availability):
self.cur.execute("SELECT description FROM exercises_back WHERE availability == ?", (exercise_availability))
descriptions = self.cur.fetchall()
return descriptions
def add_exercise(self, title, image, description, group_muscle, difficulty, availability, energy_cost):
self.cur.execute("INSERT INTO exercises(title, image, description, group_muscle, difficulty, availability,) VALUES (?, ?, ?, ?, ?, ?, ?)", (title, image, description, group_muscle, difficulty, availability, energy_cost))
self.conn.commit()
def update_exercise(self, exercise_id, title, image, description, group_muscle, difficulty, availability, energy_cost):
self.cur.execute("UPDATE exercises SET title=?, image=?, description=?, group_muscle=?, difficulty=?, availability=? WHERE id=?", (title, image, description, group_muscle, difficulty, availability, energy_cost, exercise_id))
self.conn.commit()
def delete_exercise(self, exercise_id):
self.cur.execute("DELETE FROM exercises WHERE id=?", (exercise_id,))
self.conn.commit()
def close_connection(self):
self.conn.close()
db_path = 'exercises_data.db'
exercise_manager = Exercise(db_path)
token = '7031939959:AAFOYF-nB-3_37yvr0Q7cXT1NnAf3MW-yvw'
bot = telebot.TeleBot(token)
@bot.message_handler(commands=['start'])
def start_menu(message):
markup =types.ReplyKeyboardMarkup()
butn1=types.KeyboardButton('Каталог упражнений')
butn2=types.KeyboardButton('Информация о боте')
markup.row(butn1, butn2)
welcome_text = 'Здравствуйте, этот бот - ваш персональный фитнесс ассистент, он сможет помочь вам в подборе тренировочного плана и упражнений'
bot.send_message(message.chat.id, welcome_text, reply_markup=markup)
@bot.message_handler(content_types=['text'])
def aft_click1(message):
if message.text == 'Информация о боте':
markup =types.ReplyKeyboardMarkup()
butn_back=types.KeyboardButton('Назад')
bot_information_text = 'Здравствуйте, этот бот - ваш персональный фитнесс ассистент, он сможет помочь вам в подборе тренировочного плана и упражнений.\n\nЭтот бот создат в качестве итогового проекта, является всего лишь помощником и не гарантирует 100-процентного результата, если у вас имеются проблемы со здоровьем, то перед выполнением технически сложных упражнений рекомендуется проконсультироваться со специалистом.'
markup.row(butn_back)
bot.send_message(message.chat.id, bot_information_text, reply_markup=markup)
elif message.text == 'Каталог упражнений':
markup =types.ReplyKeyboardMarkup()
butn1=types.KeyboardButton('Упражнения на ноги')
butn2=types.KeyboardButton('Упражнения на спину')
butn3=types.KeyboardButton('Упражнения на пресс')
butn4=types.KeyboardButton('Упражнения на грудные мышцы')
butn5=types.KeyboardButton('Упражнения на руки')
butn6=types.KeyboardButton('Упражнения на плечи')
butn7=types.KeyboardButton('Кардио упражнения')
butn_back=types.KeyboardButton('Назад')
markup.row(butn1, butn2)
markup.row(butn3, butn4)
markup.row(butn5, butn6)
markup.row(butn7, butn_back)
bot.send_message(message.chat.id,'Выберете желаемый тип упражнений по группам мышц', reply_markup=markup)
elif message.text == 'Назад':
markup =types.ReplyKeyboardMarkup()
butn1=types.KeyboardButton('Каталог упражнений')
butn2=types.KeyboardButton('Информация о боте')
markup.row(butn1, butn2)
bot.send_message(message.chat.id, 'Назад', reply_markup=markup)
elif message.text == 'Назад к типам упражнений':
markup =types.ReplyKeyboardMarkup()
butn1=types.KeyboardButton('Упражнения на ноги')
butn2=types.KeyboardButton('Упражнения на спину')
butn3=types.KeyboardButton('Упражнения на пресс')
butn4=types.KeyboardButton('Упражнения на грудные мышцы')
butn5=types.KeyboardButton('Упражнения на руки')
butn6=types.KeyboardButton('Упражнения на плечи')
butn7=types.KeyboardButton('Кардио упражнения')
butn_back=types.KeyboardButton('Назад')
markup.row(butn1, butn2)
markup.row(butn3, butn4)
markup.row(butn5, butn6)
markup.row(butn7, butn_back)
bot.send_message(message.chat.id,'Назад к типам упражнений', reply_markup=markup)
elif message.text == 'Упражнения на ноги':
markup =types.ReplyKeyboardMarkup()
butn1=types.KeyboardButton('Нет никакого инвентаря')
butn2=types.KeyboardButton('Есть гантели или гири')
butn3=types.KeyboardButton('Хожу в тренажерный зал')
butn_back=types.KeyboardButton('Назад к типам упражнений')
markup.row(butn1, butn2, butn3)
markup.row(butn_back)
bot.send_message(message.chat.id,'Выберите тип вашего инвентаря', reply_markup=markup)
bot.register_next_step_handler(message, list_of_legs_exercises)
def list_of_legs_exercises(message):
if message.text == 'Нет никакого инвентаря':
exercise_images = exercise_manager.get_legs_exercise_image_by_availability(('1'))
exercise_descriptions = exercise_manager.get_legs_exercise_description_by_availability(('1'))
x = 0
for i in exercise_images:
exercise_image = i[0]
exercise_image = Image.open(io.BytesIO(exercise_image))
exercise_description = exercise_descriptions[x]
x+=1
bot.send_photo(message.chat.id, exercise_image, exercise_description)
elif message.text == 'Есть гантели или гири':
exercise_images = exercise_manager.get_legs_exercise_image_by_availability(('2'))
exercise_descriptions = exercise_manager.get_legs_exercise_description_by_availability(('2'))
y = 0
for i in exercise_images:
exercise_image = i[0]
exercise_image = Image.open(io.BytesIO(exercise_image))
exercise_description = exercise_descriptions[y]
y+=1
bot.send_photo(message.chat.id, exercise_image, exercise_description)
if message.text == 'Хожу в тренажерный зал':
exercise_images = exercise_manager.get_legs_exercise_image_by_availability(('3'))
exercise_descriptions = exercise_manager.get_legs_exercise_description_by_availability(('3'))
z = 0
for i in exercise_images:
exercise_image = i[0]
exercise_image = Image.open(io.BytesIO(exercise_image))
exercise_description = exercise_descriptions[z]
z+=1
bot.send_photo(message.chat.id, exercise_image, exercise_description)
bot.polling(none_stop= True)
我尝试减少文本量,尽管它无论如何都没有违反限制,但它减少了数据库 - 它没有帮助
我尝试询问GPT,这就是他的答案,也许它可以帮助你: 您遇到的错误“错误请求:消息标题太长”表示您尝试通过 Telegram 发送的照片附带的标题太长。 Telegram 对媒体文件附带的标题的长度有限制。
要解决此问题,您需要确保附加到照片的标题在 Telegram 允许的限制范围内。如果标题超出此限制,您可以调整代码以截断或修改标题。
以下是修改代码来处理此问题的方法:
```python
def list_of_legs_exercises(message):
if message.text == 'Нет никакого инвентаря':
exercise_images = exercise_manager.get_legs_exercise_image_by_availability(('1'))
exercise_descriptions = exercise_manager.get_legs_exercise_description_by_availability(('1'))
x = 0
for i in exercise_images:
exercise_image = i[0]
exercise_image = Image.open(io.BytesIO(exercise_image))
exercise_description = exercise_descriptions[x]
x+=1
# Truncate caption if it's too long
caption = exercise_description[:1024] # Limiting to 1024 characters
bot.send_photo(message.chat.id, exercise_image, caption)
elif message.text == 'Есть гантели или гири':
exercise_images = exercise_manager.get_legs_exercise_image_by_availability(('2'))
exercise_descriptions = exercise_manager.get_legs_exercise_description_by_availability(('2'))
y = 0
for i in exercise_images:
exercise_image = i[0]
exercise_image = Image.open(io.BytesIO(exercise_image))
exercise_description = exercise_descriptions[y]
y+=1
# Truncate caption if it's too long
caption = exercise_description[:1024] # Limiting to 1024 characters
bot.send_photo(message.chat.id, exercise_image, caption)
if message.text == 'Хожу в тренажерный зал':
exercise_images = exercise_manager.get_legs_exercise_image_by_availability(('3'))
exercise_descriptions = exercise_manager.get_legs_exercise_description_by_availability(('3'))
z = 0
for i in exercise_images:
exercise_image = i[0]
exercise_image = Image.open(io.BytesIO(exercise_image))
exercise_description = exercise_descriptions[z]
z+=1
# Truncate caption if it's too long
caption = exercise_description[:1024] # Limiting to 1024 characters
bot.send_photo(message.chat.id, exercise_image, caption)
```
在此修改中,我将标题限制为 1024 个字符。您可以根据 Telegram 当前的限制和您的具体要求调整此限制。