From telebot import types ошибка

import telebot
from telebot import types

Получаю ошибку:

ImportError: cannot import name ‘types’ from ‘telebot’
(C:…..\Anaconda3\lib\site-packages\telebot__init__.py)

задан 19 мая 2019 в 16:24

Garison's user avatar

Вся проблема ушла после команды

pip install pyTelegramBotAPI

A K's user avatar

A K

28.5k19 золотых знаков58 серебряных знаков136 бронзовых знаков

ответ дан 8 окт 2019 в 7:58

Oksana Globa's user avatar

открываем setting (ctrl+alt+s) ищем python interpreter выбираем pip ищем pyTelegramBotAPI устанавливаем (я ещё и telebot установил) (пишу в pycharm)

ответ дан 6 ноя 2022 в 20:36

mi.k's user avatar

mi.kmi.k

211 серебряный знак4 бронзовых знака

@Corrandoo

Hello! I have updated pyTelegramBotAPI to 2.3.0 version and when I’m trying to launch my bot I have such error: module ‘telebot’ has no attribute ‘types’ I haven’t meet this error before the update.
I am using MacOS Sierra with Python 3.5

@Intervencion

Have you imported telebot first? Paste the import section please.

@Corrandoo

import telebot, server_manager, config, image_decoder, datetime, time
from threading import Thread

types = telebot.types #
bot = telebot.TeleBot(config.token)

I had «from telebot import types» before on the third line but it hasn’t worked too

@Intervencion

Try

import telebot, server_manager, config, image_decoder, datetime, time
from threading import Thread
config.token = "random:numbers"
types = telebot.types #
bot = telebot.TeleBot(config.token)

@Corrandoo

Unfortunately, it is not woking too. I have never had such problem before the update.

@Intervencion

Have you double checked that PyTelegramBotAPI is installed on the python you’re using?

@Corrandoo

Yes.
As I can see, I have problems only with the types. Not with whole telebot

@eternnoir

import telebot, server_manager, config, image_decoder, datetime, time
from threading import Thread

from telebot import types
bot = telebot.TeleBot(config.token)

# More code here.....

# Just use types
 rm = types.InlineKeyboardMarkup()

If you have from telebot import types just use types. You do not need types = telebot.types.

@Corrandoo

I wrote that this variant had not worked too. Everything stopped working after the update, do you understand?

@JMAgundezG

In python 3.5 the following doesn’t work from telebot import types,
The Traceback is Traceback (most recent call last): File "calendar_api.py", line 4, in <module> from telebot import types ImportError: cannot import name 'types'

@mayaracsferreira

Check it out, maybe this simple issue would help you like it did to me #323

@ttresslar

I am having the same issue. It was actually working not that long ago, but now I’m having an import issue

@gmsajeed

pip uninstall telebot
pip install pytelegrambotapi

import configparser
import config
import telebot
from telebot import types #buttons
from string import Template

bot = telebot.TeleBot(config.token)

user_dict = {}

class User:
    def __init__(self, city):
        self.city = city

        keys = ['fullname', 'phone']

        for key in keys:
            self.key = None

# если /help, /start
@bot.message_handler(commands=['start','help'])
def send_welcome(message):
    chat_id = message.chat.id
    bot.send_message(chat_id, "Здравствуйте." + "{message.from_user.first_name}" + " Я бот! Я могу вам помочь связаться с оператором для консультации.", reply_markup=markup)
    return(chat_id)
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2) 

#bot.send_message(message.chat.id, "Здравствуйте. {message.from_user.first_name}" + " Я бот! Я могу вам помочь связаться с оператором для консультации.", chat_id=call, reply_markup=markup)

def process_city_step(message):
    try:
        chat_id = message.chat.id
        user_dict[chat_id] = User(message.text)

        # удалить старую клавиатуру
        markup = types.ReplyKeyboardRemove(selective=False)

        msg = bot.send_message(chat_id, 'Как к вам обращаться?', reply_markup=markup)
        bot.register_next_step_handler(msg, process_fullname_step)

    except Exception as e:
        bot.reply_to(message, 'ooops!!')

