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

如何基于数据库数据自动生成Telethon Markup按钮?

解决Telethon根据数据库条目自动生成对应数量按钮的问题

原代码的问题在于遍历数据库查询结果时,只是反复覆盖noplat变量,最终仅使用最后一条数据生成单个按钮。要实现根据条目数自动生成按钮,需要把每条数据对应的按钮都添加到按钮列表中,再生成回复标记。

修改后的完整代码

@client.on(events.NewMessage(pattern="(?i)/start"))
async def select(event):
    sender = await event.get_sender()
    SENDER = sender.id
    idchat = sender.id
    fname = sender.first_name

    import datetime
    now = datetime.datetime.now()
    dt = now.strftime("%Y-%m-%d")

    sql = "SELECT noplat FROM tblsolar WHERE tanggal=%s AND idchat_supir=%s;"
    crsr.execute(sql, (dt, idchat))
    res = crsr.fetchall()
    
    # 初始化按钮列表,每条数据对应一个按钮(每行一个)
    buttons_list = []
    for row in res:
        noplat = row[0]
        # 每个按钮单独作为一行,添加到列表
        buttons_list.append([Button.text(noplat, resize=True, single_use=True)])

    markup = event.client.build_reply_markup(buttons_list)

    text = "🖐"
    text1 = f"Hello, <b>{fname}</b>\nplease, choose one below\n"
    await client.send_message(SENDER, text, parse_mode="HTML")
    await client.send_message(SENDER, text1, buttons=markup, parse_mode="HTML")

关键修改点

  • 新增buttons_list列表,用于存储所有按钮对象
  • 遍历查询结果res时,为每条noplat数据创建一个按钮,并将其作为单独一行(嵌套列表)添加到buttons_list中
  • 将buttons_list传入build_reply_markup,生成包含所有按钮的回复标记

如果需要将按钮按多列排列(比如每行2个按钮),可以调整按钮列表的结构,例如:

buttons_list = []
current_row = []
for idx, row in enumerate(res):
    current_row.append(Button.text(row[0], resize=True, single_use=True))
    # 每2个按钮组成一行
    if (idx + 1) % 2 == 0:
        buttons_list.append(current_row)
        current_row = []
# 处理剩余的按钮
if current_row:
    buttons_list.append(current_row)

内容的提问来源于stack exchange,提问作者sen yang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:20:17