Telegram机器人消息置顶与一键取消:完整API与Python实战教程

详细介绍Telegram Bot API中固定聊天消息和取消固定的方法,包括bind参数、使用场景、Python代码示例,以及如何通过命令实现一键取消。

阅读提示涉及账号和安全设置时,请边阅读边核对当前设备界面。

在Telegram群组或频道中,置顶消息是管理信息的重要手段。对于机器人开发者来说,掌握固定(pin)和取消固定(unpin)消息的API是必备技能。本文将从零开始,带你实现消息的固定与一键取消,让你的机器人管理能力更进一步。

什么是固定消息?为什么需要机器人来操作?

固定消息是Telegram的一项经典功能,它可以将重要信息(如公告、规则、活动通知)显示在聊天列表的顶部,确保每个成员都能第一时间看到。对于群组或频道管理员而言,手动固定消息很简单,但当消息需要定期更新、批量处理或与其他自动化流程联动时,手动操作就显得低效。利用Bot API,我们可以让机器人自动固定特定消息,甚至支持管理员一键取消,极大提升管理效率。

固定消息API基础:pinChatMessage方法

Telegram Bot API提供了pinChatMessage方法,用于将指定消息固定到聊天顶部。调用该方法需要机器人拥有对应的权限:在群组中,机器人必须是管理员且具有“固定消息”权限;在频道中,机器人通常是管理员身份。方法参数如下:

  • chat_id:必填。聊天或频道的唯一标识(支持用户名或ID)。
  • message_id:必填。要固定的消息ID。
  • disable_notification:选填。若为True,则不会向订阅者发送固定通知(默认通知)。对于静默固定非常实用。

取消固定消息:unpinChatMessage方法

与固定对应,取消固定使用unpinChatMessage方法。调用时需提供chat_id和可选的message_id。如果不传message_id,则取消最近一条固定的消息(但注意官方建议始终指定,避免歧义)。此外,你还可以使用unpinAllChatMessages方法一次性取消聊天中所有固定的消息,适合彻底清理置顶场景。

Python实现:固定消息与一键取消的完整代码

下面我们使用Python的python-telegram-bot库(v20.x)展示完整实现。假设机器人已经配置好Token。

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes

# 机器人Token
TOKEN = "YOUR_BOT_TOKEN"

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("发送 /pin <消息ID> 固定消息,或 /unpin <消息ID> 取消固定。")

async def pin(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """固定指定消息"""
    if not context.args:
        await update.message.reply_text("用法:/pin <消息ID>")
        return
    try:
        message_id = int(context.args[0])
    except ValueError:
        await update.message.reply_text("请输入合法的消息ID。")
        return
    chat_id = update.effective_chat.id
    # 调用API固定消息
    await context.bot.pin_chat_message(chat_id=chat_id, message_id=message_id)
    await update.message.reply_text(f"消息  已固定!")

async def unpin(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """取消固定指定消息"""
    if not context.args:
        # 如果没有参数,取消最近固定的消息
        try:
            await context.bot.unpin_chat_message(chat_id=update.effective_chat.id)
            await update.message.reply_text("已取消最近固定的消息。")
        except Exception as e:
            await update.message.reply_text(f"取消失败:")
        return
    try:
        message_id = int(context.args[0])
        await context.bot.unpin_chat_message(chat_id=update.effective_chat.id, message_id=message_id)
        await update.message.reply_text(f"消息  已取消固定。")
    except Exception as e:
        await update.message.reply_text(f"取消失败:")

async def unpin_all(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """一键取消所有固定消息"""
    await context.bot.unpin_all_chat_messages(chat_id=update.effective_chat.id)
    await update.message.reply_text("已取消全部固定消息。")

# 主函数
def main():
    app = Application.builder().token(TOKEN).build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("pin", pin))
    app.add_handler(CommandHandler("unpin", unpin))
    app.add_handler(CommandHandler("unpinall", unpin_all))
    app.run_polling()

if __name__ == "__main__":
    main()

在上述代码中,我们定义了三个命令:/pin/unpin/unpinall。通过向机器人发送带有消息ID的命令,即可固定或取消固定。这种方式非常适合手动管理,但还不够“一键”。

一键取消:通过命令或回调按钮实现

为了让管理员更便捷地操作,我们可以将取消固定与内联键盘按钮结合。例如,当机器人固定一条消息时,同时发送一个带有“取消固定”按钮的提示消息。点击该按钮,通过回调机制触发取消操作,真正做到“一键取消”。

async def pin_with_button(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """固定消息并附加取消按钮"""
    if not context.args:
        await update.message.reply_text("用法:/pinbtn <消息ID>")
        return
    try:
        message_id = int(context.args[0])
        chat_id = update.effective_chat.id
        await context.bot.pin_chat_message(chat_id=chat_id, message_id=message_id)
        # 创建回调按钮
        keyboard = [[InlineKeyboardButton("一键取消", callback_data=f"unpin:")]]
        reply_markup = InlineKeyboardMarkup(keyboard)
        await update.message.reply_text(
            f"消息  已固定!点击下方按钮取消。",
            reply_markup=reply_markup
        )
    except Exception as e:
        await update.message.reply_text(f"操作失败:")

async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    data = query.data
    if data.startswith("unpin:"):
        message_id = int(data.split(":")[1])
        await context.bot.unpin_chat_message(chat_id=query.message.chat_id, message_id=message_id)
        await query.edit_message_text(f"消息  已取消固定。")

在上述扩展中,固定消息后自动生成带按钮的操作提示。管理员点击按钮,机器人立即取消固定,并更新提示文字。这种交互模式在真实场景中非常受欢迎。

常见问题与注意事项

  • 机器人需要哪些权限?在群组中,机器人必须是管理员,并且有“固定消息”权限(对应权限位can_pin_messages)。在频道中,机器人也需要管理员身份。
  • 固定消息是否有限制?Telegram官方未限制固定消息的数量,但每个聊天同时置顶的只会显示一条(最新固定)。固定多条时,只有最新的一条会置顶,但可通过“已固定的消息”列表查看。
  • 为什么我无法固定消息?检查机器人是否是管理员,以及是否在BotFather中启用了对应权限。另外,某些非法消息(如服务消息)可能无法固定。
  • 如何静默固定?disable_notification设为True,固定时不打扰用户。

总结

固定和取消固定消息是Telegram机器人的基础但强大的功能。通过本文的API梳理和Python示例,你可以快速实现自动化置顶、一键取消,甚至结合回调按钮打造更人性化的交互流程。掌握这一技能,能显著提升群组和频道的管理效率。现在就开始动手实践吧!

FAQ

下载与安装

常见问题

机器人固定消息需要哪些权限?

在群组中,机器人必须是管理员,并且拥有'固定消息'(can_pin_messages)权限。在频道中同理。如果权限不足,调用pinChatMessage会返回403错误。

如何取消全部固定消息?

可以调用unpinAllChatMessages方法,传入chat_id即可一次性取消所有固定消息。在python-telegram-bot中对应unpin_all_chat_messages方法。

固定消息后用户能否看到通知?

默认会发送通知,但可以在调用pinChatMessage时将disable_notification参数设为True,实现静默固定,用户不会收到通知。

能否在固定消息中同时设置取消按钮?

可以。您可以使用InlineKeyboardButton创建回调按钮,通过CallbackQueryHandler处理点击事件,在回调中调用unpinChatMessage实现一键取消。