Error when using samp-client

Question: When using the samp-client library as such, no error occurs, however, information about the server is not transmitted. Everything is fine on your personal PC

## ================================ Раздел Импорта Библиотек =====================================

import importlib

importlib.invalidate_caches()
import asyncio
from vkbottle import Bot
from vkbottle import API
from background import keep_alive
from vkbottle.bot import Message
from samp_client.client import SampClient
import requests

## ================================ Раздел Констант =====================================

token = 'TOKEN'

bot = Bot(token=token)
api = API(token=token)

hourly_messages_enabled = True  # Флаг для определения, разрешена ли отправка сообщений

prefix = '/'  # Префикс для команд

## ================================ Раздел Функций и Команд =====================================

@bot.on.chat_message(text={f'{prefix}online_str'})
async def online_str(message: Message):
    try:
        with SampClient(address='185.169.134.3', port=7777) as client:
            first_server = str(client.get_server_info())
            first_server = list(first_server.split(', '))
            print(first_server)
            ip1 = '80.66.71.44:5125'
            online1 = int((first_server[1])[8:])
            gamemode1 = (first_server[4])[11:13]
            status1 = '🟢 Статус: online'
    except Exception as e:
        print(e)
        try:
            with SampClient(address='80.66.71.44', port=5125) as client:
                first_server = str(client.get_server_info())
                first_server = list(first_server.split(', '))
                print(first_server)
                ip1 = '80.66.71.44:5125'
                online1 = int((first_server[1])[8:])
                gamemode1 = (first_server[4])[11:13]
                status1 = '🟢 Статус: online'
        except Exception as e:
            online1 = 0
            ip1 = '80.66.71.44:5125'
            gamemode1 = 'X0'
            status1 = '🔴 Статус: offline'
            print(e)
    online = (online1)

    onlinestr = (f'Информация по Серверам SanTrope RP\n\n'
                 f'🟢 Общий онлайн – {online}/6000\n\n'
                 f'SanTrope RP #1\n'
                 f'{status1}\n'
                 f'👥 Онлайн: {online1}/1000\n'
                 f'IP Сервера: {ip1}\n'
                 f'⚙ Режим: {gamemode1}\n\n'

                 f'Если информация о Сервере не отображается, попробуйте ещё раз позже!')

    await message.answer(onlinestr)


@bot.on.chat_message()
async def handle_all_messages(message: Message):
    if message.text.startswith(prefix):
        await message.answer("🤖 Неизвестная команда. Для получения списка команд введите /команды или /commands.")
    else:
        print(f"Новое сообщение в беседе: {message.text}")  # Отправляем сообщение в консоль Python


## ================================ Раздел Начала Работы =====================================
keep_alive()  #запускаем flask-сервер в отдельном потоке. Подробнее ниже...
async def main():
    await bot.run_polling()


if __name__ == "__main__":
    asyncio.run(main())

Hi @KirillTarasov3 thanks for your post and welcome to the community.

Can you share some screenshots showing how it works on your PC so we can compare it with what happens in your Repl?

If you could also share a link to the Repl that would be appreciated. Please remember that any API keys should be hidden from other users using Secrets before you share links.

2 Likes

Hi, sorry for the long answer. Here is the console from a personal PC:

INFO:vkbottle:logging is used as the default logger, but we recommend using loguru. It may also become a required dependency in future releases.
DEBUG:asyncio:Using proactor: IocpProactor
INFO:vkbottle:Starting polling for <API token_generator=<<class 'vkbottle.api.token_generator.single.SingleTokenGenerator'>>...>
DEBUG:vkbottle:Getting polling server...
DEBUG:vkbottle:API request was validated
DEBUG:vkbottle:Request groups.getById with {} data returned {"response":[{"id":221075884,"name":"Helper BOT (Test) || ..:::Golden-Family:::..","screen_name":"club221075884","is_closed":0,"type":"group","photo_50":"https:\/\/vk.com\/images\/community_50.png","photo_100":"https:\/\/vk.com\/images\/community_100.png","photo_200":"https:\/\/vk.com\/images\/community_200.png"}]}
DEBUG:vkbottle:API response was validated
DEBUG:vkbottle:API request was validated
DEBUG:vkbottle:Request groups.getLongPollServer with {'group_id': 221075884} data returned {"response":{"key":"secret","server":"https:\/\/lp.vk.com\/whp\/221075884","ts":"341"}}
DEBUG:vkbottle:API response was validated
DEBUG:vkbottle:Starting listening to longpoll
DEBUG:vkbottle:Making long request to get event with longpoll...
DEBUG:vkbottle:New event was received: {'ts': '342', 'updates': [{'group_id': 221075884, 'type': 'message_new', 'event_id': '45bc50957077e45824b94fd9f3231c06f2b0811c', 'v': '5.131', 'object': {'message': {'date': 1689437908, 'from_id': 449642983, 'id': 0, 'out': 0, 'attachments': [], 'conversation_message_id': 624, 'fwd_messages': [], 'important': False, 'is_hidden': False, 'peer_id': 2000000001, 'random_id': 0, 'text': '/online_str'}, 'client_info': {'button_actions': ['text', 'vkpay', 'open_app', 'location', 'open_link', 'callback', 'intent_subscribe', 'intent_unsubscribe'], 'keyboard': True, 'inline_keyboard': True, 'carousel': True, 'lang_id': 0}}}]}
DEBUG:vkbottle:Making long request to get event with longpoll...
DEBUG:vkbottle:Routing update {'group_id': 221075884, 'type': 'message_new', 'event_id': '45bc50957077e45824b94fd9f3231c06f2b0811c', 'v': '5.131', 'object': {'message': {'date': 1689437908, 'from_id': 449642983, 'id': 0, 'out': 0, 'attachments': [], 'conversation_message_id': 624, 'fwd_messages': [], 'important': False, 'is_hidden': False, 'peer_id': 2000000001, 'random_id': 0, 'text': '/online_str'}, 'client_info': {'button_actions': ['text', 'vkpay', 'open_app', 'location', 'open_link', 'callback', 'intent_subscribe', 'intent_unsubscribe'], 'keyboard': True, 'inline_keyboard': True, 'carousel': True, 'lang_id': 0}}}
DEBUG:vkbottle:Handling event (message_new) with message view
DEBUG:vkbottle:Casting state for peer_id 2000000001
DEBUG:vkbottle:Handler <FromFuncHandler online_str blocking=True rules=(<PeerRule>, <VBMLRule>)> returned {}
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): 80.66.71.44:80
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): 80.66.71.44:80
('Connection aborted.', ConnectionResetError(10054, 'Удаленный хост принудительно разорвал существующее подключение', None, 10054, None))
DEBUG:urllib3.connectionpool:http://80.66.71.44:80 "GET / HTTP/1.1" 404 None
<Response [404]>
DEBUG:vkbottle:API request was validated
['ServerInfo(password=False', 'players=57', 'max_players=1000', "hostname='SanTrope RP #1'", "gamemode=' X3'", "language='RU | ANDROID')"]
DEBUG:vkbottle:Request messages.send with {'random_id': 0, 'peer_ids': '2000000001', 'message': 'Информация по Серверам SanTrope RP\n\n🟢 Общий онлайн – 57/1000\n\nSanTrope RP #1\n🟢 Статус: online\n👥 Онлайн: 57/1000\nIP Сервера: 80.66.71.44:5125\n⚙ Режим: X3\n\nЕсли информация о Сервере не отображается, попробуйте ещё раз позже!'} data returned {"response":[{"peer_id":2000000001,"message_id":0,"conversation_message_id":625}]}
DEBUG:vkbottle:API response was validated

Console from my Repl:

INFO:vkbottle:logging is used as the default logger, but we recommend using loguru. It may also become a required dependency in future releases.
DEBUG:asyncio:Using selector: EpollSelector
 * Serving Flask app ''
INFO:vkbottle:Starting polling for <API token_generator=<<class 'vkbottle.api.token_generator.single.SingleTokenGenerator'>>...>
DEBUG:vkbottle:Getting polling server...
DEBUG:vkbottle:API request was validated
 * Debug mode: off
INFO:werkzeug:WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:8080
 * Running on http://172.31.196.23:8080
INFO:werkzeug:Press CTRL+C to quit
INFO:werkzeug:172.31.196.1 - - [15/Jul/2023 16:41:33] "OPTIONS * HTTP/1.1" 404 -
INFO:werkzeug:172.31.196.1 - - [15/Jul/2023 16:41:33] "GET / HTTP/1.1" 200 -
DEBUG:vkbottle:Request groups.getById with {} data returned {"response":[{"id":221075884,"name":"Helper BOT (Test) || ..:::Golden-Family:::..","screen_name":"club221075884","is_closed":0,"type":"group","photo_50":"https:\/\/vk.com\/images\/community_50.png","photo_100":"https:\/\/vk.com\/images\/community_100.png","photo_200":"https:\/\/vk.com\/images\/community_200.png"}]}
DEBUG:vkbottle:API response was validated
DEBUG:vkbottle:API request was validated
DEBUG:vkbottle:Request groups.getLongPollServer with {'group_id': 221075884} data returned {"response":{"key":"secret","server":"https:\/\/lp.vk.com\/whp\/221075884","ts":"342"}}
DEBUG:vkbottle:API response was validated
DEBUG:vkbottle:Starting listening to longpoll
DEBUG:vkbottle:Making long request to get event with longpoll...
INFO:werkzeug:172.31.196.1 - - [15/Jul/2023 16:41:34] "GET / HTTP/1.1" 200 -
DEBUG:vkbottle:New event was received: {'ts': '343', 'updates': [{'group_id': 221075884, 'type': 'message_new', 'event_id': '414386debaf2a485ff78fb20eb2d0923b1793ca5', 'v': '5.131', 'object': {'message': {'date': 1689439305, 'from_id': 449642983, 'id': 0, 'out': 0, 'attachments': [], 'conversation_message_id': 626, 'fwd_messages': [], 'important': False, 'is_hidden': False, 'peer_id': 2000000001, 'random_id': 0, 'text': '/online_str'}, 'client_info': {'button_actions': ['text', 'vkpay', 'open_app', 'location', 'open_link', 'callback', 'intent_subscribe', 'intent_unsubscribe'], 'keyboard': True, 'inline_keyboard': True, 'carousel': True, 'lang_id': 0}}}]}
DEBUG:vkbottle:Making long request to get event with longpoll...
DEBUG:vkbottle:Routing update {'group_id': 221075884, 'type': 'message_new', 'event_id': '414386debaf2a485ff78fb20eb2d0923b1793ca5', 'v': '5.131', 'object': {'message': {'date': 1689439305, 'from_id': 449642983, 'id': 0, 'out': 0, 'attachments': [], 'conversation_message_id': 626, 'fwd_messages': [], 'important': False, 'is_hidden': False, 'peer_id': 2000000001, 'random_id': 0, 'text': '/online_str'}, 'client_info': {'button_actions': ['text', 'vkpay', 'open_app', 'location', 'open_link', 'callback', 'intent_subscribe', 'intent_unsubscribe'], 'keyboard': True, 'inline_keyboard': True, 'carousel': True, 'lang_id': 0}}}
DEBUG:vkbottle:Handling event (message_new) with message view
DEBUG:vkbottle:Casting state for peer_id 2000000001
DEBUG:vkbottle:Handler <FromFuncHandler online_str blocking=True rules=(<PeerRule>, <VBMLRule>)> returned {}
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): 80.66.71.44:80
('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): 80.66.71.44:80
DEBUG:urllib3.connectionpool:http://80.66.71.44:80 "GET / HTTP/1.1" 404 None
<Response [404]>
'NoneType' object is not subscriptable
'NoneType' object is not subscriptable
DEBUG:vkbottle:API request was validated
DEBUG:vkbottle:Request messages.send with {'random_id': 0, 'peer_ids': '2000000001', 'message': 'Информация по Серверам SanTrope RP\n\n🟢 Общий онлайн – 0/1000\n\nSanTrope RP #1\n🔴 Статус: offline\n👥 Онлайн: 0/1000\nIP Сервера: 80.66.71.44:5125\n⚙ Режим: X0\n\nЕсли информация о Сервере не отображается, попробуйте ещё раз позже!'} data returned {"response":[{"peer_id":2000000001,"message_id":0,"conversation_message_id":627}]}
DEBUG:vkbottle:API response was validated
DEBUG:vkbottle:New event was received: {'ts': '343', 'updates': []}
DEBUG:vkbottle:Making long request to get event with longpoll...

Here is the link to my Repl:
Test Helper BOT - Replit

The first screenshot is from my PC, the second is from Replit
Снимок экрана 2023-07-15 204012
Снимок экрана 2023-07-15 204156

Please help me with this problem, because I do not know how to solve it and do not understand the reasons for its occurrence at all

Hi @KirillTarasov3 thanks for posting the error messages. As far as I can see you get the same error on both your PC and the Repl.

It relates to

DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): 80.66.71.44:80
DEBUG:urllib3.connectionpool:http://80.66.71.44:80 "GET / HTTP/1.1" 404 None
<Response [404]>
'NoneType' object is not subscriptable
'NoneType' object is not subscriptable

It looks like your code is trying to connect to the IP address 80.66.71.44 on port 80 but either the website isn’t running or it cannot connect for some reason.

Are you able to ping the above IP address and get a successful connection?