Merge remote-tracking branch 'refs/remotes/origin/webhook' into webhook-dev
This commit is contained in:
commit
f1659018df
@ -1,10 +1,14 @@
|
|||||||
# tgvkbot
|
# tgvkbot
|
||||||
Бот позволяет получать и отправлять сообщения VK находясь в Telegram
|
Бот позволяет получать и отправлять сообщения VK находясь в Telegram
|
||||||
|
|
||||||
|
|
||||||
Поддерживаются вебхуки и лонгполлинг, закомментируйте и раскомментируйте нужные строки
|
Поддерживаются вебхуки и лонгполлинг, закомментируйте и раскомментируйте нужные строки
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Настройка вебхуков по гайду от [@Groosha](https://www.gitbook.com/book/groosha/telegram-bot-lessons)
|
Настройка вебхуков по гайду от [@Groosha](https://www.gitbook.com/book/groosha/telegram-bot-lessons)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[Использование](https://www.asergey.me/tgvkbot/usage)
|
[Использование](https://www.asergey.me/tgvkbot/usage)
|
||||||
|
|
||||||
|
44
bot.py
44
bot.py
@ -1,21 +1,25 @@
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import redis
|
|
||||||
import requests
|
import requests
|
||||||
import telebot
|
import telebot
|
||||||
import threading
|
import threading
|
||||||
|
import time
|
||||||
import traceback
|
import traceback
|
||||||
import ujson
|
import ujson
|
||||||
|
from telebot import types
|
||||||
|
|
||||||
|
import redis
|
||||||
import vk
|
import vk
|
||||||
import wget
|
import wget
|
||||||
import time
|
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
from telebot import types
|
from telebot import types
|
||||||
|
|
||||||
import cherrypy
|
import cherrypy
|
||||||
|
|
||||||
from credentials import token, vk_app_id, bot_url, local_port
|
from credentials import token, vk_app_id, bot_url, local_port
|
||||||
|
|
||||||
from vk_messages import VkMessage, VkPolling
|
from vk_messages import VkMessage, VkPolling
|
||||||
|
|
||||||
vk_threads = {}
|
vk_threads = {}
|
||||||
@ -75,8 +79,6 @@ def request_user_dialogs(session, userid):
|
|||||||
dialogs = vk.API(session).messages.getDialogs(count=200)
|
dialogs = vk.API(session).messages.getDialogs(count=200)
|
||||||
for chat in dialogs[1:]:
|
for chat in dialogs[1:]:
|
||||||
if 'chat_id' in chat:
|
if 'chat_id' in chat:
|
||||||
if chat['title'].replace('\\', ''):
|
|
||||||
chat['title'] = chat['title'].replace('\\', '')
|
|
||||||
chat['title'] = replace_shields(chat['title'])
|
chat['title'] = replace_shields(chat['title'])
|
||||||
order.append({'title': chat['title'], 'id': 'group' + str(chat['chat_id'])})
|
order.append({'title': chat['title'], 'id': 'group' + str(chat['chat_id'])})
|
||||||
elif chat['uid'] > 0:
|
elif chat['uid'] > 0:
|
||||||
@ -89,8 +91,16 @@ def request_user_dialogs(session, userid):
|
|||||||
for g in group_ids:
|
for g in group_ids:
|
||||||
positive_group_ids.append(str(g)[1:])
|
positive_group_ids.append(str(g)[1:])
|
||||||
|
|
||||||
|
if users_ids:
|
||||||
users = vk.API(session).users.get(user_ids=users_ids, fields=['first_name', 'last_name', 'uid'])
|
users = vk.API(session).users.get(user_ids=users_ids, fields=['first_name', 'last_name', 'uid'])
|
||||||
|
else:
|
||||||
|
users = []
|
||||||
|
|
||||||
|
if positive_group_ids:
|
||||||
groups = vk.API(session).groups.getById(group_ids=positive_group_ids, fields=[])
|
groups = vk.API(session).groups.getById(group_ids=positive_group_ids, fields=[])
|
||||||
|
else:
|
||||||
|
groups = []
|
||||||
|
|
||||||
for output in order:
|
for output in order:
|
||||||
if output['title'] == ' ... ' or not output['title']:
|
if output['title'] == ' ... ' or not output['title']:
|
||||||
if output['id'] > 0:
|
if output['id'] > 0:
|
||||||
@ -136,8 +146,6 @@ def search_users(message, text):
|
|||||||
markup.add(types.InlineKeyboardButton('{} {}'.format(chat['first_name'], chat['last_name']),
|
markup.add(types.InlineKeyboardButton('{} {}'.format(chat['first_name'], chat['last_name']),
|
||||||
callback_data=str(chat['uid'])))
|
callback_data=str(chat['uid'])))
|
||||||
elif chat['type'] == 'chat':
|
elif chat['type'] == 'chat':
|
||||||
if chat['title'].replace('\\', ''):
|
|
||||||
chat['title'] = chat['title'].replace('\\', '')
|
|
||||||
markup.add(
|
markup.add(
|
||||||
types.InlineKeyboardButton(replace_shields(chat['title']),
|
types.InlineKeyboardButton(replace_shields(chat['title']),
|
||||||
callback_data='group' + str(chat['chat_id'])))
|
callback_data='group' + str(chat['chat_id'])))
|
||||||
@ -172,8 +180,6 @@ def callback_buttons(call):
|
|||||||
chat = vk.API(session).messages.getChat(chat_id=call.data.split('group')[1], fields=[])
|
chat = vk.API(session).messages.getChat(chat_id=call.data.split('group')[1], fields=[])
|
||||||
bot.answer_callback_query(call.id,
|
bot.answer_callback_query(call.id,
|
||||||
'Вы в беседе {}'.format(replace_shields(chat['title']))).wait()
|
'Вы в беседе {}'.format(replace_shields(chat['title']))).wait()
|
||||||
if chat['title'].replace('\\', ''):
|
|
||||||
chat['title'] = chat['title'].replace('\\', '')
|
|
||||||
bot.send_message(call.from_user.id,
|
bot.send_message(call.from_user.id,
|
||||||
'<i>Вы в беседе {}</i>'.format(chat['title']),
|
'<i>Вы в беседе {}</i>'.format(chat['title']),
|
||||||
parse_mode='HTML').wait()
|
parse_mode='HTML').wait()
|
||||||
@ -213,22 +219,31 @@ def check_thread(uid):
|
|||||||
|
|
||||||
|
|
||||||
# Creating VkPolling threads and dialogs info after bot's reboot/exception using existing tokens
|
# Creating VkPolling threads and dialogs info after bot's reboot/exception using existing tokens
|
||||||
def thread_supervisor():
|
def thread_reviver(uid):
|
||||||
while True:
|
|
||||||
for uid in vk_tokens.scan_iter():
|
|
||||||
tries = 0
|
tries = 0
|
||||||
while check_thread(uid.decode("utf-8")):
|
while check_thread(uid.decode("utf-8")):
|
||||||
if tries < 6:
|
if tries < 4:
|
||||||
try:
|
try:
|
||||||
create_thread(uid.decode("utf-8"), vk_tokens.get(uid))
|
create_thread(uid.decode("utf-8"), vk_tokens.get(uid))
|
||||||
except:
|
except:
|
||||||
|
time.sleep(10)
|
||||||
tries = tries + 1
|
tries = tries + 1
|
||||||
else:
|
else:
|
||||||
mark = types.InlineKeyboardMarkup()
|
mark = types.InlineKeyboardMarkup()
|
||||||
login = types.InlineKeyboardButton('ВХОД', url=link)
|
login = types.InlineKeyboardButton('ВХОД', url=link)
|
||||||
mark.add(login)
|
mark.add(login)
|
||||||
bot.send_message(uid.decode("utf-8"), '<b>Непредвиденная ошибка, требуется повторный логин ВК!</b>',
|
bot.send_message(uid.decode("utf-8"), '<b>Непредвиденная ошибка, требуется повторный логин ВК!</b>',
|
||||||
parse_mode='HTML', reply_markup=mark)
|
parse_mode='HTML', reply_markup=mark).wait()
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
|
def thread_supervisor():
|
||||||
|
while True:
|
||||||
|
for uid in vk_tokens.scan_iter():
|
||||||
|
reviver_thread = threading.Thread(name='reviver' + str(uid.decode('utf-8')), target=thread_reviver,
|
||||||
|
args=(uid,))
|
||||||
|
reviver_thread.setDaemon(True)
|
||||||
|
reviver_thread.start()
|
||||||
time.sleep(60)
|
time.sleep(60)
|
||||||
|
|
||||||
|
|
||||||
@ -273,8 +288,6 @@ def chat_command(message):
|
|||||||
if str(message.from_user.id) in currentchat:
|
if str(message.from_user.id) in currentchat:
|
||||||
if 'group' in currentchat[str(message.from_user.id)]['id']:
|
if 'group' in currentchat[str(message.from_user.id)]['id']:
|
||||||
chat = currentchat[str(message.from_user.id)]
|
chat = currentchat[str(message.from_user.id)]
|
||||||
if chat['title'].replace('\\', ''):
|
|
||||||
chat['title'] = chat['title'].replace('\\', '')
|
|
||||||
bot.send_message(message.from_user.id,
|
bot.send_message(message.from_user.id,
|
||||||
'<i>Вы в беседе {}</i>'.format(chat['title']),
|
'<i>Вы в беседе {}</i>'.format(chat['title']),
|
||||||
parse_mode='HTML').wait()
|
parse_mode='HTML').wait()
|
||||||
@ -683,6 +696,7 @@ def reply_text(message):
|
|||||||
|
|
||||||
# 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):
|
||||||
|
@ -102,7 +102,7 @@ def attachment_handler(m, user, bot, chat_id, mainmessage=None):
|
|||||||
|
|
||||||
elif attach['type'] == 'audio':
|
elif attach['type'] == 'audio':
|
||||||
data = add_user_info(m, user['first_name'], user[
|
data = add_user_info(m, user['first_name'], user[
|
||||||
'last_name']) + '🎵 <a href="https://m.vk.com/audio?q={}%20-%20{}">{} - {}</a>'.format(
|
'last_name']) + '🎧 <a href="https://m.vk.com/audio?q={}%20-%20{}">{} - {}</a>'.format(
|
||||||
attach['audio']['artist'].replace(' ', '%20'),
|
attach['audio']['artist'].replace(' ', '%20'),
|
||||||
attach['audio']['title'].replace(' ', '%20'), attach['audio']['artist'],
|
attach['audio']['title'].replace(' ', '%20'), attach['audio']['artist'],
|
||||||
attach['audio']['title']) + add_reply_info(m)
|
attach['audio']['title']) + add_reply_info(m)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user