A
A
arhipT9992022-04-06 17:46:50
Mobile development
arhipT999, 2022-04-06 17:46:50

TypeError: unhashable type: 'list'?

Please help me fix the error.
The code:

import telebot
import requests
from bs4 import BeautifulSoup as bs

bot = telebot.TeleBot('Token')
new = 'Первым замом Жириновского в центральном аппарате ЛДПР назначен депутат Алексей Диденко'
n = []
num = 0
new = dict()
d = {}
t = 0
y = 0
kol_vo = 0

def zapoln(message):
    global new
    global y
    global d
    global n
    if y == 1:
        d[message.chat.id] = n
    if n == []:
        bot.send_message(message.chat.id, 'Чел... ты сломал бота :( поэтому установлены стандартные настройки!')
        n = ['rian_ru', 'breakingmash']
        new = {key: None for key in n}
        rass(message)
    else:
        print(f'это{n}')
    new = {key: None for key in n}
    rass(message)

def rass(message):
        while True:
            with open('input.txt','w') as inp:
                for key,val in d.items():
                    inp.write('{}:{}\n'.format(key,val))
            global new
            global n
            global num
            global t
            global kol_vo
            kol_vo += 1
            if kol_vo == len(n):
                kol_vo = 1
            p = [i for i in n]
            url = f'https://t.me/s/{p}'
            response = requests.get(url)
            soup = bs(response.text, 'lxml')
            teg = soup.find_all('div', class_='tgme_widget_message_wrap')
            div = soup.find_all('div', class_='tgme_widget_message')
            next = soup.find_all('div', class_='tgme_widget_message_bubble')
            text_ = soup.find_all('div', class_='tgme_widget_message_text')
            s = []
            out = ''
            for i in text_:
                s.append(i)
            try:
                out = str(s[-1])
            except IndexError:
                bot.send_message(message.chat.id, 'Вы неправильно ввели какал!')
                num = 0
                t = 0
                n = []
                kanal(message)
            out = out[65:]
            out = out[:-6]
            for _ in range(out.count('<')):
                a = out.find('<')
                b = out.find('>')
                s = out[a:b+1]
                out = out.replace(s, '')
            if out == new[p]:
                pass
            else:
                new[p] = out
                bot.send_message(message.chat.id, f'{out}\n-----\nНовость от @{p}')
                print(out)

def proverka(message):
    global n
    global t
    global num
    if message.text.lower() == 'стоп' and n != []:
        num = 1
        print(n)
        zapoln(message)
    else:
        if t != 1:
            n.append(message.text)
            bot.send_message(message.chat.id, 'Напиши комманду: "/next"')

def kanal(message):
    if t != 1:
        msg = bot.send_message(message.chat.id, 'Введите название канала БЕЗ @ например: rian_ru. Если больше не хотите вводить названия напишите "Стоп"')
        bot.register_next_step_handler(msg, proverka)
    else:
        zapoln(message)

@bot.message_handler(commands='next')
def pr(message):
    global n
    if n == []:
        kanal(message)
    else:
        rass(message)

@bot.message_handler(commands='start')
def nav(message):
    global t
    global y
    global n
    with open('input.txt', 'r') as inp:
        for i in inp.readlines():
            key,val = i.strip().split(':')
            d[key] = val
            if str(message.chat.id) in d:
                n = d[str(message.chat.id)]
                print(f'n - заполняется {n}')
                t = 1
            else:
                y = 1
                d[str(message.chat.id)] = n
    pr(message)

bot.polling()

Console:
n - заполняется ['rian_ru']
Traceback (most recent call last):
  File "c:\Users\Student\Documents\GitHub\arhipT999.github.io\tbot.py", line 125, in <module>
    bot.polling()
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\__init__.py", line 664, in polling
    self.__threaded_polling(non_stop, interval, timeout, long_polling_timeout, allowed_updates)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\__init__.py", line 726, in __threaded_polling
    raise e
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\__init__.py", line 686, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\util.py", line 136, in raise_exceptions
    raise self.exception_info
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\telebot\util.py", line 88, in run      
    task(*args, **kwargs)
  File "c:\Users\Student\Documents\GitHub\arhipT999.github.io\tbot.py", line 123, in nav
    pr(message)
  File "c:\Users\Student\Documents\GitHub\arhipT999.github.io\tbot.py", line 105, in pr
    rass(message)
  File "c:\Users\Student\Documents\GitHub\arhipT999.github.io\tbot.py", line 72, in rass
    if out == new[p]:
TypeError: unhashable type: 'list'

input.txt file:
-1001682669467:['breakingmash']
5131695189:['rian_ru']

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Igor, 2016-09-16
@Igoorr

Privacy policy is extremely important not only for the application but also for sites. So the user or buyer feels replaced and such a company will be more trusted. The user will treat this with understanding if you submit information in the form that is necessary for the security of your data.

V
Vindicar, 2022-04-06
@Vindicar

Well, you're pretty straight forward: Lists are not a hashable type (because they are mutable). Therefore, they cannot be used as keys in a dictionary or elements of sets.
And you:

new = dict()
p = [i for i in n]

and a call to new[p].

Y
YelKa, 2022-04-06
@YelKa

The list cannot be a dictionary key because it is mutable.
It is possible to use tuples

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question