“AttributeError:‘NoneType’对象没有属性‘from_user’”消息从说明更改为欢迎

问题描述 投票:0回答:1

我可能需要一些帮助。我正在尝试编写一个电报机器人代码。当用户开始通过 /start 与机器人交互时,他会收到一条带有内联键盘按钮的欢迎消息。第一个按钮还没有功能。但第二个按钮将欢迎消息更改为还具有内联键盘按钮(“BACK”)的说明消息。当用户按下此按钮时,指示消息应变回欢迎消息。但这并没有成功,所以我决定不使用“返回开始”功能,只给他回调“你选择返回”。但每次我尝试让它运行时,我都会收到相同的 attributeError。

这是迄今为止我的代码:

from telegram import InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler

# Ihr Bot-Token
TOKEN = "Bot_Token"

# Ein globaler Wert, um den Zustand des Bots zu verfolgen
START, INSTRUCTIONS = range(2)

def start(update, context):
    user = update.message.from_user
    
    # Text der Willkommensnachricht
    welcome_message = """⚜️ **PayEscrowBOT** ⚜️ v.1.1
#1 Automated Telegram Escrow Service

Welcome to **PayEscrowBOT**™️. This bot provides a safe escrow service for your business on Telegram. Never get ripped again, The bot secures your funds throughout the deal. If you have any issues, kindly type /contact and an arbitrator will join the group chat within 24 hours.

🎟 **ESCROW FEE:**
5% if over $100
5$ if under $100

☑️ **DEALS DONE:** 1200
🧑‍⚖️ **DISPUTES HANDLED:** 280

💬 **Declare the seller or buyer with** /seller or /buyer [BTC/LTC ADDRESS] (**Your BTC/LTC address =** [BTC/LTC ADDRESS])

💡 Type /menu **to summon a menu with all bot's features**"""

    # Erstes Inline-Keyboard
    keyboard1 = [[InlineKeyboardButton("❓ WHAT IS ESCROW", callback_data="what_is_escrow"),
                 InlineKeyboardButton("ℹ️ INSTRUCTIONS", callback_data="instructions")]]
    
    # Inline-Keyboard-Markup für das erste Keyboard
    reply_markup1 = InlineKeyboardMarkup(keyboard1)

    # Senden der Willkommensnachricht mit dem Inline-Keyboard
    update.message.reply_markdown(welcome_message, reply_markup=reply_markup1)
    
    # Setzen des Bots in den START-Zustand
    context.user_data["state"] = START

def instructions(update, context):
    query = update.callback_query
    query.answer()
    
    # Nachricht mit den Anweisungen
    instructions_message = """💬 INSTRUCTIONS

1️⃣ Add the bot to a new Group Chat with buyer + seller

2️⃣ Declare the seller with /seller [BTC/LTC ADDRESS]
        Replace [BTC/LTC ADDRESS] with receive wallet

3️⃣ Declare the buyer with /buyer [BTC/LTC ADDRESS]
        Replace [BTC/LTC ADDRESS] with refund wallet

4️⃣ Generate a wallet with /generate

5️⃣ Buyer sends agreed amount to generated BTC wallet

6️⃣ Check balance with /balance

7️⃣ Seller releases product / service to buyer when balance is confirmed

8️⃣ When buyer is satisfied, release payment with /release
    The seller can also /refund the buyer.

9️⃣ If any issues, contact arbitrator with /contact

❗️ For video example, type /video

☎️ If you need help, type /contact [INVITE LINK TO GROUP]
Replace [INVITE LINK TO GROUP] with the invite link of the group chat."""

    # Inline-Keyboard für den Zurück-Button
    back_keyboard = [[InlineKeyboardButton("⬅️ BACK", callback_data="back")]]
    back_markup = InlineKeyboardMarkup(back_keyboard)

    # Senden der Anweisungsnachricht mit dem Zurück-Button
    query.edit_message_text(text=instructions_message, reply_markup=back_markup)
    
    # Setzen des Bots in den INSTRUCTIONS-Zustand
    context.user_data["state"] = INSTRUCTIONS

def back(update, context):
    query = update.callback_query
    query.answer()
    
    if context.user_data["state"] == INSTRUCTIONS:
        # Zurück zur Willkommensnachricht mit den Optionen
        start(update, context)

def button(update, context):
    query = update.callback_query
    query.answer()

    if query.data == "instructions":
        instructions(update, context)
    elif query.data == "back":
        start(update, context)
    else:
        query.edit_message_text(text=f"Du hast {query.data} ausgewählt")

def main():
    updater = Updater(token=TOKEN, use_context=True)
    dp = updater.dispatcher

    # Definieren Sie den /start-Handler
    dp.add_handler(CommandHandler("start", start))

    # Definieren Sie den Callback-Handler für die Inline-Keyboards
    dp.add_handler(CallbackQueryHandler(button))

    updater.start_polling()
    updater.idle()

if __name__ == "__main__":
    main()

这是我收到的错误消息:

No error handlers are registered, logging exception.
Traceback (most recent call last):
  File "/Users/philippalbrecht/.pyenv/versions/3.11.1/lib/python3.11/site-packages/telegram/ext/dispatcher.py", line 340, in process_update
    handler.handle_update(update, self, check, context)
  File "/Users/philippalbrecht/.pyenv/versions/3.11.1/lib/python3.11/site-packages/telegram/ext/handler.py", line 119, in handle_update
    return self.callback(update, context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/philippalbrecht/Desktop/Telegram/Telegram_escrow", line 101, in button
    back(update, context)
  File "/Users/philippalbrecht/Desktop/Telegram/Telegram_escrow", line 92, in back
    start(update, context)
  File "/Users/philippalbrecht/Desktop/Telegram/Telegram_escrow", line 11, in start
    user = update.message.from_user
           ^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'from_user'

有人可以帮忙修复这个错误吗?

谢谢!

首先,我希望机器人从指令消息改回欢迎消息,以便用户可以再次从前两个内联键盘按钮中进行选择。因为这不起作用,我只想将说明简单更改为“你选择了回来”。但我总是收到这个错误。

telegram-bot python-telegram-bot
1个回答
0
投票

错误消息仅表明

update.message is None
。回溯还表明错误发生在函数
button
中,该函数在内部调用了函数
start
。由于
button
已注册为
CallbackQueryHandler
的回调函数,因此它只会看到
update.message
None
的更新,而不是
update.callback_query
为非
None
的更新。

您可能想使用

update.effective_user
来代替。


请注意,您使用的是 PTB v13.x 或更早版本,该版本不再受支持。我鼓励您将代码升级到 v20.x。


免责声明:我目前是

python-telegram-bot
的维护者。

© www.soinside.com 2019 - 2024. All rights reserved.