Advertisement
Artiom17

Tg Bot

Mar 4th, 2020
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.74 KB | None | 0 0
  1. import telebot
  2. from telebot import types
  3. import mysql.connector
  4. from flask import Flask, request
  5. import config
  6.  
  7. token = config.TOKEN
  8. secret = '<SECRET_KEY>'
  9. url = '<URL>' + secret
  10.  
  11. bot = telebot.TeleBot(token, threaded=False)
  12. bot.remove_webhook()
  13. bot.set_webhook(url=url)
  14.  
  15. app = Flask(__name__)
  16.  
  17. db = mysql.connector.connect(
  18.     host="localhost",
  19.     user="root",
  20.     passwd=config.password,
  21.     database=config.database,
  22.     port="3306"
  23. )
  24.  
  25. cursor = db.cursor()
  26.  
  27.  
  28. class User:
  29.     def __init__(self, first_name):
  30.         self.first_name = first_name
  31.         self.last_name = ''
  32.  
  33.  
  34. user_data = {}
  35.  
  36. # Buttons
  37. registration_main = types.InlineKeyboardButton(text='Регистрация', callback_data="Registration")
  38. search_main = types.InlineKeyboardButton(text='Поиск информации', callback_data="Search")
  39. mainMenu = types.InlineKeyboardButton(text='Вернуться в главное меню', callback_data="mainmenu")
  40.  
  41.  
  42. @bot.message_handler(commands=["start"])
  43. def main(message):
  44.     markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
  45.     but_main = types.KeyboardButton('/Main_Menu')
  46.     markup.add(but_main)
  47.     bot.send_message(message.chat.id, "Welcome text",
  48.                      reply_markup=markup)
  49.  
  50.  
  51. @app.route('/' + secret, methods=['POST'])
  52. def webhook():
  53.     update = telebot.types.Update.de_json(request.stream.read().decode('utf-8'))
  54.     bot.process_new_updates([update])
  55.     return '!', 200
  56.  
  57.  
  58. @bot.message_handler(commands=["Main_Menu"])
  59. def inline(message):
  60.     key = types.InlineKeyboardMarkup()
  61.     but_reg = registration_main
  62.     but_search = search_main
  63.     key.add(but_reg)
  64.     key.add(but_search)
  65.     bot.send_message(message.chat.id, "Зарегистрируйтесь или начните поиск необходимой информации:",
  66.                      reply_markup=key)
  67.  
  68.  
  69. @bot.message_handler(content_types=["text"])
  70. def registration_firstname(message):
  71.     try:
  72.         user_id = message.from_user.id
  73.         user_data[user_id] = User(message.text)
  74.  
  75.         msg = bot.send_message(message.chat.id, "Введите фамилию")
  76.         bot.register_next_step_handler(msg, registration_lastname)
  77.     except Exception as e:
  78.         bot.reply_to(message, 'Error')
  79.  
  80.  
  81. def registration_lastname(message):
  82.     try:
  83.         user_id = message.from_user.id
  84.         user = user_data[user_id]
  85.         user.last_name = message.text
  86.  
  87.         sql = "INSERT INTO users (first_name, last_name, user_id) \
  88.                                         VALUES (%s, %s, %s)"
  89.         val = (user.first_name, user.last_name, user_id)
  90.         cursor.execute(sql, val)
  91.         db.commit()
  92.  
  93.         bot.send_message(message.chat.id, "Success!")
  94.     except Exception as e:
  95.         bot.reply_to(message, 'Error')
  96.  
  97.  
  98. ########################################################################################################
  99. ####### How to change this function to make it working with User input and getting information from database?
  100. ####### If User inputs something like name, so we get name, lastname and phone number (if we have those datas in the table) of this
  101. ####### member in telegram bot...
  102. # Вот здесь не знаю как правильно написать функцию для поиска
  103. # информации из базы данных (в моем случае это MySQL),
  104. # пользователь тг бота вводит имя или фамилию для поиска контакта и
  105. # и в тг из базы данных отправляется: имя, фамилия и номер телефона.
  106. ########################################################################################################
  107. # Этот вариант выдает ошибку
  108. # def search_info(message):
  109.     # text = message.from_user.id
  110.     # user = user_data[text]
  111.     # user.search_info = message.text.lower()
  112.     # if text == text:
  113.         # sql = "SELECT * FROM guides WHERE first_name = %s"
  114.         # val = (user.search_info, )
  115.         # cursor.execute(sql, val)
  116.         # for result in cursor.fetchall():
  117.             # bot.send_message(message.chat.id, result)
  118. ########################################################################################################
  119. ????????????????????????????????????????????????????????????????????????????????????????????????????????
  120. def search_guides(message):
  121.     markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
  122.     but_main = types.KeyboardButton('/Main_Menu')
  123.     markup.add(but_main)
  124.     if message.text == 'Выбрать другую категорию поиска':
  125.         key = types.InlineKeyboardMarkup()
  126.         but_guides = types.InlineKeyboardButton(text="Гиды", callback_data="guides")
  127.         but_drivers = types.InlineKeyboardButton(text="Водители", callback_data="drivers")
  128.         but_agents = types.InlineKeyboardButton(text="Туроператоры", callback_data="agents")
  129.         but_hotels = types.InlineKeyboardButton(text="Гостиницы", callback_data="hotels")
  130.         but_restaurants = types.InlineKeyboardButton(text="Рестораны", callback_data="restaurants")
  131.         but_main_menu = types.InlineKeyboardButton(text="Главное меню", callback_data="mainmenu")
  132.         key.add(but_guides)
  133.         key.add(but_drivers)
  134.         key.add(but_agents)
  135.         key.add(but_hotels)
  136.         key.add(but_restaurants)
  137.         key.add(but_main_menu)
  138.         bot.send_message(message.chat.id, "Выберите категорию для поиска:",
  139.                          reply_markup=key)
  140.  
  141.     if message.text == 'Продолжить поиск гида':
  142.         msg = bot.send_message(message.chat.id, "Введите имя, фамилию или язык гида: ",
  143.                                reply_markup=markup)
  144.         bot.register_next_step_handler(msg, search_info)
  145.  
  146.     if not message.text == 'Продолжить поиск гида' or 'Выбрать другую категорию поиска':
  147.         msg = bot.send_message(message.chat.id, "Ошибка!!! Нажмите Main_Menu для продолжения работы с ботом!",
  148.                                reply_markup=markup)
  149.         bot.register_next_step_handler(msg, inline)
  150.  
  151.  
  152. def search_info(message):
  153.     markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
  154.     but_main = types.KeyboardButton('Выбрать другую категорию поиска')
  155.     but_continue = types.KeyboardButton('Продолжить поиск гида')
  156.     markup.add(but_main)
  157.     markup.add(but_continue)
  158.  
  159.     # if message.text == '/Main_Menu':
  160.     #     msg = bot.send_message(message.chat.id, text="Возврат в гланое меню", reply_markup=markup)
  161.     #     bot.register_next_step_handler(msg, inline)
  162.  
  163.     try:
  164.         text = message.from_user.id
  165.         if text == text:
  166.             sql = "SELECT * FROM guides WHERE first_name = %s"
  167.             val = (message.text,)
  168.             cursor.execute(sql, val)
  169.  
  170.             for result in cursor.fetchall():
  171.                 print(result)
  172.                 bot.send_message(message.chat.id,
  173.                                  text='Результат поиска: \nИмя: ' + result[1] + '\nФамилия: ' + result[2] +
  174.                                       '\nНомер телефона: ' + str(
  175.                                      result[3]))
  176.  
  177.     except Exception as e:
  178.         msg = bot.reply_to(message, 'Что-то пошло не так!')
  179.         bot.register_next_step_handler(msg, inline)
  180.  
  181.     msg = bot.send_message(message.chat.id, "Вы можете продолжить поиск гидов или нажмите Main Menu для "
  182.                                             "поиска другой информации",
  183.                            reply_markup=markup)
  184.     bot.register_next_step_handler(msg, search_guides)
  185.  
  186.     # if message.text == '/Main_Menu':
  187.     #     msg = bot.send_message(message.chat.id, text="Возврат в главное меню", reply_markup=markup)
  188.     #     bot.register_next_step_handler(msg, inline)
  189.  
  190. ########################################################################################################
  191.  
  192. @bot.callback_query_handler(func=lambda call: True)
  193. def callback_inline(call):
  194.     if call.data == "mainmenu":
  195.         keymain = types.InlineKeyboardMarkup()
  196.         but_reg = registration_main
  197.         but_search = search_main
  198.         keymain.add(but_reg)
  199.         keymain.add(but_search)
  200.         bot.send_message(chat_id=call.message.chat.id, text="Главное меню",
  201.                          reply_markup=keymain)
  202.  
  203.     if call.data == "Registration":
  204.         keyreg = types.InlineKeyboardMarkup()
  205.         but_main_menu = mainMenu  # главное меню
  206.         keyreg.add(but_main_menu)
  207.         msg = bot.send_message(chat_id=call.message.chat.id, text="Введите Ваше имя: ",
  208.                                reply_markup=keyreg)
  209.         bot.register_next_step_handler(msg, registration_firstname)
  210.  
  211. ########################################################################################################
  212.  
  213.     if call.data == "Search":
  214.         key = types.InlineKeyboardMarkup()
  215.         but_1 = types.InlineKeyboardButton(text="Button1")
  216.         but_2 = types.InlineKeyboardButton(text="Button2")
  217.         but_main_menu = mainMenu
  218.         key.add(but_1)
  219.         key.add(but_2)
  220.         key.add(but_main_menu)
  221.         msg = bot.send_message(chat_id=call.message.chat.id, text="Введите имя или фамилию для поиска контакта:",
  222.                          reply_markup=key)
  223.  
  224. ####### From this point User can input something (Like firstname or lastname) to get information from database (in my case it's MySQL), ####### by going to the next step, and I don't know how to make it working, is there any solution?
  225. ####### Здесь пользователь начинает вводить данные и переходит к следующей функции
  226.  
  227.         bot.register_next_step_handler(msg, search_info)
  228.  
  229. ########################################################################################################
  230.  
  231.  
  232. # Enable saving next step handlers to file "./.handlers-saves/step.save".
  233. # Delay=2 means that after any change in next step handlers (e.g. calling register_next_step_handler())
  234. # saving will hapen after delay 2 seconds.
  235. bot.enable_save_next_step_handlers(delay=2)
  236.  
  237. # Load next_step_handlers from save file (default "./.handlers-saves/step.save")
  238. # WARNING It will work only if enable_save_next_step_handlers was called!
  239. bot.load_next_step_handlers()
  240.  
  241. if __name__ == '__main__':
  242.     app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement