Answer the question
In order to leave comments, you need to log in
Pytelegrambotapi does not see the bool(re.search) link, why does it skip everything when entering a link to VK and displays that it was not a link to VK?
I will give a piece of code in which the link to a group or public VK is recognized.
I found the old code on GitHub but it should work, I read the documentation on Bool and did not understand anything, tell me, maybe there is an error on the surface!?
If it is not clear, then the comments are indicated and I give a link to the hollow bot, if anyone needs it)
https://github.com/mihail64/VKPosterBot
@bot.message_handler(func=lambda message: message.text == u'Добавить страницу ВК ')
@bot.message_handler(commands=['add'])
def add_page_url(message):
UID = message.chat.id
msg = bot.send_message(UID, 'Чтобы добавить новую страницу, с которой нужно отправлять записи, ' \
'отправь мне её адрес (например: *vk.com/mzk*):', parse_mode='Markdown', reply_markup=key_hide)
botan.track(BOTAN_TOKEN, message.chat.id, message, 'Запрос на добавление страницы (add)')
with io.open(str(UID) + '.UID', 'w', encoding='utf-8') as file:
# Создание временного файла .UID для хранения информации о новой странице
file.write(unicode(json.dumps({'uid': UID, 'vk' : '', 'vk_original' : '', 'vk_type' : '', \
'channel' : '', 'type' : '', 'last_id' : '', 'to' : ''}, ensure_ascii=False)))
bot.register_next_step_handler(msg, add_page_to)
def add_page_to(message):
UID = message.chat.id
UTXT = message.text
if UTXT == u'/cancel':
bot.send_message(UID, 'Хорошо, возвращаю тебя на главную.', reply_markup=key_default)
elif bool(re.search('(m.|new.|)(?i)vk.com', UTXT)) and \
bool(re.search('(m.|new.|)(?i)vk.com\/id\d+', UTXT)) == False:
# Если в адресе обнаружен vk.com, открываем временный файл .UID и заполняем данными
with open(str(UID) + '.UID', 'r') as file:
data = json.load(file)
if bool(re.search('(m.|new.|)(?i)vk.com\/(public|club)', UTXT)):
data['vk'] = re.sub('(\Ahttp\S?:\/\/|)(m.|new.|)(?i)vk.com\/(club|public)', '', UTXT)
data['vk_type'] = 'ID'
api = 'https://api.vk.com/method/wall.get?owner_id=-%s&count=10&filter=owner' % (data['vk'])
else:
data['vk'] = re.sub('(\Ahttp\S?:\/\/|)(m.|new.|)(?i)vk.com\/', '', UTXT)
data['vk_type'] = 'DOMAIN'
api = 'https://api.vk.com/method/wall.get?domain=%s&count=10&filter=owner' % (data['vk'])
data['vk_original'] = UTXT.lower()
-------------------------------####################################------------------------------
Пропускает этот кусок и выводит что ссылка не от вк, ну это не ошибка просто понять не могу почему не запускает проверку и не получает данные от вк а сразу выдает сообщение.
try:
# Попытка получить данные от vk.com
items = requests.get(api).json()
try:
tmp = items['response'][1]['is_pinned']
data['last_id'] = items['response'][3]['id']
except:
data['last_id'] = items['response'][2]['id']
with io.open(str(UID) + '.UID', 'w', encoding='utf-8') as file:
# Если всё прошло успешно, записываем данные в .UID
file.write(unicode(json.dumps(data)))
key_choose = types.ReplyKeyboardMarkup(resize_keyboard=True)
key_choose.row(types.KeyboardButton('В диалог с ботом '))
key_choose.row(types.KeyboardButton('В публичный канал '))
msg = bot.reply_to(message, 'Хорошо. Куда нужно присылать новые записи с этой страницы?',
reply_markup=key_choose)
bot.register_next_step_handler(msg, add_page_to_type)
-------------------------------####################################------------------------------
Бот сразу перепрыгивает на этот блок.
except Exception as ex:
msg = bot.reply_to(message, 'Видимо, ты прислал мне не ссылку *на группу или публичную' \
' страницу* ВКонтакте. Попробуй ещё раз.', parse_mode='Markdown')
bot.register_next_step_handler(msg, add_page_to)
-------------------------------####################################------------------------------
elif bool(re.search('(m.|new.|)(?i)vk.com\/id\d+', UTXT)):
msg = bot.reply_to(message, 'Бот умеет отправлять записи только из *групп и публичных страниц*, ' \
'страницы пользователей (начинаются с *id...*) сейчас не поддерживаются.\nПопробуй прислать ' \
'другую группу или публичную страницу.', parse_mode='Markdown')
bot.register_next_step_handler(msg, add_page_to)
else:
msg = bot.reply_to(message, 'Видимо, ты прислал мне не ссылку *на группу или публичную страницу* ' \
'ВКонтакте. Попробуй ещё раз.', parse_mode='Markdown')
bot.register_next_step_handler(msg, add_page_to)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question