from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
ConversationHandler,
MessageHandler,
filters,
)
app = ApplicationBuilder().token("TOKEN").build()
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text('Name')
async def name_add(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
name = update.message.text
print("Name:" ,name)
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, start_last))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, name_add))
async def start_last(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text('age')
age = update.message.text
print(age)
app.add_handler(CommandHandler("start", start))
app.run_polling()
您好我想拉取用户写的消息。 机器人示例:
用户-/开始
输入您的机器人名称
用户-迈克
机器人-输入您的年龄
用户- 18
机器人 - 姓名:迈克 年龄:18
它会像这样工作,我得到了名字,但它不是从函数中出来的。我可以得到名字,但不能得到年龄,因为名字不是从我得到的函数中出来的
给定的代码结构存在一个问题,即start_last函数无法访问用户在name_add函数中输入的数据,因为它们是不同的函数。
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
# Define a dictionary to store user data
user_data = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text('Name')
async def name_add(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
name = update.message.text
user_data["name"] = name
print("Name:", name)
await update.message.reply_text('Age')
async def start_last(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
None:
age = update.message.text
user_data["age"] = age
print(age)
# Access and display user data
name = user_data.get("name")
age = user_data.get("age")
await update.message.reply_text(f"Name: {name}\nAge: {age}")
app = ApplicationBuilder().token("YOUR_TOKEN").build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, name_add))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, start_last))
app.run_polling()
所做的修改:
存储用户数据(姓名和年龄),定义了一个字典,名为user_data。
通过 name_add 函数使用“name”键将用户名添加到 user_data 字典中。
用户的年龄使用start_last方法中的“age”键保存在user_data字典中。
从 user_data 字典中检索用户的姓名和年龄,并在创建响应消息时使用。
此方法显示两个函数均可访问的数据。