【问题标题】:NameError: name 'startCommand' is not defined - PYTHONNameError:未定义名称'startCommand' - PYTHON
【发布时间】:2021-07-22 11:57:06
【问题描述】:
from coinbase.wallet.client import Client
from telegram import ParseMode
from telegram.ext import CommandHandler, Defaults, Updater

COINBASE_KEY = 'xxxxxxxxxxxx'
COINBASE_SECRET = 'xxxxxxxxxxxx' 
TELEGRAM_TOKEN = 'xxxxxxxxxxxx'

coinbase_client = Client(COINBASE_KEY, COINBASE_SECRET)

#if __name__ == '__main__':
updater = Updater(token=TELEGRAM_TOKEN, defaults=Defaults(parse_mode=ParseMode.HTML))
dispatcher = updater.dispatcher
dispatcher.add_handler('start', startCommand) # Accessed via /start
dispatcher.add_handler('alert', priceAlert) # Accessed via /alert

updater.start_polling() # Start the bot

updater.idle() # Wait for the script to be stopped, this will stop the bot


def startCommand(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text='Hello there!')

def priceAlert(update, context):
    if len(context.args) > 2:
        crypto = context.args[0].upper()
        sign = context.args[1]
        price = context.args[2]

        context.job_queue.run_repeating(priceAlertCallback, interval=15, first=15, context=[crypto, sign, price, update.message.chat_id])

        response = f"⏳ I will send you a message when the price of {crypto} reaches £{price}, \n"
        response += f"the current price of {crypto} is £{coinbase_client.get_spot_price(currency_pair=crypto + '-GBP')['amount']}"
    else:
        response = '⚠️ Please provide a crypto code and a price value: \n<i>/price_alert {crypto code} {> / &lt;} {price}</i>'

    context.bot.send_message(chat_id=update.effective_chat.id, text=response)


def priceAlertCallback(context):
    crypto = context.job.context[0]
    sign = context.job.context[1]
    price = context.job.context[2]
    chat_id = context.job.context[3]

    send = False
    spot_price = coinbase_client.get_spot_price(currency_pair=crypto + '-GBP')['amount']

    if sign == '<':
        if float(price) >= float(spot_price):
            send = True
    else:
        if float(price) <= float(spot_price):
            send = True

    if send:
        response = f'???? {crypto} has surpassed £{price} and has just reached <b>£{spot_price}</b>!'

        context.job.schedule_removal()

        context.bot.send_message(chat_id=chat_id, text=response)

enter image description here

我得到上面代码的这个错误,我也已经尝试改变def的位置,但是它也显示错误,如何解决这个问题? 它是电报机器人的代码,并且一直显示NameError,我已经添加了python3和pip,但仍然没有解决

【问题讨论】:

  • 在定义函数之前不能引用函数名。将函数定义放在开头。
  • 我知道你说你尝试改变位置,但你一定没有把它放在正确的位置。再试一次。
  • 您是否尝试过将所有函数移到导入之后?
  • File "bot.py", line 59, in dispatcher.add_handler('start', startCommand) # Accessed via /start File "/home/ishaan/.local/lib/python3 .8/site-packages/telegram/ext/dispatcher.py", line 501, in add_handler raise TypeError(f'handler is not an instance of {Handler.__name__}') TypeError: handler is not an instance of Handler 它显示如果在导入后移动,则会出现此错误

标签: python bots telegram python-telegram-bot


【解决方案1】:

试试

dispatcher.add_handler('start', startCommand()) # Accessed via /start
dispatcher.add_handler('alert', priceAlert()) # Accessed via /alert

您还需要添加两个函数所需的两个参数。

dispatcher.add_handler('start', startCommand(update, context))
dispatcher.add_handler('alert', startCommand(update, context))

我不确定这两个函数会接收哪些数据,但我猜它是机器人返回的任何数据。

【讨论】:

  • add_handler 不是这样工作的。详情请见docs
【解决方案2】:

Python 从上到下读取文件。所以当你调用dispatcher.add_handler('start', startCommand) 时,函数startCommand 还不知道。移动零件

updater = Updater(token=TELEGRAM_TOKEN, defaults=Defaults(parse_mode=ParseMode.HTML))
dispatcher = updater.dispatcher
dispatcher.add_handler('start', startCommand) # Accessed via /start
dispatcher.add_handler('alert', priceAlert) # Accessed via /alert

updater.start_polling() # Start the bot

updater.idle() # Wait for the script to be stopped, this will stop the bot

在回调定义下方。

除此之外,add_handler 需要 Handler 作为参数,在您的情况下类似于 add_handler(CommandHanlder('start', startCommand)。请参阅PTB tutorialthe examples


免责声明:我是python-telegram-bot 库的当前维护者。

【讨论】:

    猜你喜欢
    • 2013-01-26
    • 1970-01-01
    • 2020-09-04
    • 2021-10-18
    • 2016-08-09
    • 2016-01-08
    • 1970-01-01
    相关资源
    最近更新 更多