用 Python 打造一个 Telegram 二手交易商城机器人
一、项目概述
我们将构建一个机器人,具备以下功能:
功能模块 说明 🧾 发布商品 用户填写名称、价格、描述、图片,自动生成商品卡片 🔍 搜索商品 支持关键词搜索 🗑️ 删除商品 用户可删除自己发布的商品 🧠 @letstgbot 集成 输入 /search 关键词
即可跳转 Telegram 搜索相关频道创新亮点:
无数据库实现:用 JSON 临时存储商品,简单直观;
交互式发布流程(使用
ConversationHandler
);融合搜索生态(借助
@letstgbot
)实现“商品 + 讨论社区”一体化体验。
二、环境准备
1️⃣ 安装依赖
pip install python-telegram-bot==20.6
2️⃣ 注册 Telegram Bot
在 Telegram 搜索
@BotFather
→ 创建新机器人,获取BOT_TOKEN
。
三、核心代码实现
1️⃣ 导入依赖与初始化
import json, os from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import (ApplicationBuilder, CommandHandler, MessageHandler, filters,ConversationHandler, ContextTypes, CallbackQueryHandler )BOT_TOKEN = "你的_BOT_TOKEN" DATA_FILE = "products.json"# 初始化商品数据文件 if not os.path.exists(DATA_FILE):with open(DATA_FILE, "w", encoding="utf-8") as f:json.dump([], f, ensure_ascii=False, indent=2)
2️⃣ 发布商品流程
使用 ConversationHandler 实现分步发布:
# 状态定义 NAME, PRICE, DESC, PHOTO = range(4)async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):await update.message.reply_text("欢迎来到 🛒 Telegram 二手商城机器人!\n输入 /post 发布商品 或 /list 查看全部商品。")async def post_start(update: Update, context: ContextTypes.DEFAULT_TYPE):await update.message.reply_text("请输入商品名称:")return NAMEasync def post_name(update: Update, context: ContextTypes.DEFAULT_TYPE):context.user_data["name"] = update.message.textawait update.message.reply_text("请输入价格(例如:100 元):")return PRICEasync def post_price(update: Update, context: ContextTypes.DEFAULT_TYPE):context.user_data["price"] = update.message.textawait update.message.reply_text("请发送商品描述:")return DESCasync def post_desc(update: Update, context: ContextTypes.DEFAULT_TYPE):context.user_data["desc"] = update.message.textawait update.message.reply_text("请上传一张商品图片:")return PHOTOasync def post_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):photo = update.message.photo[-1]file_id = photo.file_idcontext.user_data["photo"] = file_id# 保存商品with open(DATA_FILE, "r", encoding="utf-8") as f:products = json.load(f)products.append({"user": update.message.from_user.username,"name": context.user_data["name"],"price": context.user_data["price"],"desc": context.user_data["desc"],"photo": file_id})with open(DATA_FILE, "w", encoding="utf-8") as f:json.dump(products, f, ensure_ascii=False, indent=2)await update.message.reply_text("✅ 商品发布成功!输入 /list 查看所有商品。")return ConversationHandler.ENDasync def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):await update.message.reply_text("发布已取消。")return ConversationHandler.END
3️⃣ 查看与搜索商品
async def list_products(update: Update, context: ContextTypes.DEFAULT_TYPE):with open(DATA_FILE, "r", encoding="utf-8") as f:products = json.load(f)if not products:await update.message.reply_text("暂无商品发布。")returnfor p in products:text = f"📦 {p['name']}\n💰 价格:{p['price']}\n📝 描述:{p['desc']}\n👤 卖家:@{p['user']}"await update.message.reply_photo(photo=p['photo'], caption=text)async def search_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):if not context.args:await update.message.reply_text("用法:/search <关键词>")returnkeyword = " ".join(context.args)text = (f"🔍 关键词:{keyword}\n"f"可以在 Telegram 中使用 @letstgbot 搜索相关频道或群组:\n"f"👉 在 Telegram 搜索框输入:@letstgbot {keyword}")await update.message.reply_text(text)
4️⃣ 主函数整合
def main():app = ApplicationBuilder().token(BOT_TOKEN).build()post_conv = ConversationHandler(entry_points=[CommandHandler("post", post_start)],states={NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, post_name)],PRICE: [MessageHandler(filters.TEXT & ~filters.COMMAND, post_price)],DESC: [MessageHandler(filters.TEXT & ~filters.COMMAND, post_desc)],PHOTO: [MessageHandler(filters.PHOTO, post_photo)],},fallbacks=[CommandHandler("cancel", cancel)],)app.add_handler(CommandHandler("start", start))app.add_handler(CommandHandler("list", list_products))app.add_handler(CommandHandler("search", search_cmd))app.add_handler(post_conv)print("🛍️ 二手商城机器人已启动!")app.run_polling()if __name__ == "__main__":main()
四、运行效果演示(逻辑流程)
1️⃣ 用户输入
/post
→ 依次输入名称、价格、描述并上传图片。
2️⃣ Bot 自动生成商品卡片,保存至本地products.json
。
3️⃣ 用户输入/list
查看全部商品。
4️⃣ 输入/search iPhone
→ Bot 回复一条可在 @letstgbot 中搜索相关频道的提示。
五、创新设计点
功能模块 创新亮点 可扩展方向 🧾 发布商品 多步对话式收集信息 支持编辑、删除、自定义标签 🔍 搜索扩展 /search
命令结合@letstgbot
搜索引擎自动跳转项目讨论群 💾 存储设计 轻量 JSON 本地存储 可迁移至 SQLite / Firebase 🤖 Bot 逻辑 多 Handler 模式实现清晰交互 可加入 Inline 按钮 / 分页浏览
六、安全与合规说明
本文仅展示技术实现逻辑,不支持或涉及真实交易行为。
@letstgbot
搜索仅为 Telegram 官方搜索引擎指引。建议在自测环境运行 Bot,勿上传用户隐私内容。
代码仅供学习研究使用。