Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from telethon import TelegramClient, sync, events, errors
- import telebot
- from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove
- import psycopg2
- from psycopg2 import sql
- from contextlib import closing
- from telethon.tl.functions.messages import ImportChatInviteRequest
- from telethon.tl.functions.channels import LeaveChannelRequest, JoinChannelRequest
- import threading
- admins_list = '@vladshtatskiy'
- name = 'sessionforbot'
- api_id = 1347648
- api_hash = 'ad562ba1f498cb44df5697284a1294eb'
- client = TelegramClient(name, api_id, api_hash)
- TELEGRAM_TOKEN = '1116792075:AAEIz2JYKjJVr7YefnRC5lcD1CpOO7uOCoo'
- bot = telebot.TeleBot(TELEGRAM_TOKEN)
- username, password, host, dbname = 'bsapqeihvqgfxg','116305072a743138687b0b27ba1871da04958fe4ae50c979071893d8c7f892f6','ec2-54-247-118-139.eu-west-1.compute.amazonaws.com','d4jckgkr1ri9ef'
- print('Успешно запущено.')
- def reload_tables(): #Создания всех таблиц в базе данных (по умолчанию не используется)
- with closing(psycopg2.connect('postgres://{0}:{1}@{2}/{3}'.format(username, password, host, dbname))) as conn:
- with conn.cursor() as c:
- try:
- c.execute('DROP TABLE users')
- c.execute('DROP TABLE user_2_word')
- c.execute('DROP SEQUENCE user_2_word_sequence')
- c.execute('DROP TABLE key_word')
- c.execute('DROP TABLE channel')
- c.execute('DROP TABLE group_name')
- c.execute('DROP SEQUENCE group_name_sequence')
- except:pass
- conn.commit()
- c.execute('CREATE TABLE IF NOT EXISTS users (user_id INTEGER);')
- print('Таблица users создана успешно.')
- c.execute('CREATE TABLE IF NOT EXISTS user_2_word (id INTEGER, word TEXT, user_id INTEGER, session INTEGER, channel TEXT, PRIMARY KEY (id));')
- c.execute('CREATE SEQUENCE IF NOT EXISTS user_2_word_sequence start 1;')
- print('Таблица user_2_word создана успешно.')
- c.execute('CREATE TABLE IF NOT EXISTS key_word (word TEXT UNIQUE);')
- print('Таблица key_word создана успешно.')
- c.execute('CREATE TABLE IF NOT EXISTS channel (channel TEXT UNIQUE);')
- print('Таблица channel создана успешно.')
- c.execute('CREATE TABLE IF NOT EXISTS group_name (id INTEGER, user_id INTEGER, group_name TEXT, session INTEGER, PRIMARY KEY (id));')
- c.execute('CREATE SEQUENCE IF NOT EXISTS group_name_sequence start 1;')
- print('Таблица group_name создана успешно.')
- conn.commit()
- print('STATUS: SUCCESS')
- def checkOnNewUser(message): #Проверка нового юзера
- with closing(psycopg2.connect('postgres://{0}:{1}@{2}/{3}'.format(username,password,host,dbname))) as conn:
- with conn.cursor() as c:
- try:
- c.execute('SELECT user_id FROM users WHERE user_id = {0}'.format(message.chat.id))
- for row in c:
- user_id = row
- if user_id == None:
- c.execute('INSERT INTO users (user_id) VALUES ({0});'.format(message.chat.id))
- conn.commit()
- except:
- c.execute('INSERT INTO users (user_id) VALUES ({0});'.format(message.chat.id))
- conn.commit()
- # async def track_chat(chat_name, chat_id):
- # print('Работает...')
- # async with TelegramClient(name, api_id, api_hash) as client:
- #
- async def checkValidate_username(username): #Проверка приглашения в канал на валидность (логин)
- try:
- check = await client.get_entity(username)
- return True
- except errors.rpcerrorlist.InviteHashInvalidError as e:
- return False
- except errors.rpcerrorlist.FloodWaitError as e:
- print(str(e))
- return 'flooderror'
- except errors.rpcerrorlist.UserAlreadyParticipantError:
- return True
- except:
- return False
- await client.disconnect()
- async def checkValidate_link(link): #Проверка приглашения в канал на валидность (ссылка)
- hash = link[link.find('t.me/joinchat/') + 14:]
- try:
- await client(ImportChatInviteRequest(hash))
- check = await client.get_entity(link)
- return True
- except errors.rpcerrorlist.InviteHashInvalidError as e:
- return False
- except errors.rpcerrorlist.FloodWaitError as e:
- print(str(e))
- return 'flooderror'
- except errors.rpcerrorlist.UserAlreadyParticipantError:
- return True
- except errors.rpcerrorlist.InviteHashEmptyError:
- return False
- except:
- return False
- await client.disconnect()
- async def get_channel_name_telethon(channelIdLink): #Проверка приглашения в канал на валидность (ссылка)
- try:
- check = await client.get_entity(channelIdLink)
- check = check.to_dict()['title']
- return check
- except Exception as e:
- print(str(e))
- await client.disconnect()
- def get_session(c, conn, chat_id): # получить идентификатор сессии
- c.execute('SELECT session FROM user_2_word WHERE user_id = {0}'.format(chat_id))
- try:
- session = c.fetchall()[-1][0]
- except IndexError:
- session = None
- return session
- def channel_add(c, conn, channel_name): # добавить канал в таблицу channel
- try:
- c.execute('INSERT INTO channel (channel) VALUES ({0})'.format(f"'{channel_name}'"))
- conn.commit()
- except:pass
- def getword_u2w(c, conn, user_id): # получить word (слово) из таблицы user_2_word
- c.execute('SELECT word FROM user_2_word WHERE user_id = {0}'.format(user_id))
- word = c.fetchall()[-1][0]
- if str(word) == 'None':
- id = get_id_u2w(c, conn, user_id)
- c.execute('SELECT word FROM user_2_word WHERE user_id = {0} and id = {1}'.format(user_id, int(id)-1))
- word = c.fetchall()[-1][0]
- return word
- def get_id_u2w(c, conn, user_id):
- c.execute('SELECT id FROM user_2_word WHERE user_id = {0}'.format(user_id))
- id = c.fetchall()[-1][0]
- return id
- def insert_word(chat_id, word):
- with closing(psycopg2.connect('postgres://{0}:{1}@{2}/{3}'.format(username,password,host,dbname))) as conn:
- with conn.cursor() as c:
- try:
- c.execute('INSERT INTO key_word (word) VALUES ({0});'.format(f"'{word}'"))
- except:
- pass
- conn.commit()
- c.execute('INSERT INTO user_2_word (id, word, user_id, channel, session) VALUES ({0}, {1}, {2}, {3}, {4});'.format("nextval('user_2_word_sequence')" ,"'None'", chat_id, "'None'", 0))
- conn.commit()
- id = get_id_u2w(c, conn, chat_id)
- c.execute('UPDATE user_2_word SET session = {0}, word = {1} WHERE user_id = {2} and id = {3}'.format(id, f"'{word}'", chat_id, id))
- conn.commit()
- def get_words_u2w(c, chat_id, session):
- c.execute('SELECT word FROM user_2_word WHERE user_id = {0} and session = {1}'.format(chat_id, session))
- words = str()
- for row in c:
- words = words + '- ' + str(row[0]) + '\n'
- return words
- def get_channels_u2w(c, chat_id, session):
- c.execute('SELECT channel FROM user_2_word WHERE user_id = {0} and session = {1}'.format(chat_id, session))
- channels = str()
- for row in c:
- channels = channels + '- ' + str(row[0]) + '\n'
- return channels
- def get_channels_name(c, chat_id, session):
- client.start()
- c.execute('SELECT channel FROM user_2_word WHERE user_id = {0} and session = {1}'.format(chat_id, session))
- channels = str()
- for row in c:
- getname = client.loop.run_until_complete(get_channel_name_telethon(row[0]))
- channels = channels + '- ' + str(getname) + '\n'
- client.disconnect()
- return channels
- @bot.callback_query_handler(func=lambda call: True)
- def callback_query_handler(call):
- with closing(psycopg2.connect('postgres://{0}:{1}@{2}/{3}'.format(username,password,host,dbname))) as conn:
- with conn.cursor() as c:
- chat_id = call.message.chat.id
- if call.data[:12] == 'correct_lvl0':
- lastmessage_id = call.data[12:]
- bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text='❌')
- msg = bot.send_message(chat_id=chat_id, text='Укажи слово для поиска.')
- bot.register_next_step_handler(msg, lvl0_text)
- elif call.data[:17] == 'correct_lvl_loop0':
- lastmessage_id = call.data[17:]
- bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text='❌')
- word = getword_u2w(c, conn, chat_id)
- next_markup = InlineKeyboardMarkup()
- next_markup.add(InlineKeyboardButton('Пропустить', callback_data='finnaly_next'+str(call.message.message_id)))
- msg = bot.send_message(chat_id=chat_id, text='Хочешь отслеживать в добавленных выше каналах другие слова кроме <{0}>? Введите еще слово или нажмите ДАЛЕЕ для продолжения.'.format(word), reply_markup=next_markup)
- bot.register_next_step_handler(msg, lvl0_loop_text)
- elif call.data[:12] == 'correct_lvl1':
- lastmessage_id = call.data[12:]
- bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text='❌')
- msg = bot.send_message(chat_id=chat_id, text='Отправь мне ссылку на приглашение в канал/логин канала, который хочешь отслеживать.')
- bot.register_next_step_handler(msg, lvl1_text)
- elif call.data[:12] == 'correct_lvl2' or call.data[:12] == 'continue_set':
- lastmessage_id = call.data[12:]
- if call.data[:12] == 'continue_set':
- symbol = '➡️'
- else:
- symbol = '❌'
- bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text=symbol)
- word = getword_u2w(c, conn, chat_id)
- next_markup = InlineKeyboardMarkup()
- next_markup.add(InlineKeyboardButton('Пропустить', callback_data='finnaly_next'+str(call.message.message_id)))
- msg = bot.send_message(chat_id=chat_id, text='Отправь мне ссылку на приглашение в ДРУГОЙ канал/логин ДРУГОГО канала, если хочешь отслеживать и его на появление слова <{0}> или нажмите пропустить для продолжения.'.format(word), reply_markup=next_markup)
- bot.register_next_step_handler(msg, lvl2_text)
- elif call.data[:4] == 'lvl0': # (ПОЛУЧАЕТ СЛОВО)
- word = call.data[4:].split('edocroftilsp0')[0]
- lastmessage_id = call.data[4:].split('edocroftilsp0')[1]
- bot.edit_message_text(chat_id = chat_id, message_id = lastmessage_id, text = '✅')
- insert_word(chat_id, word)
- msg = bot.send_message(chat_id=chat_id, text='Отправь мне ссылку на приглашение в канал/логин канала, который хочешь отслеживать.')
- bot.register_next_step_handler(msg, lvl1_text)
- elif call.data[:9] == 'lvl_loop0': # укажи мне ссылку на канал (lvl0_loop - lvl1) (ПОЛУЧАЕТ СЛОВО)
- word = call.data[9:].split('edocroftilsp0')[0]
- lastmessage_id = call.data[9:].split('edocroftilsp0')[1]
- bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text='✅')
- session = get_session(c, conn, chat_id)
- id = get_id_u2w(c, conn, chat_id)
- c.execute('UPDATE user_2_word SET word = {0} WHERE session = {1} and user_id = {2} and id = {3}'.format(f"'{word}'", session, chat_id, id))
- try:
- c.execute('INSERT INTO key_word (word) VALUES ({0});'.format(f"'{word}'"))
- except:
- pass
- conn.commit()
- next_markup = InlineKeyboardMarkup()
- next_markup.row_width = 1
- next_markup.add(InlineKeyboardButton('Запустить отслеживание', callback_data='finnaly_next'),
- InlineKeyboardButton('Продолжить настройку', callback_data='continue_set'+str(call.message.message_id+1)))
- words = get_words_u2w(c, chat_id, session)
- channels_name = get_channels_name(c, chat_id, session)
- text = f'Отлично! Ты добавил следующие слова:\n{words}\n\nДля отслеживания в следующих каналах/чатах:\n\n{channels_name}\nМожем остановиться на этих данных и начать отслеживание или продолжим добавление каналов или слов? '
- bot.send_message(chat_id=chat_id, text=text, reply_markup=next_markup)
- conn.commit()
- elif call.data[:4] == 'lvl1': # отправь мне ссылку на приглашение в другой канал (lvl1 - lvl2) (ПОЛУЧАЕТ ССЫЛКУ НА КАНАЛ/ЛОГИН КАНАЛА)
- channel = call.data[4:].split('edocroftilsp0')[0]
- lastmessage_id = call.data[4:].split('edocroftilsp0')[1]
- bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text='✅')
- id = get_id_u2w(c, conn, chat_id)
- session = get_session(c, conn, chat_id)
- c.execute('UPDATE user_2_word SET channel = {0} WHERE user_id = {1} and session = {2} and id = {3}'.format(f"'{channel}'", chat_id, session, id))
- channel_add(c, conn, channel)
- next_markup = InlineKeyboardMarkup()
- next_markup.row_width = 1
- next_markup.add(InlineKeyboardButton('Запустить отслеживание', callback_data='finnaly_next'+str(call.message.message_id)), InlineKeyboardButton('Продолжить настройку', callback_data='continue_set'+str(call.message.message_id+1)))
- words = get_words_u2w(c, chat_id, session)
- channels_name = get_channels_name(c, chat_id, session)
- text = f'Отлично! Ты добавил следующие слова:\n\n{words}\nДля отслеживания в следующих каналах/чатах:\n\n{channels_name}\nМожем остановиться на этих данных и начать отслеживание или продолжим добавление каналов или слов? '
- bot.send_message(chat_id=chat_id, text=text, reply_markup=next_markup)
- conn.commit()
- elif call.data[:4] == 'lvl2': # добавить другие слова (lvl2 - lvl3) (ПОЛУЧАЕТ ССЫЛКУ НА ДРУГОЙ КАНАЛ/ЛОГИН ДРУГОГО КАНАЛА)
- channel = call.data[4:].split('edocroftilsp0')[0]
- lastmessage_id = call.data[4:].split('edocroftilsp0')[1]
- bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text='✅')
- session = get_session(c, conn, chat_id)
- c.execute('INSERT INTO user_2_word (id, word, user_id, channel, session) VALUES ({0}, {1}, {2}, {3}, {4});'.format("nextval('user_2_word_sequence')" ,"'None'", chat_id, f"'{channel}'", session))
- channel_add(c, conn, channel)
- conn.commit()
- next_markup = InlineKeyboardMarkup()
- next_markup.add(InlineKeyboardButton('Пропустить', callback_data='finnaly_next'+str(call.message.message_id)))
- word = getword_u2w(c, conn, chat_id)
- id = int(get_id_u2w(c, conn, chat_id))-1
- if word == 'None':
- c.execute('SELECT word FROM user_2_word WHERE user_id = {0} and id = {1}'.format(chat_id, id))
- for row in c:
- word = row
- try:
- word = word[0]
- except:
- word = None
- msg = bot.send_message(chat_id=chat_id, text='Хочешь отслеживать в добавленных выше каналах другие слова кроме <{0}>? Введите еще слово или нажмите пропустить для продолжения.'.format(word), reply_markup=next_markup)
- bot.register_next_step_handler(msg, lvl0_loop_text)
- elif (call.data[:12] == 'finnaly_next' and call.data[:13] != 'finnaly_next_') or call.data[:20] == 'finnaly_next_correct': # назвать группу для отслеживания / коррекция
- if call.data[:12] == 'finnaly_next' and call.data[:13] != 'finnaly_next_':
- last_id = int(call.data[12:])+1
- elif call.data[:20] == 'finnaly_next_correct':
- last_id = int(call.data[20:])+1
- bot.edit_message_text(chat_id=chat_id, message_id=last_id, text='✅')
- next_markup = InlineKeyboardMarkup()
- next_markup.add(InlineKeyboardButton('Пропустить', callback_data='finnaly_next_next'+'edocroftilsp0'+str(call.message.message_id+1)))
- msg = bot.send_message(chat_id=call.message.chat.id,
- text='Можешь назвать эту группу отслеживания для удобства( например "Туризм" или "Tesla"). Введи имя ниже или жми ПРОПУСТИТЬ',
- reply_markup=next_markup)
- bot.clear_step_handler(msg)
- bot.register_next_step_handler(msg, group_name_text)
- elif call.data[:17] == 'finnaly_next_next': # назвать группу для отслеживания (далее)
- group_name = call.data[17:].split('edocroftilsp0')[0]
- last_id = call.data[17:].split('edocroftilsp0')[1]
- bot.edit_message_text(chat_id=chat_id, message_id=last_id, text='✅')
- if group_name == '':
- c.execute('SELECT session FROM group_name WHERE user_id = {0}'.format(chat_id))
- try:
- session = c.fetchall()[-1][0]
- except:
- session = 0
- c.execute('SELECT id FROM group_name WHERE user_id = {0} and session = {1}'.format(chat_id, session))
- try:
- id = c.fetchall()[-1][0]
- except:
- id = 0
- group_name = 'ID_' + str(int(id) + 1)
- session = get_session(c, conn, chat_id)
- words = get_words_u2w(c, chat_id, session)
- c.execute('INSERT INTO group_name (id, user_id, group_name, session) VALUES ({0}, {1}, {2}, {3})'.format("nextval('group_name_sequence')", chat_id, f"'{group_name}'", session))
- settings_markup = InlineKeyboardMarkup()
- settings_markup.add(InlineKeyboardButton('Настройки', callback_data='settings'))
- channels = get_channels_name(c, chat_id, session)
- text = f'Поздравляю! Ты окончил настройку. Я отслеживаю каналы:\n\n{channels}\n на появление слов: \n\n{words}\nВ этот чат я буду присылать тебе сообщения из отслеживаемых каналов если там встретится нужное тебе слово. Для изменения каналов отслеживания и слов нажми НАСТРОЙКИ.'
- msg = bot.send_message(chat_id=chat_id,text=text,reply_markup=settings_markup)
- bot.register_next_step_handler(msg, command_handler_start)
- elif call.data[:8] == 'settings':
- session = get_session(c, conn, chat_id)
- if session == None:
- add_new = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
- add_new.add(KeyboardButton('Создать'))
- msg = bot.send_message(chat_id=chat_id, text='У Вас нет активных отслеживаний.', parse_mode='HTML',reply_markup=add_new)
- bot.register_next_step_handler(msg, start)
- else:
- id = call.data[8:]
- if id == '':
- id = 1
- c.execute('SELECT * FROM group_name WHERE user_id = {0}'.format(chat_id))
- markup = InlineKeyboardMarkup()
- group_name = str()
- for row in c:
- if str(row[0]) == str(id):
- markup.add(InlineKeyboardButton('Изменить', callback_data='edit' + str(row[0])))
- group_name = row[2]
- else:
- markup.add(InlineKeyboardButton(str(row[2]), callback_data='settings' + str(row[0])))
- c.execute('SELECT session FROM group_name WHERE user_id = {0} and id = {1}'.format(chat_id, id))
- session = c.fetchall()[-1][0]
- words = get_words_u2w(c, chat_id, session)
- channels = get_channels_name(c, chat_id, session)
- bot.edit_message_text(chat_id=chat_id, message_id = call.message.message_id,
- text=f'Настройки групп отслеживания:\n\n`{group_name}`\n\n{channels}\nОтслеживается по словам:\n\n{words}',
- reply_markup=markup, parse_mode='Markdown')
- elif call.data[:4] == 'edit':
- id = call.data[4:]
- session = 1
- c.execute('SELECT * FROM group_name WHERE user_id = {0}'.format(chat_id))
- for row in c:
- if str(row[0]) == id and str(row[1]) == str(chat_id):
- session = row[3]
- group_name = row[2]
- break
- words = get_words_u2w(c, chat_id, session)
- channels = get_channels_u2w(c, chat_id, session)
- markup = InlineKeyboardMarkup()
- markup.row_width = 1
- markup.add(InlineKeyboardButton('Удалить канал отслеживания', callback_data = 'remove_channel_list'+str(id)),
- InlineKeyboardButton('Добавить канал отслеживания', callback_data = 'add_channel'+str(id)),
- InlineKeyboardButton('Удалить слово отслеживания', callback_data = 'remove_word'+str(id)),
- InlineKeyboardButton('Добавить слово отслеживания', callback_data = 'add_word'+str(id)),
- InlineKeyboardButton('Удалить ГРУППУ отслеживания', callback_data = 'remove_group'+str(id)),
- InlineKeyboardButton('Запустить', callback_data = 'start_track'+str(id)))
- bot.send_message(chat_id=chat_id, text=f'Настройки группы отслеживания (`{group_name}`):\n\n{channels}\n\nОтслеживается по словам:\n\n{words}',reply_markup=markup, parse_mode='Markdown')
- elif call.data[:19] == 'remove_channel_list':
- channel_id = call.data[19:]
- markup = InlineKeyboardMarkup()
- c.execute(
- 'SELECT channel FROM user_2_word WHERE user_id = {0} and session = {1} and id = {2}'.format(chat_id,session,id))
- channels = str()
- for row in c:
- markup.add(InlineKeyboardButton('', callback_data = 'remove_channel'+str(id)+','+str(row[0])))
- bot.send_message(chat_id = chat_id, text='Какой канал отслеживания вы хотите удалить?', reply_markup = markup)
- elif call.data[:11] == 'start_track':
- id = call.data[11:]
- c.execute('SELECT word FROM user_2_word WHERE user_id = {0} and id = {1}'.format(chat_id, id))
- word = c.fetchall()[-1][0]
- thread = Thread(target=track_chat_0, args=(word.replace('\n','').replace('- ',''), chat_id))
- thread.start()
- conn.commit()
- @bot.message_handler(commands = ['start'])
- def command_handler_start(message): #Обработчик команды /start
- chat_id = message.chat.id
- checkOnNewUser(message)
- start_text = '''Привет. Я могу отслеживать каналы телеграм на появление там заданных тобой слов. Ты можешь отслеживать:
- - одно слово в одном канале
- - несколько слов в одном канале
- - несколько слов в нескольких каналах
- - создавать группы отслеживания из слов и каналов по тематике или на свое усмотрение.
- Нажми далее чтобы задать слово, а далее - определим канал(ы) где нужно его отследить.'''
- markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
- markup.add(KeyboardButton('Далее'))
- markup.add(KeyboardButton('Настройки'))
- msg = bot.send_message(chat_id=chat_id, text = start_text, reply_markup=markup)
- bot.register_next_step_handler(msg, start)
- @bot.message_handler(content_types=['text'])
- def start(message): # start / некорректные данные
- if message.text == 'Далее' or message.text == 'Создать':
- chat_id = message.chat.id
- bot.delete_message(chat_id = chat_id, message_id = message.message_id)
- msg = bot.send_message(chat_id=chat_id, text='Укажи слово для поиска.')
- bot.register_next_step_handler(msg, lvl0_text)
- elif message.text == 'Настройки':
- chat_id = message.chat.id
- settings = InlineKeyboardMarkup()
- settings.add(InlineKeyboardButton('Перейти в настройки', callback_data='settings'))
- bot.send_message(chat_id=chat_id, text='Вы уверены что хотите перейти в настройки?', reply_markup=settings)
- def lvl0_text(message): #Обработчик текста lvl0
- chat_id = message.from_user.id
- correct_or_next = InlineKeyboardMarkup()
- correct_or_next.add(InlineKeyboardButton('Скорректировать', callback_data='correct_lvl0'+str(message.message_id+1)),
- InlineKeyboardButton('Продолжить', callback_data='lvl0' + message.text+'edocroftilsp0'+str(message.message_id+1)))
- msg = bot.send_message(chat_id=chat_id,
- text='Ты ввел слово ({0}) - скорректировать или продолжить? '.format(message.text),
- reply_markup=correct_or_next)
- bot.register_next_step_handler(msg, empty_def)
- def lvl0_loop_text(message): #Обработчик текста lvl0_loop
- chat_id = message.from_user.id
- bot.edit_message_text(chat_id=chat_id, message_id=message.message_id - 1, text='✅')
- correct_or_next = InlineKeyboardMarkup()
- correct_or_next.add(InlineKeyboardButton('Скорректировать', callback_data='correct_lvl_loop0'+str(message.message_id+1)), InlineKeyboardButton('Продолжить', callback_data='lvl_loop0'+message.text+'edocroftilsp0'+str(message.message_id+1)))
- msg = bot.send_message(chat_id=chat_id, text='Ты ввел слово ({0}) - скорректировать или продолжить? '.format(message.text), reply_markup=correct_or_next)
- bot.register_next_step_handler(msg, empty_def)
- def lvl1_text(message): #Обработчик текста lvl1
- chat_id = message.from_user.id
- if 'https://t.me/joinchat/' in message.text:
- link = message.text
- client.start()
- checkValidate = client.loop.run_until_complete(checkValidate_link(link))
- client.disconnect()
- if checkValidate == False:
- msg = bot.send_message(chat_id=chat_id,text='Введите корректные данные!')
- bot.register_next_step_handler(msg, lvl1_text)
- elif checkValidate == True:
- hash = link[link.find('https://') + 8:]
- correct_or_incorrect = InlineKeyboardMarkup()
- correct_or_incorrect.add(InlineKeyboardButton('Правильно', callback_data='lvl1'+hash+'edocroftilsp0'+str(message.message_id+1)), InlineKeyboardButton('Изменить', callback_data='correct_lvl1'+str(message.message_id+1)))
- msg = bot.send_message(chat_id=chat_id, text='Ссылка для приглашения в чат: {0}'.format(message.text), reply_markup=correct_or_incorrect)
- bot.register_next_step_handler(msg, empty_def)
- elif checkValidate == 'flooderror':
- bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 1'.format(admins_list))
- else:
- bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 2'.format(admins_list))
- elif 'https://t.me/joinchat/' not in message.text:
- chat_username = message.text
- client.start()
- checkValidate = client.loop.run_until_complete(checkValidate_username(chat_username))
- client.disconnect()
- if checkValidate == False:
- msg = bot.send_message(chat_id=chat_id,text='Введите корректные данные!')
- bot.register_next_step_handler(msg, lvl1_text)
- elif checkValidate == True:
- correct_or_incorrect = InlineKeyboardMarkup()
- correct_or_incorrect.add(InlineKeyboardButton('Правильно', callback_data='lvl1'+chat_username+'edocroftilsp0'+str(message.message_id+1)), InlineKeyboardButton('Изменить', callback_data='correct_lvl1'+str(message.message_id+1)))
- msg = bot.send_message(chat_id=chat_id, text='Логин чата: {0}'.format(message.text), reply_markup=correct_or_incorrect)
- bot.register_next_step_handler(msg, empty_def)
- elif checkValidate == 'flooderror':
- bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 3'.format(admins_list))
- else:
- bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 4'.format(admins_list))
- else:
- msg = bot.send_message(chat_id=chat_id,text='Введите корректные данные!')
- bot.register_next_step_handler(msg, lvl1_text)
- def lvl2_text(message): #Обработчик текста lvl2
- chat_id = message.from_user.id
- bot.edit_message_text(chat_id=chat_id, message_id=message.message_id-1, text = '➡️')
- if 'https://t.me/joinchat/' in message.text:
- link = message.text
- client.start()
- checkValidate = client.loop.run_until_complete(checkValidate_link(link))
- client.disconnect()
- if checkValidate == False:
- msg = bot.send_message(chat_id=chat_id,text='Введите корректные данные!')
- bot.register_next_step_handler(msg, lvl2_text)
- elif checkValidate == True:
- correct_or_incorrect = InlineKeyboardMarkup()
- correct_or_incorrect.add(InlineKeyboardButton('Правильно', callback_data='lvl2'+message.text+'edocroftilsp0'+str(message.message_id+1)), InlineKeyboardButton('Изменить', callback_data='correct_lvl2'+str(message.message_id+1)))
- msg = bot.send_message(chat_id=chat_id, text='Ссылка для приглашения в чат: {0}'.format(message.text), reply_markup=correct_or_incorrect)
- bot.register_next_step_handler(msg, empty_def)
- elif checkValidate == 'flooderror':
- bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 1'.format(admins_list))
- else:
- bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 2'.format(admins_list))
- elif 'https://t.me/joinchat/' not in message.text:
- chat_username = message.text
- client.start()
- checkValidate = client.loop.run_until_complete(checkValidate_username(chat_username))
- client.disconnect()
- if checkValidate == False:
- msg = bot.send_message(chat_id=chat_id,text='Введите корректные данные!')
- bot.register_next_step_handler(msg, lvl2_text)
- elif checkValidate == True:
- correct_or_incorrect = InlineKeyboardMarkup()
- correct_or_incorrect.add(InlineKeyboardButton('Правильно', callback_data='lvl2'+message.text+'edocroftilsp0'+str(message.message_id+1)), InlineKeyboardButton('Изменить', callback_data='correct_lvl2'+str(message.message_id+1)))
- msg = bot.send_message(chat_id=chat_id, text='Логин чата: {0}'.format(message.text), reply_markup=correct_or_incorrect)
- bot.register_next_step_handler(msg, empty_def)
- elif checkValidate == 'flooderror':
- bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 3'.format(admins_list))
- else:
- bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 4'.format(admins_list))
- else:
- msg = bot.send_message(chat_id=chat_id,text='Введите корректные данные!')
- bot.register_next_step_handler(msg, lvl2_text)
- def group_name_text(message):
- chat_id = message.from_user.id
- bot.edit_message_text(chat_id=chat_id, message_id=message.message_id - 1, text='✅')
- correct_or_next = InlineKeyboardMarkup()
- correct_or_next.add(InlineKeyboardButton('Скорректировать', callback_data='finnaly_next_correct'+ 'edocroftilsp0'+str(message.message_id+1)),
- InlineKeyboardButton('Продолжить', callback_data='finnaly_next_next' + message.text + 'edocroftilsp0'+str(message.message_id+1)))
- msg = bot.send_message(chat_id=chat_id,
- text='Ты ввел название ({0}) - скорректировать или продолжить? '.format(message.text),
- reply_markup=correct_or_next)
- bot.register_next_step_handler(msg, empty_def)
- def empty_def(message):
- pass
- def start_telethon():
- client.start()
- chat_name = 'https://t.me/testchannelfordelete2', 'https://t.me/joinchat/AAAAAEmb6vlzmZTRfB0B5g'
- @client.on(events.NewMessage(chats=(chat_name)))
- async def normal_handler(event):
- info = event.message.to_dict()
- message = info['message']
- print(message)
- client.run_until_disconnected()
- def start_bot():
- bot.polling(none_stop=True)
- if __name__ == '__main__':
- threading.Thread(target=start_telethon).start()
- threading.Thread(target=start_bot).start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement