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

基于aiogram3的Telegram Bot多帖子回调回复差异化问题

解决方案

1. 数据库结构设计

用sqlite3创建一个映射表,存储频道帖子ID与对应回复文本的关联关系:

CREATE TABLE IF NOT EXISTS post_responses (
    post_id INTEGER PRIMARY KEY,
    response_text TEXT NOT NULL
);

2. 封装数据库操作函数

写几个轻量函数处理数据库的初始化、插入、查询操作:

import sqlite3

def init_db():
    conn = sqlite3.connect('post_responses.db')
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS post_responses (
            post_id INTEGER PRIMARY KEY,
            response_text TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()

def add_post_response(post_id, response_text):
    conn = sqlite3.connect('post_responses.db')
    cursor = conn.cursor()
    # 用INSERT OR REPLACE避免重复插入同一帖子ID的记录
    cursor.execute('INSERT OR REPLACE INTO post_responses (post_id, response_text) VALUES (?, ?)', 
                   (post_id, response_text))
    conn.commit()
    conn.close()

def get_post_response(post_id):
    conn = sqlite3.connect('post_responses.db')
    cursor = conn.cursor()
    cursor.execute('SELECT response_text FROM post_responses WHERE post_id = ?', (post_id,))
    result = cursor.fetchone()
    conn.close()
    return result[0] if result else None

3. 发布带按钮的帖子并绑定回复文本

发布频道帖子时,获取返回的帖子ID,将其与对应回复文本存入数据库:

from aiogram import Bot, types
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton

# 替换为你的Bot Token和频道ID
bot = Bot(token="YOUR_BOT_TOKEN")
CHANNEL_ID = "@your_channel_username"

async def publish_post(post_content, response_text):
    # 创建4个内联按钮,统一回调数据(因需求是任意按钮返回相同文本)
    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text="1", callback_data="post_btn"),
         InlineKeyboardButton(text="2", callback_data="post_btn")],
        [InlineKeyboardButton(text="3", callback_data="post_btn"),
         InlineKeyboardButton(text="4", callback_data="post_btn")]
    ])
    # 发送帖子到频道
    message = await bot.send_message(chat_id=CHANNEL_ID, text=post_content, reply_markup=keyboard)
    # 绑定帖子ID与回复文本
    add_post_response(message.message_id, response_text)

# 示例:发布两个测试帖子
# await publish_post("果戈理相关帖子内容", "对啦,这是果戈理")
# await publish_post("蒲宁相关帖子内容", "真棒,这是蒲宁")

4. 处理按钮回调逻辑

注册回调处理器,根据点击按钮所在的帖子ID,从数据库取出对应回复并返回给用户:

from aiogram import Router
from aiogram.types import CallbackQuery

router = Router()

@router.callback_query(lambda c: c.data == "post_btn")
async def handle_post_button(callback: CallbackQuery):
    # 获取按钮所在的帖子ID
    post_id = callback.message.message_id
    # 查询对应回复文本
    response_text = get_post_response(post_id)
    if response_text:
        # 用弹窗形式回复用户
        await callback.answer(response_text, show_alert=True)
    else:
        await callback.answer("暂无对应回复", show_alert=True)

5. 初始化并启动Bot

在主函数中完成数据库初始化和Bot启动:

import asyncio

async def main():
    init_db()
    await bot.delete_webhook(drop_pending_updates=True)
    await router.start_polling(bot)

if __name__ == "__main__":
    asyncio.run(main())

内容的提问来源于stack exchange,提问作者QWERTYZ PB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 12:47:45