def process_fullname_step(message):
    try:
        chat_id = message.chat.id
        user = user_dict[chat_id]
        user.fullname = message.text

        msg = bot.send_message(chat_id, 'Ваш номер телефона')
        bot.register_next_step_handler(msg, process_phone_step)

    except Exception as e:
        bot.reply_to(message, 'ooops!!')

def process_phone_step(message):
    try:
        int(message.text)

        chat_id = message.chat.id
        user = user_dict[chat_id]
        user.phone = message.text

    except Exception as e:
        msg = bot.reply_to(message, 'Вы ввели что то другое. Пожалуйста введите номер телефона.')
        bot.register_next_step_handler(msg, process_phone_step)

def process_social_step(message):
    try:
        chat_id = message.chat.id
        user = user_dict[chat_id]
        user.carModel = message.text

        markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
        itembtn1 = types.KeyboardButton('Только телефон')
        itembtn2 = types.KeyboardButton('Telegram')
        itembtn3 = types.KeyboardButton('Viber')
        itembtn4 = types.KeyboardButton('WhatsApp')
        markup.add(itembtn1, itembtn2, itembtn3, itembtn4)

        msg = bot.send_message(chat_id, 'Ваши соц сети', reply_markup=markup)
        bot.register_next_step_handler(msg)

    except Exception as e:
        bot.reply_to(message, 'ooops!!')

        # ваша заявка "Имя пользователя"
        bot.send_message(chat_id, getRegData(user, 'Ваша заявка', message.from_user.first_name), parse_mode="Markdown")
        # отправить в группу
        bot.send_message(config.chat_id, getRegData(user, 'Заявка от бота', bot.get_me().username), parse_mode="Markdown")

    except Exception as e:
        bot.reply_to(message, 'ooops!!')

# формирует вид заявки регистрации
# нельзя делать перенос строки Template
# в send_message должно стоять parse_mode="Markdown"
def getRegData(user, title, name):
    t = Template('$title *$name* \n ФИО: *$fullname* \n Телефон: *$phone* ')

    return t.substitute({
        'title': title,
        'name': name,
        'fullname': user.fullname,
        'phone': user.phone
    })

# произвольный текст
@bot.message_handler(content_types=["text"])
def send_help(message):
    bot.send_message(message.chat.id, 'О нас - /about\nРегистрация - /reg\nПомощь - /help')

# Enable saving next step handlers to file "./.handlers-saves/step.save".
# Delay=2 means that after any change in next step handlers (e.g. calling register_next_step_handler())
# saving will hapen after delay 2 seconds.
bot.enable_save_next_step_handlers(delay=2)

# Load next_step_handlers from save file (default "./.handlers-saves/step.save")
# WARNING It will work only if enable_save_next_step_handlers was called!
bot.load_next_step_handlers()

if __name__ == '__main__':
    bot.polling(none_stop=True)

import telebot
from telebot import types

Получаю ошибку:

ImportError: cannot import name ‘types’ from ‘telebot’
(C:…..Anaconda3libsite-packagestelebot__init__.py)

задан 19 мая 2019 в 16:24

Garison's user avatar

Вся проблема ушла после команды

pip install pyTelegramBotAPI

A K's user avatar

A K

28.3k18 золотых знаков54 серебряных знака126 бронзовых знаков

ответ дан 8 окт 2019 в 7:58

Oksana Globa's user avatar

открываем setting (ctrl+alt+s) ищем python interpreter выбираем pip ищем pyTelegramBotAPI устанавливаем (я ещё и telebot установил) (пишу в pycharm)

ответ дан 6 ноя 2022 в 20:36

mi.k's user avatar

mi.kmi.k

211 серебряный знак4 бронзовых знака

@Corrandoo

Hello! I have updated pyTelegramBotAPI to 2.3.0 version and when I’m trying to launch my bot I have such error: module ‘telebot’ has no attribute ‘types’ I haven’t meet this error before the update.
I am using MacOS Sierra with Python 3.5

@Intervencion

Have you imported telebot first? Paste the import section please.

@Corrandoo

import telebot, server_manager, config, image_decoder, datetime, time
from threading import Thread

types = telebot.types #
bot = telebot.TeleBot(config.token)

I had «from telebot import types» before on the third line but it hasn’t worked too

@Intervencion

Try

import telebot, server_manager, config, image_decoder, datetime, time
from threading import Thread
config.token = "random:numbers"
types = telebot.types #
bot = telebot.TeleBot(config.token)

@Corrandoo

Unfortunately, it is not woking too. I have never had such problem before the update.

@Intervencion

Have you double checked that PyTelegramBotAPI is installed on the python you’re using?

@Corrandoo

Yes.
As I can see, I have problems only with the types. Not with whole telebot

@eternnoir

import telebot, server_manager, config, image_decoder, datetime, time
from threading import Thread

from telebot import types
bot = telebot.TeleBot(config.token)

# More code here.....

# Just use types
 rm = types.InlineKeyboardMarkup()

If you have from telebot import types just use types. You do not need types = telebot.types.

@Corrandoo

I wrote that this variant had not worked too. Everything stopped working after the update, do you understand?

@JMAgundezG

In python 3.5 the following doesn’t work from telebot import types,
The Traceback is Traceback (most recent call last): File "calendar_api.py", line 4, in <module> from telebot import types ImportError: cannot import name 'types'

@mayaracsferreira

Check it out, maybe this simple issue would help you like it did to me #323

@ttresslar

I am having the same issue. It was actually working not that long ago, but now I’m having an import issue

@gmsajeed

pip uninstall telebot
pip install pytelegrambotapi

import configparser
import config
import telebot
from telebot import types #buttons
from string import Template

bot = telebot.TeleBot(config.token)

user_dict = {}

class User:
    def __init__(self, city):
        self.city = city

        keys = ['fullname', 'phone']

        for key in keys:
            self.key = None

# если /help, /start
@bot.message_handler(commands=['start','help'])
def send_welcome(message):
    chat_id = message.chat.id
    bot.send_message(chat_id, "Здравствуйте." + "{message.from_user.first_name}" + " Я бот! Я могу вам помочь связаться с оператором для консультации.", reply_markup=markup)
    return(chat_id)
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2) 

#bot.send_message(message.chat.id, "Здравствуйте. {message.from_user.first_name}" + " Я бот! Я могу вам помочь связаться с оператором для консультации.", chat_id=call, reply_markup=markup)

def process_city_step(message):
    try:
        chat_id = message.chat.id
        user_dict[chat_id] = User(message.text)

        # удалить старую клавиатуру
        markup = types.ReplyKeyboardRemove(selective=False)

        msg = bot.send_message(chat_id, 'Как к вам обращаться?', reply_markup=markup)
        bot.register_next_step_handler(msg, process_fullname_step)

    except Exception as e:
        bot.reply_to(message, 'ooops!!')

def process_fullname_step(message):
    try:
        chat_id = message.chat.id
        user = user_dict[chat_id]
        user.fullname = message.text

        msg = bot.send_message(chat_id, 'Ваш номер телефона')
        bot.register_next_step_handler(msg, process_phone_step)

    except Exception as e:
        bot.reply_to(message, 'ooops!!')

def process_phone_step(message):
    try:
        int(message.text)

        chat_id = message.chat.id
        user = user_dict[chat_id]
        user.phone = message.text

    except Exception as e:
        msg = bot.reply_to(message, 'Вы ввели что то другое. Пожалуйста введите номер телефона.')
        bot.register_next_step_handler(msg, process_phone_step)

def process_social_step(message):
    try:
        chat_id = message.chat.id
        user = user_dict[chat_id]
        user.carModel = message.text

        markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
        itembtn1 = types.KeyboardButton('Только телефон')
        itembtn2 = types.KeyboardButton('Telegram')
        itembtn3 = types.KeyboardButton('Viber')
        itembtn4 = types.KeyboardButton('WhatsApp')
        markup.add(itembtn1, itembtn2, itembtn3, itembtn4)

        msg = bot.send_message(chat_id, 'Ваши соц сети', reply_markup=markup)
        bot.register_next_step_handler(msg)

    except Exception as e:
        bot.reply_to(message, 'ooops!!')

        # ваша заявка "Имя пользователя"
        bot.send_message(chat_id, getRegData(user, 'Ваша заявка', message.from_user.first_name), parse_mode="Markdown")
        # отправить в группу
        bot.send_message(config.chat_id, getRegData(user, 'Заявка от бота', bot.get_me().username), parse_mode="Markdown")

    except Exception as e:
        bot.reply_to(message, 'ooops!!')

