From 7c744a8d2351e7c78ad91bf8f565f16c4c9bf94b Mon Sep 17 00:00:00 2001 From: Kylmakalle Date: Mon, 10 Jul 2017 15:23:33 +0300 Subject: [PATCH 1/3] Revert "Merge branch 'master' into webhook" This reverts commit ca5e005caf3cdd6d55ee654f48d593f11e3b98d4, reversing changes made to 1c5866b88db034f7ee7ef043672a1421f4f45330. Reverting wrong merge --- LICENSE | 5 +++-- Procfile | 1 - README.md | 10 ++-------- app.json | 34 ---------------------------------- bot.py | 16 ++++++++++------ credentials.py | 7 ++++--- requirements.txt | 6 ------ runtime.txt | 1 - vk_messages.py | 5 ++--- 9 files changed, 21 insertions(+), 64 deletions(-) delete mode 100644 Procfile delete mode 100644 app.json delete mode 100644 requirements.txt delete mode 100644 runtime.txt diff --git a/LICENSE b/LICENSE index 1038e51..2f77c35 100644 --- a/LICENSE +++ b/LICENSE @@ -5,8 +5,9 @@ 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, 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, 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: 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 deleted file mode 100644 index e1d63e3..0000000 --- a/Procfile +++ /dev/null @@ -1 +0,0 @@ -bot: python3 bot.py diff --git a/README.md b/README.md index 11931b1..b0fdc09 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,10 @@ # tgvkbot Бот позволяет получать и отправлять сообщения VK находясь в Telegram - -[![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! - -_Полноценные комментарии к коду будут чуть позже_ \ No newline at end of file +[Использование](https://www.asergey.me/tgvkbot/usage) diff --git a/app.json b/app.json deleted file mode 100644 index 2ad6f46..0000000 --- a/app.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "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 52ea4d3..f014708 100644 --- a/bot.py +++ b/bot.py @@ -13,7 +13,9 @@ import time from PIL import Image from telebot import types -from credentials import token, vk_app_id +import cherrypy + +from credentials import token, vk_app_id, bot_url, local_port from vk_messages import VkMessage, VkPolling vk_threads = {} @@ -22,7 +24,8 @@ vk_dialogs = {} FILE_URL = 'https://api.telegram.org/file/bot{0}/{1}' -vk_tokens = redis.from_url(os.environ.get("REDIS_URL")) +tokens_pool = redis.ConnectionPool(host='localhost', port=6379, db=0) +vk_tokens = redis.StrictRedis(connection_pool=tokens_pool) currentchat = {} @@ -659,7 +662,6 @@ 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: @@ -676,9 +678,11 @@ 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): @@ -696,4 +700,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 3bfa200..771a575 100644 --- a/credentials.py +++ b/credentials.py @@ -1,3 +1,4 @@ -import os -token = os.environ['TELEGRAM_TOKEN'] -vk_app_id = os.environ['VK_APP'] \ No newline at end of file +token = '123456789:hciowedjejd092jjasdasdmdkpoaasd' +vk_app_id = "5678910" +bot_url = 'www.mybot.com' +local_port = 7777 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index b250be9..0000000 --- a/requirements.txt +++ /dev/null @@ -1,6 +0,0 @@ -pyTelegramBotAPI -vk -redis -Pillow -ujson -wget diff --git a/runtime.txt b/runtime.txt deleted file mode 100644 index c91e43b..0000000 --- a/runtime.txt +++ /dev/null @@ -1 +0,0 @@ -python-3.6.1 diff --git a/vk_messages.py b/vk_messages.py index 5a9a165..4755be0 100644 --- a/vk_messages.py +++ b/vk_messages.py @@ -7,10 +7,9 @@ import vk import ujson 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")) - +tokens_pool = redis.ConnectionPool(host='localhost', port=6379, db=0) +vk_tokens = redis.StrictRedis(connection_pool=tokens_pool) class VkPolling: From 084f8958974eb1aea6516fc45948e4fe4bbb281b Mon Sep 17 00:00:00 2001 From: Kylmakalle Date: Thu, 13 Jul 2017 15:21:16 +0300 Subject: [PATCH 2/3] Fixed supervisor cycling --- bot.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index f014708..32582dc 100644 --- a/bot.py +++ b/bot.py @@ -218,17 +218,19 @@ def thread_supervisor(): for uid in vk_tokens.scan_iter(): tries = 0 while check_thread(uid.decode("utf-8")): - if tries < 6: + if tries < 3: try: create_thread(uid.decode("utf-8"), vk_tokens.get(uid)) except: + time.sleep(10) tries = tries + 1 else: mark = types.InlineKeyboardMarkup() login = types.InlineKeyboardButton('ВХОД', url=link) mark.add(login) bot.send_message(uid.decode("utf-8"), 'Непредвиденная ошибка, требуется повторный логин ВК!', - parse_mode='HTML', reply_markup=mark) + parse_mode='HTML', reply_markup=mark).wait() + break time.sleep(60) From bd09c8b9c49f2466e18b8379b434761b3a468048 Mon Sep 17 00:00:00 2001 From: Kylmakalle Date: Thu, 13 Jul 2017 19:58:38 +0300 Subject: [PATCH 3/3] Removed reundant escape function, tg style notify for music --- bot.py | 8 -------- vk_messages.py | 2 +- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/bot.py b/bot.py index 32582dc..dcdd8fc 100644 --- a/bot.py +++ b/bot.py @@ -75,8 +75,6 @@ def request_user_dialogs(session, userid): dialogs = vk.API(session).messages.getDialogs(count=200) for chat in dialogs[1:]: if 'chat_id' in chat: - if chat['title'].replace('\\', ''): - chat['title'] = chat['title'].replace('\\', '') chat['title'] = replace_shields(chat['title']) order.append({'title': chat['title'], 'id': 'group' + str(chat['chat_id'])}) elif chat['uid'] > 0: @@ -136,8 +134,6 @@ def search_users(message, text): markup.add(types.InlineKeyboardButton('{} {}'.format(chat['first_name'], chat['last_name']), callback_data=str(chat['uid']))) elif chat['type'] == 'chat': - if chat['title'].replace('\\', ''): - chat['title'] = chat['title'].replace('\\', '') markup.add( types.InlineKeyboardButton(replace_shields(chat['title']), callback_data='group' + str(chat['chat_id']))) @@ -172,8 +168,6 @@ def callback_buttons(call): chat = vk.API(session).messages.getChat(chat_id=call.data.split('group')[1], fields=[]) bot.answer_callback_query(call.id, 'Вы в беседе {}'.format(replace_shields(chat['title']))).wait() - if chat['title'].replace('\\', ''): - chat['title'] = chat['title'].replace('\\', '') bot.send_message(call.from_user.id, 'Вы в беседе {}'.format(chat['title']), parse_mode='HTML').wait() @@ -275,8 +269,6 @@ def chat_command(message): if str(message.from_user.id) in currentchat: if 'group' in currentchat[str(message.from_user.id)]['id']: chat = currentchat[str(message.from_user.id)] - if chat['title'].replace('\\', ''): - chat['title'] = chat['title'].replace('\\', '') bot.send_message(message.from_user.id, 'Вы в беседе {}'.format(chat['title']), parse_mode='HTML').wait() diff --git a/vk_messages.py b/vk_messages.py index 4755be0..53e9d7c 100644 --- a/vk_messages.py +++ b/vk_messages.py @@ -102,7 +102,7 @@ def attachment_handler(m, user, bot, chat_id, mainmessage=None): elif attach['type'] == 'audio': data = add_user_info(m, user['first_name'], user[ - 'last_name']) + '🎵 {} - {}'.format( + 'last_name']) + '🎧 {} - {}'.format( attach['audio']['artist'].replace(' ', '%20'), attach['audio']['title'].replace(' ', '%20'), attach['audio']['artist'], attach['audio']['title']) + add_reply_info(m)