From 393fca6529d5de2a75bc8bf64f39dfd032fdaf76 Mon Sep 17 00:00:00 2001 From: Kylmakalle Date: Tue, 5 Sep 2017 00:52:31 +0300 Subject: [PATCH 1/4] Revert "Merge pull request #9 from Kylmakalle/webhook" This reverts commit 47fc72df23608639d1416ee38a4d897d0d11cfde, reversing changes made to ff27f0b2d791dfbb9fc4faa7fd96e5a09231b711. wrong merge reverting --- LICENSE | 5 ++--- Procfile | 1 + README.md | 9 ++++++--- app.json | 34 ++++++++++++++++++++++++++++++++++ bot.py | 20 ++++++-------------- credentials.py | 7 +++---- requirements.txt | 6 ++++++ runtime.txt | 1 + vk_messages.py | 5 +++-- 9 files changed, 62 insertions(+), 26 deletions(-) create mode 100644 Procfile create mode 100644 app.json create mode 100644 requirements.txt create mode 100644 runtime.txt diff --git a/LICENSE b/LICENSE index 2f77c35..1038e51 100644 --- a/LICENSE +++ b/LICENSE @@ -5,9 +5,8 @@ Copyright (c) 2017 Sergey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +to use, copy, modify, merge, publish, distribute, and to permit persons to whom +the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. diff --git a/Procfile b/Procfile new file mode 100644 index 0000000..e1d63e3 --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +bot: python3 bot.py diff --git a/README.md b/README.md index 6ca404a..a2877d0 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,17 @@ # tgvkbot Бот позволяет получать и отправлять сообщения VK находясь в Telegram +https://www.asergey.me/tgvkbot -Поддерживаются вебхуки и лонгполлинг, закомментируйте и раскомментируйте нужные строки +[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy) +[Ветка](https://github.com/Kylmakalle/tgvkbot/tree/webhook) для деплоя на локальной машине (поддерживаются вебхуки и лонгполлинг, закомментируйте и раскомментируйте нужные строки) + Настройка вебхуков по гайду от [@Groosha](https://www.gitbook.com/book/groosha/telegram-bot-lessons) +## Stay Tuned! -[Использование](https://www.asergey.me/tgvkbot/usage) - +_Полноценные комментарии к коду будут чуть позже_ diff --git a/app.json b/app.json new file mode 100644 index 0000000..2ad6f46 --- /dev/null +++ b/app.json @@ -0,0 +1,34 @@ +{ + "name": "tgvkbot", + "description": "Бот позволяет получать и отправлять сообщения VK находясь в Telegram", + "repository": "https://github.com/Kylmakalle/tgvkbot", + "keywords": ["vk", "bot", "telegram"], + "website": "https://asergey.me/tgvkbot/", + "buildpacks":[ + { + "url": "heroku/python" + } + ], + "env": { + "TELEGRAM_TOKEN": { + "description": "Telegram bot API токен от https://t.me/BotFather", + "value": "123456789:AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLL" + }, + "VK_APP": { + "description": "ID VK приложения из https://vk.com/apps?act=manage", + "required": true + } + }, + "addons": [ + { + "plan": "heroku-redis:hobby-dev", + "as": "Redis" + } + ], +"formation": { + "bot": { + "quantity": 1, + "size": "free" + } + } +} diff --git a/bot.py b/bot.py index 1c18e64..f32af82 100644 --- a/bot.py +++ b/bot.py @@ -13,13 +13,7 @@ import redis import vk import wget from PIL import Image - -from telebot import types - -import cherrypy - -from credentials import token, vk_app_id, bot_url, local_port - +from credentials import token, vk_app_id from vk_messages import VkMessage, VkPolling vk_threads = {} @@ -28,8 +22,7 @@ vk_dialogs = {} FILE_URL = 'https://api.telegram.org/file/bot{0}/{1}' -tokens_pool = redis.ConnectionPool(host='localhost', port=6379, db=0) -vk_tokens = redis.StrictRedis(connection_pool=tokens_pool) +vk_tokens = redis.from_url(os.environ.get("REDIS_URL")) currentchat = {} @@ -675,6 +668,7 @@ def reply_text(message): create_thread(message.from_user.id, code) bot.send_message(message.from_user.id, 'Вход выполнен в аккаунт {} {}!'.format(user['first_name'], user['last_name'])).wait() + bot.send_message(message.from_user.id, '[Использование](https://asergey.me/tgvkbot/usage/)', parse_mode='Markdown').wait() except: @@ -691,12 +685,10 @@ def reply_text(message): except Exception: bot.reply_to(message, 'Произошла неизвестная ошибка при отправке', parse_mode='Markdown').wait() - print('Error: {}'.format(traceback.format_exc())) -# bot.polling(none_stop=True) -class WebhookServer(object): - +bot.polling(none_stop=True) +"""class WebhookServer(object): # index равнозначно /, т.к. отсутствию части после ip-адреса (грубо говоря) @cherrypy.expose def index(self): @@ -714,4 +706,4 @@ if __name__ == '__main__': cherrypy.config.update( {'server.socket_host': '127.0.0.1', 'server.socket_port': local_port, 'engine.autoreload.on': False, 'log.screen': False}) - cherrypy.quickstart(WebhookServer(), '/', {'/': {}}) + cherrypy.quickstart(WebhookServer(), '/', {'/': {}})""" diff --git a/credentials.py b/credentials.py index 771a575..3bfa200 100644 --- a/credentials.py +++ b/credentials.py @@ -1,4 +1,3 @@ -token = '123456789:hciowedjejd092jjasdasdmdkpoaasd' -vk_app_id = "5678910" -bot_url = 'www.mybot.com' -local_port = 7777 \ No newline at end of file +import os +token = os.environ['TELEGRAM_TOKEN'] +vk_app_id = os.environ['VK_APP'] \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..b250be9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +pyTelegramBotAPI +vk +redis +Pillow +ujson +wget diff --git a/runtime.txt b/runtime.txt new file mode 100644 index 0000000..c91e43b --- /dev/null +++ b/runtime.txt @@ -0,0 +1 @@ +python-3.6.1 diff --git a/vk_messages.py b/vk_messages.py index 53e9d7c..f3c83b6 100644 --- a/vk_messages.py +++ b/vk_messages.py @@ -7,9 +7,10 @@ import vk import ujson import wget + logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.WARNING, filename='vk.log') -tokens_pool = redis.ConnectionPool(host='localhost', port=6379, db=0) -vk_tokens = redis.StrictRedis(connection_pool=tokens_pool) +vk_tokens = redis.from_url(os.environ.get("REDIS_URL")) + class VkPolling: From 022e96c09cdd24edd92cb78ce02f5547a7092102 Mon Sep 17 00:00:00 2001 From: Kylmakalle Date: Sat, 9 Sep 2017 22:25:00 +0300 Subject: [PATCH 2/4] Fixed chat chooser --- bot.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/bot.py b/bot.py index f32af82..d077286 100644 --- a/bot.py +++ b/bot.py @@ -1,18 +1,17 @@ -import logging import os import re +import redis import requests import telebot import threading import time import traceback import ujson -from telebot import types - -import redis import vk import wget from PIL import Image +from telebot import types + from credentials import token, vk_app_id from vk_messages import VkMessage, VkPolling @@ -176,7 +175,7 @@ def callback_buttons(call): bot.send_message(call.from_user.id, 'Вы в беседе {}'.format(chat['title']), parse_mode='HTML').wait() - currentchat[str(call.from_user.id)] = call.data + currentchat[str(call.from_user.id)] = {'title': chat['title'], 'id': 'group' + str(chat['chat_id'])} elif call.data.lstrip('-').isdigit(): session = VkMessage(vk_tokens.get(str(call.from_user.id))).session if '-' in call.data: From d6b730d6996308a76346f00149c9427b1d051004 Mon Sep 17 00:00:00 2001 From: Kylmakalle Date: Sun, 10 Sep 2017 02:37:12 +0300 Subject: [PATCH 3/4] Audio recieve support --- vk_messages.py | 48 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 38 insertions(+), 10 deletions(-) diff --git a/vk_messages.py b/vk_messages.py index f3c83b6..49a3b99 100644 --- a/vk_messages.py +++ b/vk_messages.py @@ -3,16 +3,14 @@ import os import redis import requests import time -import vk import ujson +import vk import wget - logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.WARNING, filename='vk.log') vk_tokens = redis.from_url(os.environ.get("REDIS_URL")) - class VkPolling: def __init__(self): self._running = True @@ -102,13 +100,43 @@ def attachment_handler(m, user, bot, chat_id, mainmessage=None): send_doc_link(attach, m, user, bot, chat_id, mainmessage) elif attach['type'] == 'audio': - data = add_user_info(m, user['first_name'], user[ - 'last_name']) + '🎧 {} - {}'.format( - attach['audio']['artist'].replace(' ', '%20'), - attach['audio']['title'].replace(' ', '%20'), attach['audio']['artist'], - attach['audio']['title']) + add_reply_info(m) - bot.send_message(chat_id, data, parse_mode='HTML', disable_web_page_preview=False, - disable_notification=check_notification(m), reply_to_message_id=mainmessage).wait() + headers = {'content-type': 'application/json'} + audio = requests.get('https://asergey.me/vkmusapi/', + json={'aid': attach['audio']['aid'], 'owner_id': attach['audio']['owner_id']}, + headers=headers) + try: + if audio.status_code == 200 and audio.json()['ok']: + audio_dict = audio.json() + data = add_user_info(m, user["first_name"], + user["last_name"]) + '🎧 Аудиозапись' + add_reply_info(m) + audio_msg = bot.send_message(chat_id, data, parse_mode='HTML', disable_web_page_preview=False, + disable_notification=check_notification(m), + reply_to_message_id=mainmessage).wait() + action = bot.send_chat_action(chat_id, 'upload_document') + bot.send_audio(chat_id, audio_dict['vk_response']['url'], + duration=audio_dict['vk_response']['duration'], + title=audio_dict['vk_response']['title'], + performer=audio_dict['vk_response']['artist'], + disable_notification=check_notification(m), + reply_to_message_id=audio_msg.message_id).wait() + action.wait() + else: + data = add_user_info(m, user['first_name'], user[ + 'last_name']) + '🎧 {} - {}'.format( + attach['audio']['artist'].replace(' ', '%20'), + attach['audio']['title'].replace(' ', '%20'), attach['audio']['artist'], + attach['audio']['title']) + add_reply_info(m) + bot.send_message(chat_id, data, parse_mode='HTML', disable_web_page_preview=False, + disable_notification=check_notification(m), reply_to_message_id=mainmessage).wait() + except Exception as e: + print(e) + data = add_user_info(m, user['first_name'], user[ + 'last_name']) + '🎧 {} - {}'.format( + attach['audio']['artist'].replace(' ', '%20'), + attach['audio']['title'].replace(' ', '%20'), attach['audio']['artist'], + attach['audio']['title']) + add_reply_info(m) + bot.send_message(chat_id, data, parse_mode='HTML', disable_web_page_preview=False, + disable_notification=check_notification(m), reply_to_message_id=mainmessage).wait() elif attach['type'] == 'doc': if attach['doc']['ext'] == 'gif': From b9f5c3156c6babe889fd40daeb51f2e1a1615bc5 Mon Sep 17 00:00:00 2001 From: Sergey Date: Sun, 8 Oct 2017 19:19:52 +0300 Subject: [PATCH 4/4] Update README.md --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index a2877d0..93e2884 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,12 @@ https://www.asergey.me/tgvkbot Настройка вебхуков по гайду от [@Groosha](https://www.gitbook.com/book/groosha/telegram-bot-lessons) +Бэкенд API для получения музыки через https://asergey.me/vkmusapi/ + +https://gist.github.com/Kylmakalle/e63902025c527ac3610989530f4fa417 + + + ## Stay Tuned!