Merge branch 'master' into webhook-dev

This commit is contained in:
Sergey 2018-02-07 22:21:20 +03:00 committed by GitHub
commit 60d090aee7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 103 additions and 28 deletions

View File

@ -5,9 +5,8 @@ Copyright (c) 2017 Sergey
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, and to permit persons to whom
copies of the Software, and to permit persons to whom the Software is the Software is furnished to do so, subject to the following conditions:
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. copies or substantial portions of the Software.

1
Procfile Normal file
View File

@ -0,0 +1 @@
bot: python3 bot.py

View File

@ -1,14 +1,23 @@
# tgvkbot # tgvkbot
Бот позволяет получать и отправлять сообщения VK находясь в Telegram Бот позволяет получать и отправлять сообщения 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) Настройка вебхуков по гайду от [@Groosha](https://www.gitbook.com/book/groosha/telegram-bot-lessons)
Бэкенд API для получения музыки через https://asergey.me/vkmusapi/
https://gist.github.com/Kylmakalle/e63902025c527ac3610989530f4fa417
[Использование](https://www.asergey.me/tgvkbot/usage)
## Stay Tuned!
олноценные комментарии к коду будут чуть позже_

34
app.json Normal file
View File

@ -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"
}
}
}

15
bot.py
View File

@ -1,5 +1,3 @@
import cherrypy
import logging
import os import os
import re import re
import redis import redis
@ -14,7 +12,7 @@ import wget
from PIL import Image from PIL import Image
from telebot import types from telebot import types
from credentials import token, vk_app_id, bot_url, local_port from credentials import token, vk_app_id
from vk_messages import VkMessage, VkPolling from vk_messages import VkMessage, VkPolling
vk_threads = {} vk_threads = {}
@ -25,8 +23,7 @@ VK_API_VERSION = '3.0'
FILE_URL = 'https://api.telegram.org/file/bot{0}/{1}' FILE_URL = 'https://api.telegram.org/file/bot{0}/{1}'
tokens_pool = redis.ConnectionPool(host='localhost', port=6379, db=0) vk_tokens = redis.from_url(os.environ.get("REDIS_URL"))
vk_tokens = redis.StrictRedis(connection_pool=tokens_pool)
currentchat = {} currentchat = {}
@ -683,6 +680,7 @@ def reply_text(message):
create_thread(message.from_user.id, code) create_thread(message.from_user.id, code)
bot.send_message(message.from_user.id, bot.send_message(message.from_user.id,
'Вход выполнен в аккаунт {} {}!'.format(user['first_name'], user['last_name'])).wait() 'Вход выполнен в аккаунт {} {}!'.format(user['first_name'], user['last_name'])).wait()
bot.send_message(message.from_user.id, '[Использование](https://asergey.me/tgvkbot/usage/)', bot.send_message(message.from_user.id, '[Использование](https://asergey.me/tgvkbot/usage/)',
parse_mode='Markdown').wait() parse_mode='Markdown').wait()
except: except:
@ -699,11 +697,10 @@ def reply_text(message):
except Exception: except Exception:
bot.reply_to(message, 'Произошла неизвестная ошибка при отправке', bot.reply_to(message, 'Произошла неизвестная ошибка при отправке',
parse_mode='Markdown').wait() parse_mode='Markdown').wait()
print('Error: {}'.format(traceback.format_exc()))
# bot.polling(none_stop=True) bot.polling(none_stop=True)
class WebhookServer(object): """class WebhookServer(object):
# index равнозначно /, т.к. отсутствию части после ip-адреса (грубо говоря) # index равнозначно /, т.к. отсутствию части после ip-адреса (грубо говоря)
@cherrypy.expose @cherrypy.expose
def index(self): def index(self):
@ -721,4 +718,4 @@ if __name__ == '__main__':
cherrypy.config.update( cherrypy.config.update(
{'server.socket_host': '127.0.0.1', 'server.socket_port': local_port, 'engine.autoreload.on': False, {'server.socket_host': '127.0.0.1', 'server.socket_port': local_port, 'engine.autoreload.on': False,
'log.screen': False}) 'log.screen': False})
cherrypy.quickstart(WebhookServer(), '/', {'/': {}}) cherrypy.quickstart(WebhookServer(), '/', {'/': {}})"""

View File

@ -1,4 +1,3 @@
token = '123456789:hciowedjejd092jjasdasdmdkpoaasd' import os
vk_app_id = "5678910" token = os.environ['TELEGRAM_TOKEN']
bot_url = 'www.mybot.com' vk_app_id = os.environ['VK_APP']
local_port = 7777

6
requirements.txt Normal file
View File

@ -0,0 +1,6 @@
pyTelegramBotAPI
vk
redis
Pillow
ujson
wget

1
runtime.txt Normal file
View File

@ -0,0 +1 @@
python-3.6.1

View File

@ -3,15 +3,14 @@ import os
import redis import redis
import requests import requests
import time import time
import vk
import ujson import ujson
import vk
import wget import wget
VK_POLLING_VERSION = '3.0' VK_POLLING_VERSION = '3.0'
logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.WARNING, filename='vk.log') 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.from_url(os.environ.get("REDIS_URL"))
vk_tokens = redis.StrictRedis(connection_pool=tokens_pool)
class VkPolling: class VkPolling:
@ -104,13 +103,43 @@ def attachment_handler(m, user, bot, chat_id, mainmessage=None):
send_doc_link(attach, m, user, bot, chat_id, mainmessage) send_doc_link(attach, m, user, bot, chat_id, mainmessage)
elif attach['type'] == 'audio': elif attach['type'] == 'audio':
data = add_user_info(m, user['first_name'], user[ headers = {'content-type': 'application/json'}
'last_name']) + '🎧 <a href="https://m.vk.com/audio?q={}%20-%20{}">{} - {}</a>'.format( audio = requests.get('https://asergey.me/vkmusapi/',
attach['audio']['artist'].replace(' ', '%20'), json={'aid': attach['audio']['aid'], 'owner_id': attach['audio']['owner_id']},
attach['audio']['title'].replace(' ', '%20'), attach['audio']['artist'], headers=headers)
attach['audio']['title']) + add_reply_info(m) try:
bot.send_message(chat_id, data, parse_mode='HTML', disable_web_page_preview=False, if audio.status_code == 200 and audio.json()['ok']:
disable_notification=check_notification(m), reply_to_message_id=mainmessage).wait() audio_dict = audio.json()
data = add_user_info(m, user["first_name"],
user["last_name"]) + '🎧 <i>Аудиозапись</i>' + 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']) + '🎧 <a href="https://m.vk.com/audio?q={}%20-%20{}">{} - {}</a>'.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']) + '🎧 <a href="https://m.vk.com/audio?q={}%20-%20{}">{} - {}</a>'.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': elif attach['type'] == 'doc':
if attach['doc']['ext'] == 'gif': if attach['doc']['ext'] == 'gif':