eternnoir / pyTelegramBotAPI

Python Telegram bot api.
GNU General Public License v2.0
8.11k stars 2.03k forks source link

telebot within class #740

Closed mattou78400 closed 4 years ago

mattou78400 commented 4 years ago

Please answer these questions before submitting your issue. Thanks!

  1. What version of pyTelegramBotAPI are you using? latest
  2. What OS are you using? windows 10
  3. What version of python are you using? 3.7

Hi,

I'm trying to run telebot from within a class, though the decorators don't seem to work from within. I have:

def __init__(self, message):

        self.bot = telebot.TeleBot(token='XXXXXXXX')

@bot.message_handler(commands=['help', 'start'])
    def start(self):
          pass

But if I put "@self.bot" it doesn't work either.

Does anyone have a solution? thanks!

Badiboy commented 4 years ago
    def __init__(self, message):
        self.bot = telebot.TeleBot(token='XXXXXXXX')

        # Handle /start command
        @self.bot.message_handler(commands=["start"])
        def _process_command_start(message):
            self.process_command_start(message)

    def process_command_start(self, message)
        ...
GussSoares commented 10 months ago

Me too looked any soluction for this problem. Try this:


class TestBot:

    def __init__(self) -> None:
        self.bot: telebot.TeleBot = telebot.TeleBot(os.getenv('BOT_TOKEN'))
        self.init_commands()  # this method initialize my commands

    def start(self):
        self.bot.infinity_polling()

    def init_commands(self):
        """Initialize methods to represent bot commands"""
        self.help = self.bot.message_handler(commands=['help'])(self.help_command)
        self.test = self.bot.message_handler(commands=['test'])(self.test_command)

    # Commands bellow
    def help_command(self, message: types.Message):
        self.bot.send_message(chat_id=message.chat.id, text="Help!")

    def test_command(self, message: types.Message):
        self.bot.send_message(chat_id=message.chat.id, text=message.text)

TestBot().start()

the method init_commands run some instructions:

self.help = self.bot.message_handler(commands=['help'])(self.help_command)

It will create a method help() decorated by self.bot.message_handler and passing self.help_command reference that is a real action for help command.

You can use this approach for your commands

tar-pal commented 6 months ago

Hello, Why when I try to run your code - I have such errors: AttributeError: module 'types' has no attribute 'Message'