· 5 years ago · Mar 04, 2020, 09:26 AM
1import telebot
2from telebot import types
3import mysql.connector
4from flask import Flask, request
5import config
6
7token = config.TOKEN
8secret = '<SECRET_KEY>'
9url = '<URL>' + secret
10
11bot = telebot.TeleBot(token, threaded=False)
12bot.remove_webhook()
13bot.set_webhook(url=url)
14
15app = Flask(__name__)
16
17db = mysql.connector.connect(
18 host="localhost",
19 user="root",
20 passwd=config.password,
21 database=config.database,
22 port="3306"
23)
24
25cursor = db.cursor()
26
27
28class User:
29 def __init__(self, first_name):
30 self.first_name = first_name
31 self.last_name = ''
32
33
34user_data = {}
35
36# Buttons
37registration_main = types.InlineKeyboardButton(text='Регистрация', callback_data="Registration")
38search_main = types.InlineKeyboardButton(text='Поиск информации', callback_data="Search")
39mainMenu = types.InlineKeyboardButton(text='Вернуться в главное меню', callback_data="mainmenu")
40
41
42@bot.message_handler(commands=["start"])
43def 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'])
52def 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"])
59def 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"])
70def 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
81def 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 ####### member in telegram bot...
101
102def search_info(message):
103 text = message.from_user.id
104 if text == text:
105 cursor.execute('SELECT * FROM users')
106 for result in cursor.fetchall():
107 bot.send_message(message.chat.id, result)
108
109########################################################################################################
110
111@bot.callback_query_handler(func=lambda call: True)
112def callback_inline(call):
113 if call.data == "mainmenu":
114 keymain = types.InlineKeyboardMarkup()
115 but_reg = registration_main
116 but_search = search_main
117 keymain.add(but_reg)
118 keymain.add(but_search)
119 bot.send_message(chat_id=call.message.chat.id, text="Главное меню",
120 reply_markup=keymain)
121
122 if call.data == "Registration":
123 keyreg = types.InlineKeyboardMarkup()
124 but_main_menu = mainMenu # главное меню
125 keyreg.add(but_main_menu)
126 msg = bot.send_message(chat_id=call.message.chat.id, text="Введите Ваше имя: ",
127 reply_markup=keyreg)
128 bot.register_next_step_handler(msg, registration_firstname)
129
130########################################################################################################
131
132 if call.data == "Search":
133 key = types.InlineKeyboardMarkup()
134 but_1 = types.InlineKeyboardButton(text="Button1")
135 but_2 = types.InlineKeyboardButton(text="Button2")
136 but_main_menu = mainMenu
137 key.add(but_1)
138 key.add(but_2)
139 key.add(but_main_menu)
140 msg = bot.send_message(chat_id=call.message.chat.id, text="Введите имя или фамилию для поиска контакта:",
141 reply_markup=key)
142
143####### 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?
144
145 bot.register_next_step_handler(msg, search_info)
146
147########################################################################################################
148
149
150# Enable saving next step handlers to file "./.handlers-saves/step.save".
151# Delay=2 means that after any change in next step handlers (e.g. calling register_next_step_handler())
152# saving will hapen after delay 2 seconds.
153bot.enable_save_next_step_handlers(delay=2)
154
155# Load next_step_handlers from save file (default "./.handlers-saves/step.save")
156# WARNING It will work only if enable_save_next_step_handlers was called!
157bot.load_next_step_handlers()
158
159if __name__ == '__main__':
160 app.run()