【发布时间】:2020-09-03 09:02:00
【问题描述】:
我正在尝试将另一个类的装饰器应用于我的类中的方法... 这是我对这个 Telegram API 包装库的实现: https://github.com/eternnoir/pyTelegramBotAPI
但在我的示例中,我不想从脚本中使用它——而是像这样的类方法:
class Bot:
def __init__(self, key):
self.key = key
self.bot=telebot.TeleBot(key)
def start(self):
self.bot.polling()
# Handle '/start' and '/help'
@self.bot.message_handler(commands=['help', 'start'])
def send_welcome(self,message):
self.bot.reply_to(message, """\
Hi there, I am EchoBot. \
I am here to echo your kind words back to you. \
Just say anything nice and I'll say the exact same thing to you!\
""")
# Handle all other messages with content_type 'text' (content_types defaults to ['text'])
@self.bot.message_handler(func=lambda message: True)
def echo_message(message):
self.bot.reply_to(message, message.text)
所有self 都被突出显示......当然不能正常工作 - 如果有人能解释我做错了什么会很高兴?
尝试自定义的原始示例是:
import telebot
bot = telebot.TeleBot("TOKEN")
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.reply_to(message, "Howdy, how are you doing?")
@bot.message_handler(func=lambda message: True)
def echo_all(message):
bot.reply_to(message, message.text)
bot.polling()
【问题讨论】:
-
您不应该将密钥存储在类的变量中。只需传递并使用它。您是否尝试过在不使用 self 关键字的情况下使用它?
标签: python telegram telegram-bot python-decorators