@dyrtage6

Выходит ошибка при создание телеграм бота на питоне, как ее исправить?

Делаю телеграм бота. Хочу добавить функцию с Википедией, чтобы по быстрому находить информацию. Выходит вот такая ошибка -
2020-06-21 12:41:03,603 (util.py:68 WorkerThread1) ERROR - TeleBot: "AttributeError occurred, args=("'str' object has no attribute 'chat'",)
Traceback (most recent call last):
File "C:\Users\nikit\AppData\Local\Programs\Python\Python38-32\lib\site-packages\telebot\util.py", line 62, in run
task(*args, **kwargs)
File "tbot.py", line 72, in task
bot.send_message(message.chat.id, message)
AttributeError: 'str' object has no attribute 'chat'

А вот сам код -
import telebot
import random
from telebot import types
from covid import Covid
import wikipedia
 
bot = telebot.TeleBot('Тут токен')

play = ["Бумага", "Ножницы", "Камень"]
covid = Covid()
wikipedia.set_lang("RU")

@bot.message_handler(commands=['start'])
def welcome(message):
	sti = open('static/welcome.tgs', 'rb')
	bot.send_sticker(message.chat.id, sti)
 
	# keyboard
	markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
	item1 = types.KeyboardButton("Рандомное число")
	item2 = types.KeyboardButton("Как дела?")
	item3 = types.KeyboardButton("Камень, ножницы, бумага")
	item4 = types.KeyboardButton("Данные об Коронавирусе")
	item5 = types.KeyboardButton("Википедия")
 
	markup.add(item1, item2, item3, item4, item5)
 
	bot.send_message(message.chat.id, "Добро пожаловать, {0.first_name}!\nЯ - <b>{1.first_name}</b>, бот созданный чтобы быть подопытным кроликом.".format(message.from_user, bot.get_me()),
		parse_mode='html', reply_markup=markup)
 
@bot.message_handler(content_types=['text'])
def task(message):
	if message.chat.type == 'private':
		if message.text == 'Рандомное число':
			bot.send_message(message.chat.id, str(random.randint(0,100)))

		elif message.text == 'Как дела?':
 
			markup = types.InlineKeyboardMarkup(row_width=2)
			item1 = types.InlineKeyboardButton("Хорошо", callback_data='good')
			item2 = types.InlineKeyboardButton("Не очень", callback_data='bad')
 
			markup.add(item1, item2)
				
			bot.send_message(message.chat.id, 'Отлично, сам как?', reply_markup=markup)

		elif message.text == 'Камень, ножницы, бумага':

			markup = types.InlineKeyboardMarkup(row_width=3)
			item1 = types.InlineKeyboardButton("Камень", callback_data='rock')
			item2 = types.InlineKeyboardButton("Ножницы", callback_data='scissors')
			item3 = types.InlineKeyboardButton("Бумага", callback_data='paper')
 
			markup.add(item1, item2, item3)
				
			bot.send_message(message.chat.id, 'Давай сыграем в игру "Камень, ножницы, бумага". Напиши свой ход и я его сделаю))', reply_markup=markup)
		
		elif message.text == 'Данные об Коронавирусе':

			virus = open('static/virus.tgs', 'rb')
			bot.send_sticker(message.chat.id, virus)
			bot.send_message(message.chat.id, 'Заражено - ' + str(covid.get_total_confirmed_cases()) + '\nВыздоровело - ' + str(covid.get_total_recovered()) + '\nУмерло - ' + str(covid.get_total_deaths()))
		
		elif message.text == 'Википедия':
			pep = open('static/pep.tgs', 'rb')
			bot.send_sticker(message.chat.id, pep)
			bot.send_message(message.chat.id, 'Введите /Вики и то что хотите узнать')		
		elif '/Вики' in message.text:
			search_query = message.text.replace('/Вики ', '')
			search_result = str(wikipedia.summary(search_query))
			message = "Вот что я нашёл: \n{}".format(search_result)
			bot.send_message(message.chat.id, message)

		else:
			bot.send_message(message.chat.id, 'Я не знаю что ответить ')
 
@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
	try:
		if call.message:
			if call.data == 'good':
				bot.send_message(call.message.chat.id, 'Вот и отличненько ')
			elif call.data == 'bad':
				bot.send_message(call.message.chat.id, 'Бывает ')

			elif call.data == 'rock':
				bot.send_message(call.message.chat.id, random.choice(play) + '. Как думаешь, кто выиграл?')
			elif call.data == 'scissors':
				bot.send_message(call.message.chat.id, random.choice(play) + '. Как думаешь, кто выиграл?')
			elif call.data == 'paper':
				bot.send_message(call.message.chat.id, random.choice(play) + '. Как думаешь, кто выиграл?')

	except Exception as e:
		print(repr(e))
 
# RUN
bot.polling(none_stop=True)
  • Вопрос задан
  • 3816 просмотров
Решения вопроса 1
dmitriy337
@dmitriy337
Python Dev from Ukraine
Попробуй переменную message переименовать в 71 строке.Вообще, нельзя называть переменные уже занятыми именами. У тебя message.chat.id пытается достать атрибуты с переменной message,которая является str.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы