【发布时间】: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} {> / <} {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)
我得到上面代码的这个错误,我也已经尝试改变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