You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telegram消息编辑报错:随机内容发送与洗牌按钮功能异常

Telegram Bot: Fixing Message Edit Errors with the "Shuffle Again" Inline Button

Hey, let's figure out why your Telegram bot's message edit is failing when users click the "Shuffle Again" button. I've run into similar snags with inline buttons before, so let's break down the common issues and fix your code step by step.

First, Let's Diagnose the Likely Problems

Your current code sets up the button and sends the initial random item, but there are two big missing pieces that are almost certainly causing the error:

  1. You don't have a handler to respond to the button's callback query — Telegram needs explicit code to handle when a user clicks an inline button.
  2. You're not properly referencing the original message's ID when trying to edit it (I'm guessing you tried to edit without passing this required ID).

Here's the Fixed, Complete Code

Let's fill in the gaps and make sure everything works:

import random
from telegram import types
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler

# Replace this with your actual list of items to shuffle
shuffle_items = ["Track 1", "Track 2", "Track 3", "Track 4", "Track 5"]

def get_random_item():
    return random.choice(shuffle_items)

# Reusable inline keyboard (no need to recreate it every time)
shuffle_keyboard = types.InlineKeyboardMarkup(
    [[types.InlineKeyboardButton(text='Shuffle Again', callback_data='shuffle')]]
)

# Handle the /shuffle command
@bot.message_handler(commands=['shuffle'])
def start_shuffle(message):
    chat_id = message.chat.id
    # Send the initial message and save its ID for future edits
    sent_msg = bot.send_message(chat_id, get_random_item(), reply_markup=shuffle_keyboard)

# Handle the "Shuffle Again" button click
@bot.callback_query_handler(func=lambda call: call.data == 'shuffle')
def handle_shuffle_click(call):
    chat_id = call.message.chat.id
    new_random_item = get_random_item()
    try:
        # Edit the original message with new content (keep the button)
        bot.edit_message_text(
            chat_id=chat_id,
            message_id=call.message.message_id,
            text=new_random_item,
            reply_markup=shuffle_keyboard
        )
        # Let Telegram know we've handled the callback (removes the loading spinner)
        bot.answer_callback_query(call.id)
    except Exception as e:
        # Print the error to debug, and notify the user
        print(f"Edit error: {str(e)}")
        bot.answer_callback_query(call.id, text="Oops, something went wrong trying to shuffle!")

# Don't forget to start your bot (adjust for your library version)
# updater = Updater("YOUR_BOT_TOKEN_HERE")
# dp = updater.dispatcher
# dp.add_handler(CommandHandler('shuffle', start_shuffle))
# dp.add_handler(CallbackQueryHandler(handle_shuffle_click))
# updater.start_polling()
# updater.idle()

Extra Troubleshooting Tips If It's Still Broken

  • Check Bot Permissions: In groups, make sure your bot has permission to edit messages (it needs to be an admin or have the "Edit Messages" permission enabled).
  • Message Age: Telegram blocks edits to messages older than 48 hours — if you're testing with an old message, send a new one and try again.
  • Library Version: If you're using python-telegram-bot v20+, the syntax is a bit different (uses Application instead of Updater). Double-check your library docs if you're on the latest version.
  • Error Messages: If you see a specific error in your console, share it! That'll help narrow down the issue even faster.

内容的提问来源于stack exchange,提问作者Sergey Ronin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:03:04