Cannot import name types from telebot как исправить

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.4k19 золотых знаков54 серебряных знака130 бронзовых знаков

ответ дан 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 бронзовых знака

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

Traceback (most recent call last):
  File "C:UsersmaksaDesktopMy Filesbad botmain.py", line 2, in <module>
    from telebot import types
ImportError: cannot import name 'types' from 'telebot' (C:Program FilesPython39libsite-packagestelebot__init__.py)

Что в такой ситуации делать? устанавливал даже 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)

@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

Sasha_Romanov


  • #1

Начал писать бота для телеги, вылезла это ошибка:
Traceback (most recent call last):
File «main.py», line 3, in <module>
from telebot import types
ImportError: cannot import name ‘types’ from ‘telebot’ (/home/runner/telebot/venv/lib/python3.8/site-packages/telebot/__init__.py)
А сам код для бота вот:
import telebot
import requests
from telebot import types
bot = telebot.TeleBot(«5468636017:AAE03qPOxTkGhTuIyP2NBOlNbdomFMFM-g4»)

@bot.message_handler(commands=[«start»,])
def start(message):
bot.send_message(message.chat.id,f»hi»)
@bot.message_handler(commands=[‘help’])
def button_message(message):
markup=types.ReplyKeyboardMarkup(resize_keyboard=True)
item1=types.KeyboardButton(«Мой вк»)
markup.add(item1)
bot.send_message(message.chat.id,’Выберите что вам надо’,reply_markup=markup)
@bot.message_handler(content_types=’text’)
def message_reply(message):
if message.text==»Мой вк»:
bot.send_message(message.chat.id,»https://vk.com/trumtrum2″)

bot.infinity_polling()
Писал на этом сайте https://replit.com/@sanyaaaaaa/telebot#main.py

  • #3

pip install PyTelegramBotAPI, а лучше переходи на aiogram, он лучше в разы

Понравилась статья? Поделить с друзьями:
  • Люди в майнкрафте как найти
  • Как найти последние измененные файлы windows 10
  • Как найти слона в музее
  • Как найти строку с максимальным значением pandas
  • Как найти вписанный угол его градусную величину