0

I'm working on a simple dictionary accessible through a telegram bot. This is my code in Python, what am I wrong?

   #!/usr/bin/python3
import telebot
API_TOKEN = 'MY TELEGRAM TOKEN'

bot = telebot.TeleBot(API_TOKEN)


Dizio={'cat': 'blue', 'dog': 'red', 'fly': 'black'}

# Handle all other messages with content_type 'text' (content_types defaults to ['text'])
    @bot.message_handler(func=lambda message: True)
    def echo_message(message):
        if message.text.lower() in Dizio.keys():
            res = Dizio.get('translate', {}).get('=')
            bot.send_message(message.chat.id, message.text(res))

    else:
        bot.send_message(message.chat.id, 'not found')

bot.infinity_polling()
RF1991
  • 2,037
  • 4
  • 8
  • 17
  • Can you explain the problem you are encountering? Do you get an error message? Does the bot work at all? – Hoxha Alban Mar 20 '22 at 14:27
  • If I write a key in the bot that is not in the dictionary, I get the message (still in the bot) "not found". If, on the other hand, I write a key present in the dictionary it does not give me the respective value giving me a list of errors including "TypeError: 'str' object is not callable" in the Python console while nothing in the bot – Mauro Sumino Mar 20 '22 at 14:36
  • Why there are two `get` in the line `res = Dizio.get('translate', {}).get('=')`? Why you are calling `message.text(res)`? – Hoxha Alban Mar 20 '22 at 14:40
  • it was an attempt. How could I solve? – Mauro Sumino Mar 20 '22 at 14:43

1 Answers1

0

There are a couple of problems inside the echo_message function:

  1. You aren't using correctly the dict.get method;
  2. you are calling message.text, this is a string, and you can't call strings;

Here's how i would resolve this problem, we can use the fact that dict.get allows us to provide a default value if the key is missing:

def echo_message(message):
    res = Dizio.get(message.text.lower(), "not found")
    bot.send_message(message.chat.id, res)
Hoxha Alban
  • 1,042
  • 1
  • 8
  • 12