Attachments handler
This commit is contained in:
parent
e02203b3dc
commit
56917be9af
65
bot.py
65
bot.py
@ -15,9 +15,10 @@ vk_threads = {}
|
|||||||
vk_tokens = {}
|
vk_tokens = {}
|
||||||
|
|
||||||
bot = telebot.AsyncTeleBot(token)
|
bot = telebot.AsyncTeleBot(token)
|
||||||
|
bot.remove_webhook()
|
||||||
|
|
||||||
link = 'https://oauth.vk.com/authorize?client_id={}&' \
|
link = 'https://oauth.vk.com/authorize?client_id={}&' \
|
||||||
'display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=friends,messages' \
|
'display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=friends,messages,offline' \
|
||||||
'&response_type=token&v=5.65'.format(vk_app_id)
|
'&response_type=token&v=5.65'.format(vk_app_id)
|
||||||
|
|
||||||
mark = types.InlineKeyboardMarkup()
|
mark = types.InlineKeyboardMarkup()
|
||||||
@ -52,9 +53,7 @@ def stop_thread(message):
|
|||||||
def extract_unique_code(text):
|
def extract_unique_code(text):
|
||||||
# Extracts the unique_code from the sent /start command.
|
# Extracts the unique_code from the sent /start command.
|
||||||
try:
|
try:
|
||||||
text = text[45:]
|
return text[45:].split('&')[0]
|
||||||
text = text.split('&')
|
|
||||||
return text[0]
|
|
||||||
except:
|
except:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@ -66,7 +65,7 @@ def verifycode(code):
|
|||||||
|
|
||||||
|
|
||||||
def info_extractor(info):
|
def info_extractor(info):
|
||||||
info = info[0].url[8:-3].split('.')
|
info = info[0].url[8:-1].split('.')
|
||||||
return info
|
return info
|
||||||
|
|
||||||
|
|
||||||
@ -90,8 +89,36 @@ def start_command(message):
|
|||||||
bot.send_message(message.chat.id, 'Вход уже выполнен!\n/stop для выхода.').wait()
|
bot.send_message(message.chat.id, 'Вход уже выполнен!\n/stop для выхода.').wait()
|
||||||
|
|
||||||
|
|
||||||
|
"""def vk_sender(message, method):
|
||||||
|
if message.reply_to_message:
|
||||||
|
if str(message.from_user.id) in vk_tokens:
|
||||||
|
info = info_extractor(message.reply_to_message.entities)
|
||||||
|
if info is not None:
|
||||||
|
if len(info) - 1:
|
||||||
|
method(message, info[0], False)
|
||||||
|
vk.API(vk_tokens[str(message.from_user.id)].session).messages.send(chat_id=info[1],
|
||||||
|
message=message.text)
|
||||||
|
else:
|
||||||
|
method(message, info[0], True)
|
||||||
|
vk.API(vk_tokens[str(message.from_user.id)].session).messages.send(user_id=info[0],
|
||||||
|
message=message.text)
|
||||||
|
else:
|
||||||
|
bot.send_message(message.chat.id, 'Вход не выполнен! /start дл входа').wait()
|
||||||
|
|
||||||
|
|
||||||
|
def send_audio(msg, info, private):
|
||||||
|
if private:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@bot.message_handler(content_types=['audio'])
|
||||||
|
def reply_audio(message):
|
||||||
|
vk_sender(message, send_audio)"""
|
||||||
|
|
||||||
|
|
||||||
@bot.message_handler(content_types=['text'])
|
@bot.message_handler(content_types=['text'])
|
||||||
def reply(message):
|
def reply_text(message):
|
||||||
m = re.search('https://oauth\.vk\.com/blank\.html#access_token=[a-z0-9]*&expires_in=[0-9]*&user_id=[0-9]*',
|
m = re.search('https://oauth\.vk\.com/blank\.html#access_token=[a-z0-9]*&expires_in=[0-9]*&user_id=[0-9]*',
|
||||||
message.text)
|
message.text)
|
||||||
if m:
|
if m:
|
||||||
@ -107,9 +134,9 @@ def reply(message):
|
|||||||
' попробуешь? telegram.org/download', parse_mode='Markdown').wait()
|
' попробуешь? telegram.org/download', parse_mode='Markdown').wait()
|
||||||
bot.send_message(message.chat.id, 'Для сообщений из групповых чатов будет указываться'
|
bot.send_message(message.chat.id, 'Для сообщений из групповых чатов будет указываться'
|
||||||
' чат после имени отправителя:').wait()
|
' чат после имени отправителя:').wait()
|
||||||
rp = bot.send_message(message.chat.id, '*Ник Невидов @ My English is perfect:*\n'
|
bot.send_message(message.chat.id, '*Ник Невидов @ My English is perfect:*\n'
|
||||||
'London is the capital of Great Britain',
|
'London is the capital of Great Britain',
|
||||||
parse_mode='Markdown').wait()
|
parse_mode='Markdown').wait()
|
||||||
bot.send_message(message.chat.id, 'Чтобы ответить, используй Reply на нужное сообщение.'
|
bot.send_message(message.chat.id, 'Чтобы ответить, используй Reply на нужное сообщение.'
|
||||||
' (нет, на эти не сработает, нужно реальное)',
|
' (нет, на эти не сработает, нужно реальное)',
|
||||||
parse_mode='Markdown').wait()
|
parse_mode='Markdown').wait()
|
||||||
@ -120,16 +147,20 @@ def reply(message):
|
|||||||
return
|
return
|
||||||
|
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
info = info_extractor(message.reply_to_message.entities)
|
if str(message.from_user.id) in vk_tokens:
|
||||||
if info is not None:
|
info = info_extractor(message.reply_to_message.entities)
|
||||||
if len(info) - 1:
|
if info is not None:
|
||||||
vk.API(vk_tokens[str(message.from_user.id)].session).messages.send(chat_id=info[1],
|
if len(info) - 1:
|
||||||
message=message.text)
|
vk.API(vk_tokens[str(message.from_user.id)].session).messages.send(chat_id=info[1],
|
||||||
else:
|
message=message.text)
|
||||||
vk.API(vk_tokens[str(message.from_user.id)].session).messages.send(user_id=info[0],
|
else:
|
||||||
message=message.text)
|
vk.API(vk_tokens[str(message.from_user.id)].session).messages.send(user_id=info[0],
|
||||||
|
message=message.text)
|
||||||
|
else:
|
||||||
|
bot.send_message(message.chat.id, 'Вход не выполнен! /start дл входа').wait()
|
||||||
|
|
||||||
|
|
||||||
|
#bot.polling()
|
||||||
class WebhookServer(object):
|
class WebhookServer(object):
|
||||||
# index равнозначно /, т.к. отсутствию части после ip-адреса (грубо говоря)
|
# index равнозначно /, т.к. отсутствию части после ip-адреса (грубо говоря)
|
||||||
@cherrypy.expose
|
@cherrypy.expose
|
||||||
|
150
vk_messages.py
150
vk_messages.py
@ -1,5 +1,7 @@
|
|||||||
import vk
|
import vk
|
||||||
import time
|
import time
|
||||||
|
import requests
|
||||||
|
import wget
|
||||||
|
|
||||||
|
|
||||||
class VkPolling:
|
class VkPolling:
|
||||||
@ -11,24 +13,141 @@ class VkPolling:
|
|||||||
|
|
||||||
def run(self, vk_user, bot, chat_id):
|
def run(self, vk_user, bot, chat_id):
|
||||||
while self._running:
|
while self._running:
|
||||||
|
updates = []
|
||||||
try:
|
try:
|
||||||
messages = vk_user.get_new_messages()
|
updates = vk_user.get_new_messages()
|
||||||
if messages:
|
|
||||||
for m in messages:
|
|
||||||
if m.split('">​</a>')[0][-1]:
|
|
||||||
bot.send_message(chat_id, m, parse_mode='HTML', disable_notification=True)
|
|
||||||
else:
|
|
||||||
bot.send_message(chat_id, m, parse_mode='HTML')
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print('Error: {}'.format(e))
|
print('Error: {}'.format(e))
|
||||||
for i in range(35):
|
if updates:
|
||||||
|
handle_updates(vk_user, bot, chat_id, updates)
|
||||||
|
for i in range(45):
|
||||||
if self._running:
|
if self._running:
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
|
|
||||||
|
|
||||||
|
def handle_messages(m, vk_user, bot, chat_id):
|
||||||
|
user = vk.API(vk_user.session).users.get(user_ids=m["uid"], fields=[])[0]
|
||||||
|
if 'body' in m and not 'attachment' in m:
|
||||||
|
data = add_reply_info(m, user["first_name"], user["last_name"]) + '{}'.format(m["body"].replace('<br>', '\n'))
|
||||||
|
bot.send_message(chat_id, data, parse_mode='HTML',
|
||||||
|
disable_notification=check_notification(m)).wait()
|
||||||
|
if 'attachment' in m:
|
||||||
|
attachment_handler(m, user, bot, chat_id)
|
||||||
|
|
||||||
|
|
||||||
|
def handle_updates(vk_user, bot, chat_id, updates):
|
||||||
|
for m in updates:
|
||||||
|
if True: # not m['out']:
|
||||||
|
print(m)
|
||||||
|
handle_messages(m, vk_user, bot, chat_id)
|
||||||
|
|
||||||
|
|
||||||
|
def attachment_handler(m, user, bot, chat_id):
|
||||||
|
if m['attachment']['type'] == 'photo':
|
||||||
|
for photo in m['attachments']:
|
||||||
|
data = add_reply_info(m, user['first_name'], user['last_name']) + '<a href="{}">Фото</a>'.format(
|
||||||
|
get_max_src(photo['photo']))
|
||||||
|
bot.send_message(chat_id, data, parse_mode='HTML',
|
||||||
|
disable_notification=check_notification(m)).wait()
|
||||||
|
if m['attachment']['type'] == 'video':
|
||||||
|
for vid in m['attachments']:
|
||||||
|
link = 'https://vk.com/video{}_{}'.format(vid['video']['owner_id'],
|
||||||
|
vid['video']['vid'])
|
||||||
|
data = add_reply_info(m, user['first_name'], user['last_name']) + '<a href="{}">Видео</a>'.format(link)
|
||||||
|
bot.send_message(chat_id, data, parse_mode='HTML',
|
||||||
|
disable_notification=check_notification(m)).wait()
|
||||||
|
if m['attachment']['type'] == 'audio':
|
||||||
|
for audio in m['attachments']:
|
||||||
|
data = add_reply_info(m, user['first_name'], user['last_name']) + '🎵 <code>{} - {}</code>'.format(
|
||||||
|
audio['audio']['artist'],
|
||||||
|
audio['audio']['title'])
|
||||||
|
bot.send_message(chat_id, data, parse_mode='HTML',
|
||||||
|
disable_notification=check_notification(m)).wait()
|
||||||
|
if m['attachment']['type'] == 'doc':
|
||||||
|
for doc in m['attachments']:
|
||||||
|
if doc['doc']['ext'] == 'gif':
|
||||||
|
link = doc['doc']['url']
|
||||||
|
data = add_reply_info(m, user["first_name"], user["last_name"]) + '<a href="{}">GIF</a>'.format(link)
|
||||||
|
bot.send_message(chat_id, data, parse_mode='HTML',
|
||||||
|
disable_notification=check_notification(m)).wait()
|
||||||
|
|
||||||
|
if doc['doc']['ext'] == 'pdf' or doc['doc']['ext'] == 'zip':
|
||||||
|
link = doc['doc']['url']
|
||||||
|
data = add_reply_info(m, user["first_name"], user["last_name"], ) + '<a href="{}">Документ</a>'.format(
|
||||||
|
link)
|
||||||
|
bot.send_message(chat_id, data, parse_mode='HTML',
|
||||||
|
disable_notification=check_notification(m)).wait()
|
||||||
|
|
||||||
|
if doc['doc']['ext'] == 'jpg' or doc['doc']['ext'] == 'png':
|
||||||
|
link = doc['doc']['url']
|
||||||
|
data = add_reply_info(m, user["first_name"], user["last_name"], ) + '<i>Документ</i>'
|
||||||
|
bot.send_message(chat_id, data, parse_mode='HTML',
|
||||||
|
disable_notification=check_notification(m)).wait()
|
||||||
|
uploading = bot.send_chat_action(chat_id, 'upload_document')
|
||||||
|
bot.send_document(chat_id, link).wait()
|
||||||
|
uploading.wait()
|
||||||
|
|
||||||
|
if doc['doc']['ext'] == 'doc' or doc['doc']['ext'] == 'docx' or doc['doc']['ext'] == 'rar' or \
|
||||||
|
doc['doc']['ext'] == 'ogg':
|
||||||
|
data = add_reply_info(m, user["first_name"], user["last_name"], ) + '<i>Документ</i>'
|
||||||
|
bot.send_message(chat_id, data, parse_mode='HTML',
|
||||||
|
disable_notification=check_notification(m)).wait()
|
||||||
|
uploading = bot.send_chat_action(chat_id, 'upload_document')
|
||||||
|
bot.send_document(chat_id, wget.download(requests.get(doc['doc']['url']).url)).wait()
|
||||||
|
uploading.wait()
|
||||||
|
|
||||||
|
else:
|
||||||
|
link = doc['doc']['url']
|
||||||
|
data = add_reply_info(m, user["first_name"], user["last_name"]) + \
|
||||||
|
'<i>Документ</i>\n<a href="{}">{}</a>'.format(link, doc['doc']['title'])
|
||||||
|
bot.send_message(chat_id, data, parse_mode='HTML',
|
||||||
|
disable_notification=check_notification(m)).wait()
|
||||||
|
|
||||||
|
if m['attachment']['type'] == 'sticker':
|
||||||
|
link = m['attachment']['sticker']['photo_512']
|
||||||
|
data = add_reply_info(m, user["first_name"], user["last_name"], ) + '<a href="{}">Стикер</a>'.format(link)
|
||||||
|
bot.send_message(chat_id, data, parse_mode='HTML',
|
||||||
|
disable_notification=check_notification(m)).wait()
|
||||||
|
# TODO: Wall Posts and comments
|
||||||
|
|
||||||
|
|
||||||
|
def add_reply_info(m, first_name, last_name):
|
||||||
|
if 'body' in m:
|
||||||
|
if 'chat_id' in m:
|
||||||
|
# TODO: Handle forwared messages
|
||||||
|
return '<a href="x{}.{}">​</a><b>{} {} @ {}:</b>\n{}\n'.format(m['uid'], m['chat_id'], first_name,
|
||||||
|
last_name, m['title'], m['body'].replace('<br>', '\n'))
|
||||||
|
else:
|
||||||
|
return '<a href="x{}.0">​</a><b>{} {}:</b>\n{}\n'.format(m['uid'], first_name, last_name,
|
||||||
|
m['body'].replace('<br>', '\n'))
|
||||||
|
else:
|
||||||
|
if 'chat_id' in m:
|
||||||
|
return '<a href="x{}.{}">​</a><b>{} {} @ {}:</b>\n'.format(m['uid'], m['chat_id'], first_name,
|
||||||
|
last_name, m['title'])
|
||||||
|
else:
|
||||||
|
return '<a href="x{}.0">​</a><b>{} {}:</b>\n'.format(m['uid'], first_name, last_name)
|
||||||
|
|
||||||
|
|
||||||
|
def check_notification(value):
|
||||||
|
if 'push_settings' in value:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def get_max_src(attachment):
|
||||||
|
if 'src_xxbig' in attachment:
|
||||||
|
return attachment['src_xxbig']
|
||||||
|
if 'src_xbig' in attachment:
|
||||||
|
return attachment['src_xbig']
|
||||||
|
if 'src_big' in attachment:
|
||||||
|
return attachment['src_big']
|
||||||
|
if 'src' in attachment:
|
||||||
|
return attachment['src']
|
||||||
|
|
||||||
|
|
||||||
class VkMessage:
|
class VkMessage:
|
||||||
def __init__(self, token):
|
def __init__(self, token):
|
||||||
self.session = get_session(token)
|
self.session = get_session(token)
|
||||||
@ -48,18 +167,7 @@ class VkMessage:
|
|||||||
else:
|
else:
|
||||||
messages = msgs[1:]
|
messages = msgs[1:]
|
||||||
for m in messages:
|
for m in messages:
|
||||||
if not m['out'] and m['body']:
|
res.append(m)
|
||||||
if 'chat_id' in m:
|
|
||||||
user = api.users.get(user_ids=m["uid"], fields=[])[0]
|
|
||||||
data = '<a href="x{}.{}.{}">​</a><b>{} {} @ {}:</b>\n{}'.format(
|
|
||||||
m["uid"], m['chat_id'], m['push_settings']['sound'], user["first_name"],
|
|
||||||
user["last_name"], m['title'], m["body"].replace('<br>', '\n'))
|
|
||||||
res.append(data)
|
|
||||||
else:
|
|
||||||
user = api.users.get(user_ids=m["uid"], fields=[])[0]
|
|
||||||
data = '<a href="x{}.0">​</a><b>{} {}:</b>\n{}'.format(
|
|
||||||
m["uid"], user["first_name"], user["last_name"], m["body"].replace('<br>', '\n'))
|
|
||||||
res.append(data)
|
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user