# формирует вид заявки регистрации
# нельзя делать перенос строки Template
# в send_message должно стоять parse_mode="Markdown"
def getRegData(user, title, name):
    t = Template('$title *$name* n ФИО: *$fullname* n Телефон: *$phone* ')

    return t.substitute({
        'title': title,
        'name': name,
        'fullname': user.fullname,
        'phone': user.phone
    })

# произвольный текст
@bot.message_handler(content_types=["text"])
def send_help(message):
    bot.send_message(message.chat.id, 'О нас - /aboutnРегистрация - /regnПомощь - /help')

# Enable saving next step handlers to file "./.handlers-saves/step.save".
# Delay=2 means that after any change in next step handlers (e.g. calling register_next_step_handler())
# saving will hapen after delay 2 seconds.
bot.enable_save_next_step_handlers(delay=2)

# Load next_step_handlers from save file (default "./.handlers-saves/step.save")
# WARNING It will work only if enable_save_next_step_handlers was called!
bot.load_next_step_handlers()

if __name__ == '__main__':
    bot.polling(none_stop=True)

#python #types #telegram #telegram-bot

Вопрос:

Ну, я попытался запустить на своем компьютере бота для телеграмм от другого человека, но ошибся, что:

 Traceback (most recent call last):
  File "C:UsersDmitriyPycharmProjectspythonProjectMain.py", line 10, in <module>
    keyboard = telebot.types.ReplyKeyboardMarkup(True, True)
AttributeError: module 'telebot' has no attribute 'types'
 

Я пытался импортировать типы из telebot:

 from telebot import types
 

Но на самом деле это не помогло. Самое странное, что этот код работает на компьютере владельца кода.

О чем это может быть?

введите описание изображения здесь

Ответ №1:

Вам нужно установить python-telegram-бота, например, через pip

 pip install python-telegram-bot 
 

затем импортируйте его из пакета telegram

 from telegram import ReplyKeyboardMarkup
 

и замените создание ReplyKeyboardMarkup на это:

 keyboard = ReplyKeyboardMarkup(True, True)
 

Комментарии:

