Advertisement
Guest User

Untitled

a guest
Mar 28th, 2020
441
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 32.05 KB | None | 0 0
  1. from telethon import TelegramClient, sync, events, errors
  2. import telebot
  3. from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove
  4. import psycopg2
  5. from psycopg2 import sql
  6. from contextlib import closing
  7. from telethon.tl.functions.messages import ImportChatInviteRequest
  8. from telethon.tl.functions.channels import LeaveChannelRequest, JoinChannelRequest
  9. import threading
  10.  
  11. admins_list = '@vladshtatskiy'
  12.  
  13. name = 'sessionforbot'
  14. api_id = 1347648
  15. api_hash = 'ad562ba1f498cb44df5697284a1294eb'
  16. client = TelegramClient(name, api_id, api_hash)
  17.  
  18. TELEGRAM_TOKEN = '1116792075:AAEIz2JYKjJVr7YefnRC5lcD1CpOO7uOCoo'
  19. bot = telebot.TeleBot(TELEGRAM_TOKEN)
  20.  
  21. username, password, host, dbname = 'bsapqeihvqgfxg','116305072a743138687b0b27ba1871da04958fe4ae50c979071893d8c7f892f6','ec2-54-247-118-139.eu-west-1.compute.amazonaws.com','d4jckgkr1ri9ef'
  22. print('Успешно запущено.')
  23.  
  24. def reload_tables(): #Создания всех таблиц в базе данных (по умолчанию не используется)
  25. with closing(psycopg2.connect('postgres://{0}:{1}@{2}/{3}'.format(username, password, host, dbname))) as conn:
  26. with conn.cursor() as c:
  27. try:
  28. c.execute('DROP TABLE users')
  29. c.execute('DROP TABLE user_2_word')
  30. c.execute('DROP SEQUENCE user_2_word_sequence')
  31. c.execute('DROP TABLE key_word')
  32. c.execute('DROP TABLE channel')
  33. c.execute('DROP TABLE group_name')
  34. c.execute('DROP SEQUENCE group_name_sequence')
  35. except:pass
  36. conn.commit()
  37. c.execute('CREATE TABLE IF NOT EXISTS users (user_id INTEGER);')
  38. print('Таблица users создана успешно.')
  39. c.execute('CREATE TABLE IF NOT EXISTS user_2_word (id INTEGER, word TEXT, user_id INTEGER, session INTEGER, channel TEXT, PRIMARY KEY (id));')
  40. c.execute('CREATE SEQUENCE IF NOT EXISTS user_2_word_sequence start 1;')
  41. print('Таблица user_2_word создана успешно.')
  42. c.execute('CREATE TABLE IF NOT EXISTS key_word (word TEXT UNIQUE);')
  43. print('Таблица key_word создана успешно.')
  44. c.execute('CREATE TABLE IF NOT EXISTS channel (channel TEXT UNIQUE);')
  45. print('Таблица channel создана успешно.')
  46. c.execute('CREATE TABLE IF NOT EXISTS group_name (id INTEGER, user_id INTEGER, group_name TEXT, session INTEGER, PRIMARY KEY (id));')
  47. c.execute('CREATE SEQUENCE IF NOT EXISTS group_name_sequence start 1;')
  48. print('Таблица group_name создана успешно.')
  49. conn.commit()
  50. print('STATUS: SUCCESS')
  51.  
  52. def checkOnNewUser(message): #Проверка нового юзера
  53. with closing(psycopg2.connect('postgres://{0}:{1}@{2}/{3}'.format(username,password,host,dbname))) as conn:
  54. with conn.cursor() as c:
  55. try:
  56. c.execute('SELECT user_id FROM users WHERE user_id = {0}'.format(message.chat.id))
  57. for row in c:
  58. user_id = row
  59. if user_id == None:
  60. c.execute('INSERT INTO users (user_id) VALUES ({0});'.format(message.chat.id))
  61. conn.commit()
  62. except:
  63. c.execute('INSERT INTO users (user_id) VALUES ({0});'.format(message.chat.id))
  64. conn.commit()
  65.  
  66. # async def track_chat(chat_name, chat_id):
  67. # print('Работает...')
  68. # async with TelegramClient(name, api_id, api_hash) as client:
  69. #
  70. async def checkValidate_username(username): #Проверка приглашения в канал на валидность (логин)
  71. try:
  72. check = await client.get_entity(username)
  73. return True
  74. except errors.rpcerrorlist.InviteHashInvalidError as e:
  75. return False
  76. except errors.rpcerrorlist.FloodWaitError as e:
  77. print(str(e))
  78. return 'flooderror'
  79. except errors.rpcerrorlist.UserAlreadyParticipantError:
  80. return True
  81. except:
  82. return False
  83. await client.disconnect()
  84. async def checkValidate_link(link): #Проверка приглашения в канал на валидность (ссылка)
  85. hash = link[link.find('t.me/joinchat/') + 14:]
  86. try:
  87. await client(ImportChatInviteRequest(hash))
  88. check = await client.get_entity(link)
  89. return True
  90. except errors.rpcerrorlist.InviteHashInvalidError as e:
  91. return False
  92. except errors.rpcerrorlist.FloodWaitError as e:
  93. print(str(e))
  94. return 'flooderror'
  95. except errors.rpcerrorlist.UserAlreadyParticipantError:
  96. return True
  97. except errors.rpcerrorlist.InviteHashEmptyError:
  98. return False
  99. except:
  100. return False
  101. await client.disconnect()
  102.  
  103. async def get_channel_name_telethon(channelIdLink): #Проверка приглашения в канал на валидность (ссылка)
  104. try:
  105. check = await client.get_entity(channelIdLink)
  106. check = check.to_dict()['title']
  107. return check
  108. except Exception as e:
  109. print(str(e))
  110. await client.disconnect()
  111.  
  112. def get_session(c, conn, chat_id): # получить идентификатор сессии
  113. c.execute('SELECT session FROM user_2_word WHERE user_id = {0}'.format(chat_id))
  114. try:
  115. session = c.fetchall()[-1][0]
  116. except IndexError:
  117. session = None
  118. return session
  119. def channel_add(c, conn, channel_name): # добавить канал в таблицу channel
  120. try:
  121. c.execute('INSERT INTO channel (channel) VALUES ({0})'.format(f"'{channel_name}'"))
  122. conn.commit()
  123. except:pass
  124. def getword_u2w(c, conn, user_id): # получить word (слово) из таблицы user_2_word
  125. c.execute('SELECT word FROM user_2_word WHERE user_id = {0}'.format(user_id))
  126. word = c.fetchall()[-1][0]
  127. if str(word) == 'None':
  128. id = get_id_u2w(c, conn, user_id)
  129. c.execute('SELECT word FROM user_2_word WHERE user_id = {0} and id = {1}'.format(user_id, int(id)-1))
  130. word = c.fetchall()[-1][0]
  131. return word
  132. def get_id_u2w(c, conn, user_id):
  133. c.execute('SELECT id FROM user_2_word WHERE user_id = {0}'.format(user_id))
  134. id = c.fetchall()[-1][0]
  135. return id
  136. def insert_word(chat_id, word):
  137. with closing(psycopg2.connect('postgres://{0}:{1}@{2}/{3}'.format(username,password,host,dbname))) as conn:
  138. with conn.cursor() as c:
  139. try:
  140. c.execute('INSERT INTO key_word (word) VALUES ({0});'.format(f"'{word}'"))
  141. except:
  142. pass
  143. conn.commit()
  144. 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))
  145. conn.commit()
  146. id = get_id_u2w(c, conn, chat_id)
  147. 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))
  148. conn.commit()
  149. def get_words_u2w(c, chat_id, session):
  150. c.execute('SELECT word FROM user_2_word WHERE user_id = {0} and session = {1}'.format(chat_id, session))
  151. words = str()
  152. for row in c:
  153. words = words + '- ' + str(row[0]) + '\n'
  154. return words
  155. def get_channels_u2w(c, chat_id, session):
  156. c.execute('SELECT channel FROM user_2_word WHERE user_id = {0} and session = {1}'.format(chat_id, session))
  157. channels = str()
  158. for row in c:
  159. channels = channels + '- ' + str(row[0]) + '\n'
  160. return channels
  161. def get_channels_name(c, chat_id, session):
  162. client.start()
  163. c.execute('SELECT channel FROM user_2_word WHERE user_id = {0} and session = {1}'.format(chat_id, session))
  164. channels = str()
  165. for row in c:
  166. getname = client.loop.run_until_complete(get_channel_name_telethon(row[0]))
  167. channels = channels + '- ' + str(getname) + '\n'
  168. client.disconnect()
  169. return channels
  170.  
  171. @bot.callback_query_handler(func=lambda call: True)
  172. def callback_query_handler(call):
  173. with closing(psycopg2.connect('postgres://{0}:{1}@{2}/{3}'.format(username,password,host,dbname))) as conn:
  174. with conn.cursor() as c:
  175. chat_id = call.message.chat.id
  176. if call.data[:12] == 'correct_lvl0':
  177. lastmessage_id = call.data[12:]
  178. bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text='❌')
  179. msg = bot.send_message(chat_id=chat_id, text='Укажи слово для поиска.')
  180. bot.register_next_step_handler(msg, lvl0_text)
  181. elif call.data[:17] == 'correct_lvl_loop0':
  182. lastmessage_id = call.data[17:]
  183. bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text='❌')
  184. word = getword_u2w(c, conn, chat_id)
  185. next_markup = InlineKeyboardMarkup()
  186. next_markup.add(InlineKeyboardButton('Пропустить', callback_data='finnaly_next'+str(call.message.message_id)))
  187. msg = bot.send_message(chat_id=chat_id, text='Хочешь отслеживать в добавленных выше каналах другие слова кроме <{0}>? Введите еще слово или нажмите ДАЛЕЕ для продолжения.'.format(word), reply_markup=next_markup)
  188. bot.register_next_step_handler(msg, lvl0_loop_text)
  189. elif call.data[:12] == 'correct_lvl1':
  190. lastmessage_id = call.data[12:]
  191. bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text='❌')
  192. msg = bot.send_message(chat_id=chat_id, text='Отправь мне ссылку на приглашение в канал/логин канала, который хочешь отслеживать.')
  193. bot.register_next_step_handler(msg, lvl1_text)
  194. elif call.data[:12] == 'correct_lvl2' or call.data[:12] == 'continue_set':
  195. lastmessage_id = call.data[12:]
  196. if call.data[:12] == 'continue_set':
  197. symbol = '➡️'
  198. else:
  199. symbol = '❌'
  200. bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text=symbol)
  201. word = getword_u2w(c, conn, chat_id)
  202. next_markup = InlineKeyboardMarkup()
  203. next_markup.add(InlineKeyboardButton('Пропустить', callback_data='finnaly_next'+str(call.message.message_id)))
  204. msg = bot.send_message(chat_id=chat_id, text='Отправь мне ссылку на приглашение в ДРУГОЙ канал/логин ДРУГОГО канала, если хочешь отслеживать и его на появление слова <{0}> или нажмите пропустить для продолжения.'.format(word), reply_markup=next_markup)
  205. bot.register_next_step_handler(msg, lvl2_text)
  206.  
  207. elif call.data[:4] == 'lvl0': # (ПОЛУЧАЕТ СЛОВО)
  208. word = call.data[4:].split('edocroftilsp0')[0]
  209. lastmessage_id = call.data[4:].split('edocroftilsp0')[1]
  210. bot.edit_message_text(chat_id = chat_id, message_id = lastmessage_id, text = '✅')
  211. insert_word(chat_id, word)
  212. msg = bot.send_message(chat_id=chat_id, text='Отправь мне ссылку на приглашение в канал/логин канала, который хочешь отслеживать.')
  213. bot.register_next_step_handler(msg, lvl1_text)
  214. elif call.data[:9] == 'lvl_loop0': # укажи мне ссылку на канал (lvl0_loop - lvl1) (ПОЛУЧАЕТ СЛОВО)
  215. word = call.data[9:].split('edocroftilsp0')[0]
  216. lastmessage_id = call.data[9:].split('edocroftilsp0')[1]
  217. bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text='✅')
  218. session = get_session(c, conn, chat_id)
  219. id = get_id_u2w(c, conn, chat_id)
  220. 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))
  221. try:
  222. c.execute('INSERT INTO key_word (word) VALUES ({0});'.format(f"'{word}'"))
  223. except:
  224. pass
  225. conn.commit()
  226. next_markup = InlineKeyboardMarkup()
  227. next_markup.row_width = 1
  228. next_markup.add(InlineKeyboardButton('Запустить отслеживание', callback_data='finnaly_next'),
  229. InlineKeyboardButton('Продолжить настройку', callback_data='continue_set'+str(call.message.message_id+1)))
  230. words = get_words_u2w(c, chat_id, session)
  231. channels_name = get_channels_name(c, chat_id, session)
  232. text = f'Отлично! Ты добавил следующие слова:\n{words}\n\nДля отслеживания в следующих каналах/чатах:\n\n{channels_name}\nМожем остановиться на этих данных и начать отслеживание или продолжим добавление каналов или слов? '
  233. bot.send_message(chat_id=chat_id, text=text, reply_markup=next_markup)
  234. conn.commit()
  235. elif call.data[:4] == 'lvl1': # отправь мне ссылку на приглашение в другой канал (lvl1 - lvl2) (ПОЛУЧАЕТ ССЫЛКУ НА КАНАЛ/ЛОГИН КАНАЛА)
  236. channel = call.data[4:].split('edocroftilsp0')[0]
  237. lastmessage_id = call.data[4:].split('edocroftilsp0')[1]
  238. bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text='✅')
  239. id = get_id_u2w(c, conn, chat_id)
  240. session = get_session(c, conn, chat_id)
  241. 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))
  242. channel_add(c, conn, channel)
  243. next_markup = InlineKeyboardMarkup()
  244. next_markup.row_width = 1
  245. next_markup.add(InlineKeyboardButton('Запустить отслеживание', callback_data='finnaly_next'+str(call.message.message_id)), InlineKeyboardButton('Продолжить настройку', callback_data='continue_set'+str(call.message.message_id+1)))
  246. words = get_words_u2w(c, chat_id, session)
  247. channels_name = get_channels_name(c, chat_id, session)
  248. text = f'Отлично! Ты добавил следующие слова:\n\n{words}\nДля отслеживания в следующих каналах/чатах:\n\n{channels_name}\nМожем остановиться на этих данных и начать отслеживание или продолжим добавление каналов или слов? '
  249. bot.send_message(chat_id=chat_id, text=text, reply_markup=next_markup)
  250. conn.commit()
  251. elif call.data[:4] == 'lvl2': # добавить другие слова (lvl2 - lvl3) (ПОЛУЧАЕТ ССЫЛКУ НА ДРУГОЙ КАНАЛ/ЛОГИН ДРУГОГО КАНАЛА)
  252. channel = call.data[4:].split('edocroftilsp0')[0]
  253. lastmessage_id = call.data[4:].split('edocroftilsp0')[1]
  254. bot.edit_message_text(chat_id=chat_id, message_id=lastmessage_id, text='✅')
  255. session = get_session(c, conn, chat_id)
  256. 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))
  257. channel_add(c, conn, channel)
  258. conn.commit()
  259. next_markup = InlineKeyboardMarkup()
  260. next_markup.add(InlineKeyboardButton('Пропустить', callback_data='finnaly_next'+str(call.message.message_id)))
  261. word = getword_u2w(c, conn, chat_id)
  262. id = int(get_id_u2w(c, conn, chat_id))-1
  263. if word == 'None':
  264. c.execute('SELECT word FROM user_2_word WHERE user_id = {0} and id = {1}'.format(chat_id, id))
  265. for row in c:
  266. word = row
  267. try:
  268. word = word[0]
  269. except:
  270. word = None
  271. msg = bot.send_message(chat_id=chat_id, text='Хочешь отслеживать в добавленных выше каналах другие слова кроме <{0}>? Введите еще слово или нажмите пропустить для продолжения.'.format(word), reply_markup=next_markup)
  272. bot.register_next_step_handler(msg, lvl0_loop_text)
  273.  
  274. elif (call.data[:12] == 'finnaly_next' and call.data[:13] != 'finnaly_next_') or call.data[:20] == 'finnaly_next_correct': # назвать группу для отслеживания / коррекция
  275.  
  276. if call.data[:12] == 'finnaly_next' and call.data[:13] != 'finnaly_next_':
  277. last_id = int(call.data[12:])+1
  278. elif call.data[:20] == 'finnaly_next_correct':
  279. last_id = int(call.data[20:])+1
  280. bot.edit_message_text(chat_id=chat_id, message_id=last_id, text='✅')
  281. next_markup = InlineKeyboardMarkup()
  282. next_markup.add(InlineKeyboardButton('Пропустить', callback_data='finnaly_next_next'+'edocroftilsp0'+str(call.message.message_id+1)))
  283. msg = bot.send_message(chat_id=call.message.chat.id,
  284. text='Можешь назвать эту группу отслеживания для удобства( например "Туризм" или "Tesla"). Введи имя ниже или жми ПРОПУСТИТЬ',
  285. reply_markup=next_markup)
  286. bot.clear_step_handler(msg)
  287. bot.register_next_step_handler(msg, group_name_text)
  288. elif call.data[:17] == 'finnaly_next_next': # назвать группу для отслеживания (далее)
  289. group_name = call.data[17:].split('edocroftilsp0')[0]
  290. last_id = call.data[17:].split('edocroftilsp0')[1]
  291. bot.edit_message_text(chat_id=chat_id, message_id=last_id, text='✅')
  292. if group_name == '':
  293. c.execute('SELECT session FROM group_name WHERE user_id = {0}'.format(chat_id))
  294. try:
  295. session = c.fetchall()[-1][0]
  296. except:
  297. session = 0
  298. c.execute('SELECT id FROM group_name WHERE user_id = {0} and session = {1}'.format(chat_id, session))
  299. try:
  300. id = c.fetchall()[-1][0]
  301. except:
  302. id = 0
  303. group_name = 'ID_' + str(int(id) + 1)
  304. session = get_session(c, conn, chat_id)
  305. words = get_words_u2w(c, chat_id, session)
  306. 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))
  307. settings_markup = InlineKeyboardMarkup()
  308. settings_markup.add(InlineKeyboardButton('Настройки', callback_data='settings'))
  309. channels = get_channels_name(c, chat_id, session)
  310. text = f'Поздравляю! Ты окончил настройку. Я отслеживаю каналы:\n\n{channels}\n на появление слов: \n\n{words}\nВ этот чат я буду присылать тебе сообщения из отслеживаемых каналов если там встретится нужное тебе слово. Для изменения каналов отслеживания и слов нажми НАСТРОЙКИ.'
  311. msg = bot.send_message(chat_id=chat_id,text=text,reply_markup=settings_markup)
  312. bot.register_next_step_handler(msg, command_handler_start)
  313.  
  314. elif call.data[:8] == 'settings':
  315. session = get_session(c, conn, chat_id)
  316. if session == None:
  317. add_new = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
  318. add_new.add(KeyboardButton('Создать'))
  319. msg = bot.send_message(chat_id=chat_id, text='У Вас нет активных отслеживаний.', parse_mode='HTML',reply_markup=add_new)
  320. bot.register_next_step_handler(msg, start)
  321. else:
  322. id = call.data[8:]
  323. if id == '':
  324. id = 1
  325. c.execute('SELECT * FROM group_name WHERE user_id = {0}'.format(chat_id))
  326. markup = InlineKeyboardMarkup()
  327. group_name = str()
  328. for row in c:
  329. if str(row[0]) == str(id):
  330. markup.add(InlineKeyboardButton('Изменить', callback_data='edit' + str(row[0])))
  331. group_name = row[2]
  332. else:
  333. markup.add(InlineKeyboardButton(str(row[2]), callback_data='settings' + str(row[0])))
  334. c.execute('SELECT session FROM group_name WHERE user_id = {0} and id = {1}'.format(chat_id, id))
  335. session = c.fetchall()[-1][0]
  336. words = get_words_u2w(c, chat_id, session)
  337. channels = get_channels_name(c, chat_id, session)
  338. bot.edit_message_text(chat_id=chat_id, message_id = call.message.message_id,
  339. text=f'Настройки групп отслеживания:\n\n`{group_name}`\n\n{channels}\nОтслеживается по словам:\n\n{words}',
  340. reply_markup=markup, parse_mode='Markdown')
  341. elif call.data[:4] == 'edit':
  342. id = call.data[4:]
  343. session = 1
  344. c.execute('SELECT * FROM group_name WHERE user_id = {0}'.format(chat_id))
  345. for row in c:
  346. if str(row[0]) == id and str(row[1]) == str(chat_id):
  347. session = row[3]
  348. group_name = row[2]
  349. break
  350. words = get_words_u2w(c, chat_id, session)
  351. channels = get_channels_u2w(c, chat_id, session)
  352. markup = InlineKeyboardMarkup()
  353. markup.row_width = 1
  354. markup.add(InlineKeyboardButton('Удалить канал отслеживания', callback_data = 'remove_channel_list'+str(id)),
  355. InlineKeyboardButton('Добавить канал отслеживания', callback_data = 'add_channel'+str(id)),
  356. InlineKeyboardButton('Удалить слово отслеживания', callback_data = 'remove_word'+str(id)),
  357. InlineKeyboardButton('Добавить слово отслеживания', callback_data = 'add_word'+str(id)),
  358. InlineKeyboardButton('Удалить ГРУППУ отслеживания', callback_data = 'remove_group'+str(id)),
  359. InlineKeyboardButton('Запустить', callback_data = 'start_track'+str(id)))
  360. 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')
  361. elif call.data[:19] == 'remove_channel_list':
  362. channel_id = call.data[19:]
  363. markup = InlineKeyboardMarkup()
  364. c.execute(
  365. 'SELECT channel FROM user_2_word WHERE user_id = {0} and session = {1} and id = {2}'.format(chat_id,session,id))
  366. channels = str()
  367. for row in c:
  368. markup.add(InlineKeyboardButton('', callback_data = 'remove_channel'+str(id)+','+str(row[0])))
  369. bot.send_message(chat_id = chat_id, text='Какой канал отслеживания вы хотите удалить?', reply_markup = markup)
  370. elif call.data[:11] == 'start_track':
  371. id = call.data[11:]
  372. c.execute('SELECT word FROM user_2_word WHERE user_id = {0} and id = {1}'.format(chat_id, id))
  373. word = c.fetchall()[-1][0]
  374. thread = Thread(target=track_chat_0, args=(word.replace('\n','').replace('- ',''), chat_id))
  375. thread.start()
  376. conn.commit()
  377.  
  378. @bot.message_handler(commands = ['start'])
  379. def command_handler_start(message): #Обработчик команды /start
  380. chat_id = message.chat.id
  381. checkOnNewUser(message)
  382. start_text = '''Привет. Я могу отслеживать каналы телеграм на появление там заданных тобой слов. Ты можешь отслеживать:
  383.  
  384. - одно слово в одном канале
  385.  
  386. - несколько слов в одном канале
  387.  
  388. - несколько слов в нескольких каналах
  389.  
  390. - создавать группы отслеживания из слов и каналов по тематике или на свое усмотрение.
  391.  
  392.  
  393.  
  394. Нажми далее чтобы задать слово, а далее - определим канал(ы) где нужно его отследить.'''
  395.  
  396. markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
  397. markup.add(KeyboardButton('Далее'))
  398. markup.add(KeyboardButton('Настройки'))
  399. msg = bot.send_message(chat_id=chat_id, text = start_text, reply_markup=markup)
  400. bot.register_next_step_handler(msg, start)
  401.  
  402. @bot.message_handler(content_types=['text'])
  403. def start(message): # start / некорректные данные
  404. if message.text == 'Далее' or message.text == 'Создать':
  405. chat_id = message.chat.id
  406. bot.delete_message(chat_id = chat_id, message_id = message.message_id)
  407. msg = bot.send_message(chat_id=chat_id, text='Укажи слово для поиска.')
  408. bot.register_next_step_handler(msg, lvl0_text)
  409. elif message.text == 'Настройки':
  410. chat_id = message.chat.id
  411. settings = InlineKeyboardMarkup()
  412. settings.add(InlineKeyboardButton('Перейти в настройки', callback_data='settings'))
  413. bot.send_message(chat_id=chat_id, text='Вы уверены что хотите перейти в настройки?', reply_markup=settings)
  414. def lvl0_text(message): #Обработчик текста lvl0
  415. chat_id = message.from_user.id
  416. correct_or_next = InlineKeyboardMarkup()
  417. correct_or_next.add(InlineKeyboardButton('Скорректировать', callback_data='correct_lvl0'+str(message.message_id+1)),
  418. InlineKeyboardButton('Продолжить', callback_data='lvl0' + message.text+'edocroftilsp0'+str(message.message_id+1)))
  419. msg = bot.send_message(chat_id=chat_id,
  420. text='Ты ввел слово ({0}) - скорректировать или продолжить? '.format(message.text),
  421. reply_markup=correct_or_next)
  422. bot.register_next_step_handler(msg, empty_def)
  423. def lvl0_loop_text(message): #Обработчик текста lvl0_loop
  424.  
  425. chat_id = message.from_user.id
  426. bot.edit_message_text(chat_id=chat_id, message_id=message.message_id - 1, text='✅')
  427. correct_or_next = InlineKeyboardMarkup()
  428. 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)))
  429. msg = bot.send_message(chat_id=chat_id, text='Ты ввел слово ({0}) - скорректировать или продолжить? '.format(message.text), reply_markup=correct_or_next)
  430. bot.register_next_step_handler(msg, empty_def)
  431. def lvl1_text(message): #Обработчик текста lvl1
  432. chat_id = message.from_user.id
  433. if 'https://t.me/joinchat/' in message.text:
  434. link = message.text
  435. client.start()
  436. checkValidate = client.loop.run_until_complete(checkValidate_link(link))
  437. client.disconnect()
  438. if checkValidate == False:
  439. msg = bot.send_message(chat_id=chat_id,text='Введите корректные данные!')
  440. bot.register_next_step_handler(msg, lvl1_text)
  441. elif checkValidate == True:
  442. hash = link[link.find('https://') + 8:]
  443. correct_or_incorrect = InlineKeyboardMarkup()
  444. 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)))
  445. msg = bot.send_message(chat_id=chat_id, text='Ссылка для приглашения в чат: {0}'.format(message.text), reply_markup=correct_or_incorrect)
  446. bot.register_next_step_handler(msg, empty_def)
  447. elif checkValidate == 'flooderror':
  448. bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 1'.format(admins_list))
  449. else:
  450. bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 2'.format(admins_list))
  451. elif 'https://t.me/joinchat/' not in message.text:
  452. chat_username = message.text
  453. client.start()
  454. checkValidate = client.loop.run_until_complete(checkValidate_username(chat_username))
  455. client.disconnect()
  456. if checkValidate == False:
  457. msg = bot.send_message(chat_id=chat_id,text='Введите корректные данные!')
  458. bot.register_next_step_handler(msg, lvl1_text)
  459. elif checkValidate == True:
  460. correct_or_incorrect = InlineKeyboardMarkup()
  461. 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)))
  462. msg = bot.send_message(chat_id=chat_id, text='Логин чата: {0}'.format(message.text), reply_markup=correct_or_incorrect)
  463. bot.register_next_step_handler(msg, empty_def)
  464. elif checkValidate == 'flooderror':
  465. bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 3'.format(admins_list))
  466. else:
  467. bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 4'.format(admins_list))
  468. else:
  469. msg = bot.send_message(chat_id=chat_id,text='Введите корректные данные!')
  470. bot.register_next_step_handler(msg, lvl1_text)
  471. def lvl2_text(message): #Обработчик текста lvl2
  472. chat_id = message.from_user.id
  473. bot.edit_message_text(chat_id=chat_id, message_id=message.message_id-1, text = '➡️')
  474. if 'https://t.me/joinchat/' in message.text:
  475. link = message.text
  476. client.start()
  477. checkValidate = client.loop.run_until_complete(checkValidate_link(link))
  478. client.disconnect()
  479. if checkValidate == False:
  480. msg = bot.send_message(chat_id=chat_id,text='Введите корректные данные!')
  481. bot.register_next_step_handler(msg, lvl2_text)
  482. elif checkValidate == True:
  483. correct_or_incorrect = InlineKeyboardMarkup()
  484. 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)))
  485. msg = bot.send_message(chat_id=chat_id, text='Ссылка для приглашения в чат: {0}'.format(message.text), reply_markup=correct_or_incorrect)
  486. bot.register_next_step_handler(msg, empty_def)
  487. elif checkValidate == 'flooderror':
  488. bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 1'.format(admins_list))
  489. else:
  490. bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 2'.format(admins_list))
  491. elif 'https://t.me/joinchat/' not in message.text:
  492. chat_username = message.text
  493. client.start()
  494. checkValidate = client.loop.run_until_complete(checkValidate_username(chat_username))
  495. client.disconnect()
  496. if checkValidate == False:
  497. msg = bot.send_message(chat_id=chat_id,text='Введите корректные данные!')
  498. bot.register_next_step_handler(msg, lvl2_text)
  499. elif checkValidate == True:
  500.  
  501. correct_or_incorrect = InlineKeyboardMarkup()
  502. 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)))
  503. msg = bot.send_message(chat_id=chat_id, text='Логин чата: {0}'.format(message.text), reply_markup=correct_or_incorrect)
  504. bot.register_next_step_handler(msg, empty_def)
  505. elif checkValidate == 'flooderror':
  506. bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 3'.format(admins_list))
  507. else:
  508. bot.send_message(chat_id=chat_id,text='Возникли технические неполадки. Обратитесь к {}. Код 4'.format(admins_list))
  509. else:
  510. msg = bot.send_message(chat_id=chat_id,text='Введите корректные данные!')
  511. bot.register_next_step_handler(msg, lvl2_text)
  512. def group_name_text(message):
  513. chat_id = message.from_user.id
  514. bot.edit_message_text(chat_id=chat_id, message_id=message.message_id - 1, text='✅')
  515. correct_or_next = InlineKeyboardMarkup()
  516. correct_or_next.add(InlineKeyboardButton('Скорректировать', callback_data='finnaly_next_correct'+ 'edocroftilsp0'+str(message.message_id+1)),
  517. InlineKeyboardButton('Продолжить', callback_data='finnaly_next_next' + message.text + 'edocroftilsp0'+str(message.message_id+1)))
  518. msg = bot.send_message(chat_id=chat_id,
  519. text='Ты ввел название ({0}) - скорректировать или продолжить? '.format(message.text),
  520. reply_markup=correct_or_next)
  521. bot.register_next_step_handler(msg, empty_def)
  522. def empty_def(message):
  523. pass
  524.  
  525. def start_telethon():
  526. client.start()
  527. chat_name = 'https://t.me/testchannelfordelete2', 'https://t.me/joinchat/AAAAAEmb6vlzmZTRfB0B5g'
  528.  
  529. @client.on(events.NewMessage(chats=(chat_name)))
  530. async def normal_handler(event):
  531. info = event.message.to_dict()
  532. message = info['message']
  533. print(message)
  534.  
  535. client.run_until_disconnected()
  536.  
  537. def start_bot():
  538. bot.polling(none_stop=True)
  539.  
  540. if __name__ == '__main__':
  541. threading.Thread(target=start_telethon).start()
  542. threading.Thread(target=start_bot).start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement