D
D
Denis Kulikov2021-12-04 16:11:28
Python
Denis Kulikov, 2021-12-04 16:11:28

Why does it throw an out-of-bounds error when using the first element of a list?

I am writing a VK Bot for playing dice.
The code:

import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
from vk_api.utils import get_random_id
import bs4 as bs4
import requests

class VkBot:
  def __init__(self, user_id):
    print('Создан объект бота!')
    self._USER_ID = user_id
    self._USERNAME = self._get_user_name_from_vk_id(user_id)
    self._COMMANDS = ['Бот', 'Да', 'да', 'Бросить кости', 'бот', 'бросить кости']
  #ID пользователя
  def _get_user_name_from_vk_id(self, user_id):
    request = requests.get("https://vk.com/id" + str(user_id))
    bs = bs4.BeautifulSoup(request.text, "html.parser")
    
    user_name = self._clean_all_tag_from_str(bs.findAll("title")[0])
    
    return user_name.split()[0]
  #Очистка тэгов
  @staticmethod
  def _clean_all_tag_from_str(string_line):
    """
    Очистка строки stringLine от тэгов и их содержимых
    :param string_line: Очищаемая строка
    :return: очищенная строка
    """
    result = ""
    not_skip = True
    for i in list(string_line):
      if not not_skip:
        if i == "<":
          not_skip = False
        else:
          result += i
      else:
        if i == ">":
          not_skip = True
    return result
  #Главная функция бота(игра в кости)
  def dice():
    pass
  #Вывод ответа на команду
  def new_message(self, message):
    if message.upper() == self._COMMANDS[0]:
      return "Присутствую!"
    elif message.upper() == self._COMMANDS[1] or message.upper() == self._COMMANDS[2]:
      return "Нецензурное слово!"
    elif message.upper() == self._COMMANDS[3]:
      return dice()
    else:
      return "Не понимаю о чем ты..."

gives an error on the line on the site according to the guide which I am doing, this bot is written exactly exactly, only it works for them, but I don’t. Please tell me how to solve the problem. PS here is the site: https://habr.com/ru/post/427691/
return user_name.split()[0]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2021-12-04
@Artin24

The article is shameful, I do not advise you to focus on it. The error occurs because of an empty string as a result of the work.
Replace your name search with this one

user_name = bs.find('title').text.split('|')[0].strip()

And I advise you to find any other material, at least the same doc on VK api. Because it makes sense to parse the name through bs4 and requests if api is connected?

V
Vindicar, 2021-12-04
@Vindicar

Because user_name contains an empty string. But why is it so, this is the second question.
Although _clean_all_tag_from_str() is still some code... can titles even have nested tags?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question