pythontelegram-botpy-telegram-bot-api

The bot crashes when people write to it


The bot crashes when it receives any message that is not related to pressing a button, I tried to fix it through ChatGPT by adding a function that when the bot receives a message, it responds "use the menu below", but this did not help with crashes.

I need the bot to respond only to buttons and when it is written an arbitrary message it responds so that the user uses the menu

Here is the code:

import telebot
from telebot import types
import requests
import config

bot = telebot.TeleBot(config.token)

# Define the API key
api_key = 'API_KEY'  # Replace 'your_api_key' with your actual API key

@bot.message_handler(commands=['start'])
def start(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    btn1 = types.KeyboardButton("👋 Say hello")
    btn2 = types.KeyboardButton("❓ Ask a question")
    markup.add(btn1, btn2)
    bot.send_message(message.chat.id, text="Hello", reply_markup=markup)

@bot.message_handler(content_types=['text'])
def func(message):
    if message.text == "👋 Say hello":
        bot.send_message(message.chat.id, text="Hi, thanks for reading the article!)")
    elif message.text == "❓ Ask a question":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        btn1 = types.KeyboardButton("What's my name?")
        btn2 = types.KeyboardButton("What can I do?")
        back = types.KeyboardButton("Back to main menu")
        markup.add(btn1, btn2, back)
        bot.send_message(message.chat.id, text="Ask me a question", reply_markup=markup)
    elif message.text == "What's my name?":
        bot.send_message(message.chat.id, "I don't have a name.")
    elif message.text == "What can I do?":
        bot.send_message(message.chat.id, text="Say hello to the readers")
    elif message.text == "Back to main menu":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("👋 Say hello")
        button2 = types.KeyboardButton("❓ Ask a question")
        markup.add(button1, button2)
        bot.send_message(message.chat.id, text="You have returned to the main menu", reply_markup=markup)
    else:
        # Handle messages that don't relate to pressing the buttons
        bot.send_message(message.chat.id, text="Use the menu buttons")

        # Example of making an API request with the API key
        api_url = 'https://api.example.com'  # Replace with the actual API endpoint
        headers = {'Authorization': 'Bearer ' + api_key}
        response = requests.get(api_url, headers=headers)

        if response.status_code == 200:
            # Process the API response
            data = response.json()
            bot.send_message(message.chat.id, text=f"API Response: {data}")
        else:
            bot.send_message(message.chat.id, text="Error accessing the API")

bot.polling(none_stop=True)

I tried to fix it through ChatGPT by adding a function that when the bot receives a message, it responds "use the menu below", but this did not help with crashes.

errors:

    Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\urllib3\connection.py", line 203, in _new_conn
    sock = connection.create_connection(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\urllib3\util\connection.py", line 60, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\socket.py", line 963, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
socket.gaierror: [Errno 11001] getaddrinfo failed

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\urllib3\connectionpool.py", line 790, in urlopen
    response = self._make_request(
               ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\urllib3\connectionpool.py", line 491, in _make_request
    raise new_e
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\urllib3\connectionpool.py", line 467, in _make_request
    self._validate_conn(conn)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\urllib3\connectionpool.py", line 1092, in _validate_conn
    conn.connect()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\urllib3\connection.py", line 611, in connect
    self.sock = sock = self._new_conn()
                       ^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\urllib3\connection.py", line 210, in _new_conn
    raise NameResolutionError(self.host, self, e) from e
urllib3.exceptions.NameResolutionError: <urllib3.connection.HTTPSConnection object at 0x00000216A3C7D7C0>: Failed to resolve 'api.example.com' ([Errno 11001] getaddrinfo failed)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\requests\adapters.py", line 486, in send
    resp = conn.urlopen(
           ^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\urllib3\connectionpool.py", line 844, in urlopen
    retries = retries.increment(
              ^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\urllib3\util\retry.py", line 515, in increment
    raise MaxRetryError(_pool, url, reason) from reason  # type: ignore[arg-type]
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded with url: / (Caused by NameResolutionError("<urllib3.connection.HTTPSConnection object at 0x00000216A3C7D7C0>: Failed to resolve 'api.example.com' ([Errno 11001] getaddrinfo failed)"))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\Botv2\botv2.py", line 56, in <module>
    bot.polling(none_stop=True)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\telebot\__init__.py", line 1043, in polling
    self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\telebot\__init__.py", line 1118, in __threaded_polling
    raise e
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\telebot\__init__.py", line 1074, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\telebot\util.py", line 147, in raise_exceptions
    raise self.exception_info
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\telebot\util.py", line 90, in run
    task(*args, **kwargs)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\telebot\__init__.py", line 6801, in _run_middlewares_and_handler
    result = handler['function'](message)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\Desktop\Botv2\botv2.py", line 47, in func
    response = requests.get(api_url, headers=headers)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\requests\api.py", line 73, in get
    return request("get", url, params=params, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\requests\api.py", line 59, in request
    return session.request(method=method, url=url, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\requests\sessions.py", line 589, in request
    resp = self.send(prep, **send_kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\requests\sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\requests\adapters.py", line 519, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded with url: / (Caused by NameResolutionError("<urllib3.connection.HTTPSConnection object at 0x00000216A3C7D7C0>: Failed to resolve 'api.example.com' ([Errno 11001] getaddrinfo failed)"))


Solution

  • When I run your code and send a simple message to the bot, the following error is shown:

    requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded with url: / (Caused by NameResolutionError("<urllib3.connection.HTTPSConnection object at 0x10d3cc5d0>: Failed to resolve 'api.example.com' ([Errno 8] nodename nor servname provided, or not known)"))
    

    The else case of the content_types=['text'] triggers when you send such a simple message.

    The error throws because the request to example.com fails. Seem like you didn't include any error checking on that request.

    Consider reading/implementing the following:
    Correct way to try/except using Python requests module?