我被我的代码卡住了,原因是它没有响应,因为我想要一个机器人,价格命令有一个冷却时间,在下一次有人使用价格命令时,它将不会响应30分钟,或提示人们等待,直到冷却时间结束,这样它将减少在telegram组的垃圾邮件,当许多人在同一时间做价格。
def price(update, context):
if chat_data.get('last_time'):
if datetime.now()-last_time <= my_threshold:
return
chat_data['last_time'] = datetime.now()
update.message.reply_text(
'Bitcoin PRICE TRACKER \n'
'🤑 Price: $ ' + usd + '\n'
'📈 Marketcap: $ ' + usdcap + '\n'
'💸 24 Hour Volume: $ ' + usdvol + '\n'
'💵 24 Hour Change: % ' + usdchange + '\n'
'⚙️ Last Updated at: ' + lastat +'\n'
)
updater = Updater('mytoken', use_context=True)
updater.dispatcher.add_handler(CommandHandler('price', price))
用django-rest风格的东西怎么样,比如一个装饰器?
import datetime
throttle_data = {
'minutes': 30,
'last_time': None
}
def throttle(func):
def wrapper(*args, **kwargs):
now = datetime.datetime.now()
delta = now - datetime.timedelta(minutes=throttle_data.get('minutes', 30))
last_time = throttle_data.get('last_time')
if not last_time:
last_time = delta
if last_time <= delta:
throttle_data['last_time'] = now
func(*args, **kwargs)
else:
return not_allowed(*args)
return wrapper
def not_allowed(update, context):
update.message.reply_text(text="You are not allowed.")
@throttle
def price(update, context):
update.message.reply_text(
'Bitcoin PRICE TRACKER \n'
'🤑 Price: $ ' + usd + '\n'
'📈 Marketcap: $ ' + usdcap + '\n'
'💸 24 Hour Volume: $ ' + usdvol + '\n'
'💵 24 Hour Change: % ' + usdchange + '\n'
'⚙️ Last Updated at: ' + lastat +'\n'
)
updater = Updater('mytoken', use_context=True)
updater.dispatcher.add_handler(CommandHandler('price', price))
当然,每次重启机器人时,节制器都会被重置.顺便说一句,这将垃圾邮件 "你不被允许",所以我你有很多用户节制,你改变了 not_allowed
移除回复的功能。