Answer the question
In order to leave comments, you need to log in
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 "Не понимаю о чем ты..."
return user_name.split()[0]
Answer the question
In order to leave comments, you need to log in
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()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question