skip to Main Content
@BOT.message_handler(commands=['drink'])
def drink(message):
    try:
        BOT.send_message(message.chat.id, f'I added {message.text.split(" ", 2)[1]} to your daily intake for today, {fecha_excel}!')

    except IndexError:
        BOT.send_message(message.chat.id, 'IndexError')

I basically want to create a function to shorten the "BOT.send_message(message.chat.id," part, since it will always be the same (at least for this project)

I tried creating this function inside the (handler? method? the @ thingy):

def send(message): BOT.send_message(message.chat.id, message)

And then in the drink() function, change it to:

@BOT.message_handler(commands=['drink'])
def drink(message):
    try:
        send(f'I added {message.text.split(" ", 2)[1]} to your daily intake for today, {fecha_excel}!')

    except IndexError:
        send('IndexError')

That doesn’t work because it doesn’t need a string but a "chat" object (if I understood correctly the error message), but is there any way to make it work?
This project should be fairly simple and short, so I won’t lose too much time typing "BOT.send_message(message.chat.id,", but in the future it might save me some time 🙂

2

Answers


  1. You can modify the helper function to take two arguments, chat_id and text :

    def send(chat_id, text):
        BOT.send_message(chat_id, text)
    

    Then in the drink function, change it to:

    @BOT.message_handler(commands=['drink'])
    def drink(message):
        try:
            send(message.chat.id, f'I added {message.text.split(" ", 2)[1]} to your daily intake for today, {fecha_excel}!')
    
        except IndexError:
            send(message.chat.id, 'IndexError')
    

    Now use the helper function send to send messages to the chat with a given chat id and text.

    Login or Signup to reply.
  2. You can’t avoid using message or message.chat.id completely. The best (shortest) you can do is:

    def respond(message, text):
       BOT.send_message(message.chat.id, text)
    
    @BOT.message_handler(commands=['drink'])
    def drink(message):
        try:
            respond(message, f'I added {message.text.split(" ", 2)[1]} to your daily intake for today, {fecha_excel}!')
        except IndexError:
            respond(message, 'IndexError')
    

    Although, doesn’t Message have .reply_text(text)?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search