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
Have you imported telebot first? Paste the import section please.
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
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)
Unfortunately, it is not woking too. I have never had such problem before the update.
Have you double checked that PyTelegramBotAPI is installed on the python you’re using?
Yes.
As I can see, I have problems only with the types. Not with whole telebot
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
.
I wrote that this variant had not worked too. Everything stopped working after the update, do you understand?
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'
Check it out, maybe this simple issue would help you like it did to me #323
I am having the same issue. It was actually working not that long ago, but now I’m having an import issue
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)
DiZiNnEs 0 / 0 / 0 Регистрация: 02.01.2019 Сообщений: 57 |
||||||||
1 |
||||||||
13.09.2019, 14:01. Показов 6510. Ответов 5 Метки telebot, url (Все метки)
Всех с праздником! Делаю телеграмм-бота и решил сделать ссылку, т.е пользователь вводить команду /url и выводит ссылку на мой ВК Вот сам код:
Сама ошибка: Весь исходный код: Кликните здесь для просмотра всего текста
__________________
0 |
Автоматизируй это! 6481 / 4174 / 1140 Регистрация: 30.03.2015 Сообщений: 12,325 Записей в блоге: 29 |
|
13.09.2019, 14:06 |
2 |
AttributeError: module ‘types’ has no attribute ‘InlineKeyboardMarkup’ какое слово ты не смог тут перевести?
ВК разработчика я бы был скромнее, если бы не мог понять смысл ошибки по используемой библиотеке.
0 |
DiZiNnEs 0 / 0 / 0 Регистрация: 02.01.2019 Сообщений: 57 |
||||
13.09.2019, 14:24 [ТС] |
3 |
|||
Так я его добавил
0 |
Автоматизируй это! 6481 / 4174 / 1140 Регистрация: 30.03.2015 Сообщений: 12,325 Записей в блоге: 29 |
|
13.09.2019, 14:37 |
4 |
Так я его добавил ясно… попробую еще раз — как ты перевел и понял ту ошибку, что тебе написал интерпретатор?
0 |
DiZiNnEs 0 / 0 / 0 Регистрация: 02.01.2019 Сообщений: 57 |
||||
13.09.2019, 14:49 [ТС] |
5 |
|||
Модуль «types» — не имеет атрибута «InlineKeyboardMarkup», следовательно его нужно добавить, только как я не понял Добавлено через 5 минут
0 |
Welemir1 |
13.09.2019, 14:53
|
Не по теме:
Модуль «types» — не имеет атрибута «InlineKeyboardMarkup», следовательно его нужно добавить на самом деле нет, но я так понимаю это не важно, бот написан и ты -его разработчик…
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
13.09.2019, 14:53 |
Реализация ссылки в таблице, с выводом id на другую … Загрузка файла с выводом ссылки для скачивания Ошибка с выводом Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 6 |
-
#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)
Что делать? :((((
Ошибку сверху исправил
появилась новая
-
1648551458552.png
20.6 KB · Просмотры: 12
Последнее редактирование: 29 Мар 2022
You have many possibilities:Given that test is going to be the content of data_Q4 (fourth quarter), a very simple option is to create a column that identifies the quarter:import io
import pandas as pd
import pandas as pd
Control delimiters, rows, column names with read_csv (see later)
data_Q1 = pd.read_csv(«LoanStats_2018Q1.csv», skiprows=1, skipfooter=2, engine=’python’)
data_Q2 = pd.read_csv(«LoanStats_2018Q2.csv», skiprows=1, skipfooter=2, engine=’python’)
data_Q3 = pd.read_csv(«LoanStats_2018Q3.csv», skiprows=1, skipfooter=2, engine=’python’)
data_Q4 = pd.read_csv(«LoanStats_2018Q4.csv», skiprows=1, skipfooter=2, engine=’python’)
data_Q1[«quarter»] = «Q1»
data_Q2[«quarter»] = «Q2»
data_Q3[«quarter»] = «Q3»
data_Q4[«quarter»] = «Q4»
frames = [data_Q1,data_Q2, data_Q3, data_Q4]
result = pd.concat(frames)
bool_filter = result[«quarter»] == «Q4»
test = result[bool_filter]
training = result[~bool_filter]
>>> training[«issue_d»].unique()
[‘Mar-2018’ ‘Feb-2018’ ‘Jan-2018’ ‘Jun-2018’ ‘May-2018’ ‘Apr-2018’
‘Sep-2018’ ‘Aug-2018’ ‘Jul-2018’]
>>> test[«issue_d»].unique())
[‘Dec-2018’ ‘Nov-2018’ ‘Oct-2018’]
Another option is to simply filter using a bolean filter on the column issue_d:bool_filter = result[«issue_d»].isin([‘Dec-2018’, ‘Nov-2018’, ‘Oct-2018’])
test = result[bool_filter]
training = result[~bool_filter]
Making the categorical column would be another possibility:months= [‘Jan-2018’, ‘Feb-2018’, ‘Mar-2018’, ‘Apr-2018’, ‘May-2018’, ‘Jun-2018’,
‘Jul-2018’, ‘Aug-2018’, ‘Sep-2018’, ‘Oct-2018’, ‘Nov-2018′ ,’Dec-2018’]
result[«issue_d»] = pd.Categorical( result[«issue_d»], categories=months, ordered=True)
test = result[result[«issue_d»] >= ‘Oct-2018’]
training = result[result[«issue_d»] < ‘Oct-2018′]
Finally, the most direct and general way is to convert the column issue_d a guy. datetime and then simply select using dates intervals:result[«issue_d»] = pd.to_datetime(result[«issue_d»], format=’%b-%Y’)
test = result[result[«issue_d»] >= ‘Oct-2018’]
training = result[result[«issue_d»] < ‘Oct-2018’]
test[«issue_d»].unique()
>>> test.shape
(366830, 144)
>>> test[«issue_d»].unique()
array([‘2018-12-01T00:00:00.000000000’, ‘2018-11-01T00:00:00.000000000’,
‘2018-10-01T00:00:00.000000000′], dtype=’datetime64[ns]’)
>>> training.shape
(366830, 144)
>>> training[«issue_d»].unique()
array([‘2018-03-01T00:00:00.000000000’, ‘2018-02-01T00:00:00.000000000’,
‘2018-01-01T00:00:00.000000000’, ‘2018-06-01T00:00:00.000000000’,
‘2018-05-01T00:00:00.000000000’, ‘2018-04-01T00:00:00.000000000’,
‘2018-09-01T00:00:00.000000000’, ‘2018-08-01T00:00:00.000000000’,
‘2018-07-01T00:00:00.000000000′], dtype=’datetime64[ns]’)