1. @domandihno , на самом деле это не помогло(

2. какая ошибка у вас возникает после применения этого шаня? Ошибка должна быть другой, как в решении, которое я предложил, мы не импортируем ReplyKeyboardMarkup из telebot.типы

Ответ №2:

за подобные ошибки … переустановите библиотеку или используйте (—обновление) при ее установке !

подобный этому:

 pip uninstall telebot
pip install pyTelegramBotAPI
pip install pytelegrambotapi --upgrade
 

Счастливого Кодирования!

DiZiNnEs

0 / 0 / 0

Регистрация: 02.01.2019

Сообщений: 57

1

13.09.2019, 14:01. Показов 6405. Ответов 5

Метки telebot, url (Все метки)


Всех с праздником!

Делаю телеграмм-бота и решил сделать ссылку, т.е пользователь вводить команду /url и выводит ссылку на мой ВК

Вот сам код:

Python
1
2
3
4
5
6
@bot.message_handler(commands=['url'])
def url(message):
    markup = types.InlineKeyboardMarkup()
    btn_my_site = types.InlineKeyboardButton(text='ВК разработчика', url='https://vk.com/id507008184')
    markup.add(btn_my_site)
    bot.send_message(message.chat.id, "Нажми на кнопку и перейди на VK разработчика бота.", reply_markup=markup)

Сама ошибка:
File «/home/dizinnes/PycharmProjects/TestAndTelebot/justTest.py», line 16, in url
markup = types.InlineKeyboardMarkup()
AttributeError: module ‘types’ has no attribute ‘InlineKeyboardMarkup’

Ошибка с выводом ссылки, telebot

Весь исходный код:

Кликните здесь для просмотра всего текста

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import telebot
import types
 
import URL
 
bot = telebot.TeleBot("secret")
 
#Keyborad - клавиатура
#keyboard1 = telebot.types.ReplyKeyboardMarkup()
#keyboard1.row('Начальные команды', '/help', '/start',)
 
URL.keyboard()
 
@bot.message_handler(commands=['url'])
def url(message):
    markup = types.InlineKeyboardMarkup()
    btn_my_site = types.InlineKeyboardButton(text='ВК разработчика', url='https://vk.com/id507008184')
    markup.add(btn_my_site)
    bot.send_message(message.chat.id, "Нажми на кнопку и перейди на VK разработчика бота.", reply_markup=markup)
 
#Обработчик команды /start
@bot.message_handler(commands=['start', 'url'])
def handle_start(message):
    bot.send_message(message.from_user.id, 'Привет. я бот.')
 
#Обработчик команды /help
@bot.message_handler(commands=['help'])
def handle_help(message):
    bot.send_message(message.from_user.id, 'Я готов помочь.')
 
 
 
@bot.message_handler(content_types=['text'])
def handle_text(message):
    if message.text.lower() == 'начальные команды':
        bot.send_message(message.from_user.id, 'n/start', 'n/help', )
 
 
 
bot.polling(none_stop=True, interval=0)

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Автоматизируй это!

Эксперт Python

6374 / 4121 / 1133

Регистрация: 30.03.2015

Сообщений: 12,194

Записей в блоге: 29

13.09.2019, 14:06

2

Цитата
Сообщение от DiZiNnEs
Посмотреть сообщение

AttributeError: module ‘types’ has no attribute ‘InlineKeyboardMarkup’

какое слово ты не смог тут перевести?

Цитата
Сообщение от DiZiNnEs
Посмотреть сообщение

ВК разработчика

я бы был скромнее, если бы не мог понять смысл ошибки по используемой библиотеке.

0

DiZiNnEs

0 / 0 / 0

Регистрация: 02.01.2019

Сообщений: 57

13.09.2019, 14:24

 [ТС]

3

Так я его добавил

Python
1
import types

0

Автоматизируй это!

Эксперт Python

6374 / 4121 / 1133

Регистрация: 30.03.2015

Сообщений: 12,194

Записей в блоге: 29

13.09.2019, 14:37

4

Цитата
Сообщение от DiZiNnEs
Посмотреть сообщение

Так я его добавил

ясно… попробую еще раз — как ты перевел и понял ту ошибку, что тебе написал интерпретатор?

0

DiZiNnEs

0 / 0 / 0

Регистрация: 02.01.2019

Сообщений: 57

13.09.2019, 14:49

 [ТС]

5

Модуль «types» — не имеет атрибута «InlineKeyboardMarkup», следовательно его нужно добавить, только как я не понял

Добавлено через 5 минут
Нужно было лишь сделать так

Python
1
from telebot import types

0

Welemir1

13.09.2019, 14:53


    Ошибка с выводом ссылки, telebot

Не по теме:

Цитата
Сообщение от DiZiNnEs
Посмотреть сообщение

Модуль «types» — не имеет атрибута «InlineKeyboardMarkup», следовательно его нужно добавить

на самом деле нет, но я так понимаю это не важно, бот написан и ты -его разработчик…

0

IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

13.09.2019, 14:53

Поиск из двух таблиц с выводом ссылки
Здравствуйте, как реализовать запрос из двух таблиц при том, что в таблице blog(поле title_post) ,…

Реализация ссылки в таблице, с выводом id на другую
возможнно ли как то реализовать ссылку на подобии того, что попытался на 21 строке?
&lt;?php

Загрузка файла с выводом ссылки для скачивания
Допустим есть простейшая форма и скрипт загрузки файла:
&lt;html&gt;
&lt;form action=&quot;$_SERVER&quot;…

Ошибка с выводом
Patient: Фамилия, Имя, Отчество, Адрес, Номер медицинской карты,
Показатель температуры….

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

6

N

Well, first of all, putting one service in one assembly is usually too much to make a living out of itself, but, yeah, the problem is understandable, it’s the same thing.And secondly, it’s simple: instead of having someService’s original space, you need to name it Contracts (where you speak of Abstract-Services-StateISomeService), we’re collecting these things separately in the topicide packages, which is logical and understandable — contracts for that, for that. And it’s not so critical, one interface or one hundred in the contract, but it’s just that the name gets easier. Well, we’re allowed to have one of the model rules — it’s CompanyName.ProjectNameContracts or CompanyName.ProjectName.SomeContracts.With Concrete, I usually don’t have a question like this — everything is in the application project, usually there’s no need to make more than one move, but, hypothetically, I can give an example for implementation in Ef, Dapper, Ado: apply Ef, Dapper, Ado before the name of your service. I mean, find what you’ve got to do with this and make it a prefix. And if you’ve got one, then use the word Default as a default prefix.In summary, I suggest, for example, that someService collect folders/chempes Models, Contracts and DefaultImplementation. (Cannounce other options, that’s what you’re asking for)Besides, I’ve been watching a lot of examples on Mediatr, and I like things sometimes that you’re writing the name of a nemspeys and through the name of a class, like me. https://github.com/akmetainfo/WallyBackend/blob/master/src/Wally.WebApi/Controllers/TransactionController.cs :once indicated using:using Transactions = Usol.Wally.Application.Transactions;
And then we’ll write in names. Transactions.List.Query or Transactions.Create.Command — and it basically reminds me a little bit of one of the options — like if we’d made long unique names. CreateCommand or CreateTransactionCommand♪So, sometimes, it’s a good look at these parts, and it’s important to group logically.

-koma-

Пользователь

    Автор темы

  • #1

Столкнулся со следующей проблемой…
Нашел интересного для себя бота.
В [preview]main.py [/preview]указан Telebot
Попробовав установить его — выдавало ошибки

ImportError: cannot import name 'types' from 'telebot'

Немного погуглив, решил поставить pyTelegramBotAPI
Попытавшись запустить с ним и заранее удаленным Telebot выдает следующее

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    import telebot
ModuleNotFoundError: No module named 'telebot'

В чем же дело и как пофиксить?

annelo

  • #2

Столкнулся со следующей проблемой…
Нашел интересного для себя бота.
В [preview]main.py [/preview]указан Telebot
Попробовав установить его — выдавало ошибки

ImportError: cannot import name 'types' from 'telebot'

Немного погуглив, решил поставить pyTelegramBotAPI
Попытавшись запустить с ним и заранее удаленным Telebot выдает следующее

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    import telebot
ModuleNotFoundError: No module named 'telebot'

В чем же дело и как пофиксить?

Ты да или да? Там же все написано… В 3-ей строке ошибка, ты импортируешь библиотеку которая не установлена. И так как ты хочешь не получится, в библиотеках может отличаться функция и т.д. Лучше поищи другого бота.

Столкнулся со следующей проблемой…
Нашел интересного для себя бота.
В [preview]main.py [/preview]указан Telebot
Попробовав установить его — выдавало ошибки

ImportError: cannot import name 'types' from 'telebot'

Немного погуглив, решил поставить pyTelegramBotAPI
Попытавшись запустить с ним и заранее удаленным Telebot выдает следующее

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    import telebot
ModuleNotFoundError: No module named 'telebot'

В чем же дело и как пофиксить?

Скинь под хайд бота, поковыряем…

SQL

Эксперт

  • #3

Столкнулся со следующей проблемой…
Нашел интересного для себя бота.
В [preview]main.py [/preview]указан Telebot
Попробовав установить его — выдавало ошибки

ImportError: cannot import name 'types' from 'telebot'

Немного погуглив, решил поставить pyTelegramBotAPI
Попытавшись запустить с ним и заранее удаленным Telebot выдает следующее

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    import telebot
ModuleNotFoundError: No module named 'telebot'

В чем же дело и как пофиксить?

Ты версию telebot не ласт ставь, а какую-нибудь поменьше
from telebot import types

annelo

  • #4

Ты версию telebot не ласт ставь, а какую-нибудь поменьше
from telebot import types

Может у него pip не последний, встречал ошибку, не устанавливалась, а именно не компилилась библиотека на не последнем PIP-е :FeelsBadMan::FeelsBadMan::FeelsBadMan:

fukuzaca

  • #1

Я недавно начал пробывать себя в сфере ботов телеге.

При запуске выдает ошибку и говорит что эта фигня виновата (ниже)
bot = telebot.TeleBot(«**********************»)

Traceback (most recent call last):
  File "D:Pythonbot.py", line 2, in <module>
    from telebot import types
  File "C:UsersGavrikAppDataLocalProgramsPythonPython310libsite-packagestelebottypes.py", line 12, in <module>
    from telebot import util
  File "C:UsersGavrikAppDataLocalProgramsPythonPython310libsite-packagestelebotutil.py", line 322, in <module>
    def user_link(user: types.User, include_id: bool=False) -> str:
AttributeError: partially initialized module 'telebot.types' has no attribute 'User' (most likely due to a circular import)
import telebot
from telebot import types


bot = telebot.TeleBot("******************)", parse_mode=None)

@bot.message_handler(commands=["start"])
def start (message):
    channel_link = "https://t.me/aogirilifestyle"
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    keyboard = types.KeyboardButton(text="Confirm")
    markup.add(keyboard)
    chat_id = message.chat.id
    user = message.chat.first_name
    bot.send_message(chat_id, f"Hi {user} if u want to use bot you must subscribe to the channel/n"
        f"{channel_link}", reply_markup=markup)

@bot.message_handler(content_types=["text"])
def text(message):
    user = message.chat.first_name
    if message.chat.type == 'private':
        if message.text == 'Confirm':
            status = ['creator', 'administrator', 'member']
            for stat in status:
                if stat == bot.get_chat_member(char_id="@aogirilifestyle", user_id=message.from_user.id).status:
                    bot.send_message(message.chat.id, f"Open {user}")
                    break


                else:
                    bot.send_message(message.chat.id, "Sub to the channel!")





    bot.polling(none_stop=True)

1648551786195.png

Что делать? :((((

Ошибку сверху исправил
появилась новая

1648552373561.png

  • 1648551458552.png

    1648551458552.png

    20.6 KB · Просмотры: 12

Последнее редактирование: 29 Мар 2022

#python #types #telegram #telegram-bot

Вопрос:

Ну, я попытался запустить на своем компьютере бота для телеграмм от другого человека, но ошибся, что:

 Traceback (most recent call last):
  File "C:UsersDmitriyPycharmProjectspythonProjectMain.py", line 10, in <module>
    keyboard = telebot.types.ReplyKeyboardMarkup(True, True)
AttributeError: module 'telebot' has no attribute 'types'
 

Я пытался импортировать типы из telebot:

 from telebot import types
 

Но на самом деле это не помогло. Самое странное, что этот код работает на компьютере владельца кода.

О чем это может быть?

введите описание изображения здесь

Ответ №1:

Вам нужно установить python-telegram-бота, например, через pip

 pip install python-telegram-bot 
 

затем импортируйте его из пакета telegram

 from telegram import ReplyKeyboardMarkup
 

и замените создание ReplyKeyboardMarkup на это:

 keyboard = ReplyKeyboardMarkup(True, True)
 

Комментарии:

1. @domandihno , на самом деле это не помогло(

2. какая ошибка у вас возникает после применения этого шаня? Ошибка должна быть другой, как в решении, которое я предложил, мы не импортируем ReplyKeyboardMarkup из telebot.типы

Ответ №2:

за подобные ошибки … переустановите библиотеку или используйте (—обновление) при ее установке !

подобный этому:

 pip uninstall telebot
pip install pyTelegramBotAPI
pip install pytelegrambotapi --upgrade
 

Счастливого Кодирования!

Понравилась статья? Поделить с друзьями:
  • From sympy import ошибка
  • From pyqt5 import uic ошибка
  • From pil import image imagetk ошибка
  • From keyword not found where expected oracle ошибка
  • From keras models import sequential ошибка