1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
| # -*- coding: utf-8 -*-
"""
This Example will show you how to use register_next_step handler.
"""
import constants
#!/usr/bin/python
# This is a simple echo bot using the decorator mechanism.
# It echoes any incoming text messages.
import sqlite3
import telebot
import constants
from telebot import types
#Подключение к базе
conn = sqlite3.connect('my.sqlite',check_same_thread=False )
#Создание курсора
c = conn.cursor()
#Функция занесения пользователя в базу
def add_user(userid,username,usersurname,userage,userlongtitude,userlaltitude,photoid):
c.execute("INSERT INTO users (id,name,surname,aage,longitude,latitude,photoid) VALUES ('%s','%s','%s','%s','%s','%s')"%(userid,username,usersurname,userage,longitude,latitude, photoid))
conn.commit()
#Вводим данные
id = ''
name = ''
surname = ''
age = ''
global longitude
longitude = ''
global latitude
latitude = ''
print('\n')
#Делаем запрос в базу
print("Список пользователей:\n")
c.execute('SELECT * FROM users')
row = c.fetchone()
#выводим список пользователей в цикле
while row is not None:
print("id:"+str(row[0])+" Логин: "+row[1]+" | Пароль: "+row[2])
row = c.fetchone()
API_TOKEN = constants.token
bot = telebot.TeleBot(API_TOKEN)
@bot.message_handler(commands=['commands'])
def send_welcome(message):
bot.send_message(message.from_user.id, """
---- \n
all commands \n
- /help - о проекте \n
- /start - главное меню \n
- /reg - регистрация анкеты \n
----
""")
# Handle '/start' and '/help'
@bot.message_handler(commands=['help'])
def send_welcome(message):
bot.reply_to(message, """\
Hi, I'm healthy lifestyle bot. I help you to find any coaches & partners for your training""")
@bot.message_handler(commands=['start'])
def handle_start(message):
user_markup = telebot.types.ReplyKeyboardMarkup(True)
user_markup.row('Поиск пары','Найти тренера')
user_markup.row('Посмотреть анкету ')
user_markup.row('Ближайшая открытая тренировка')
bot.send_message(message.from_user.id, 'Добро пожаловать ', reply_markup=user_markup)
@bot.message_handler(content_types=['text'])
def start(message):
conn = sqlite3.connect('my.sqlite', check_same_thread=False)
# Создание курсора
c = conn.cursor()
try:
c.execute("SELECT * FROM Users WHERE (id = ?) ",
(message.from_user.id,))
FindUsers = c.fetchone()
permid, permname, permsurname, permage, longitude, latitude, photoid = FindUsers
IsRegister = True
except TypeError:
bot.send_message(message.from_user.id,'Вы ещё не зарегестрированы, пожалуйста создайте анкету /reg')
IsRegister = False
if message.text == 'Посмотреть анкету' or '/reg':
if IsRegister:
bot.send_message(message.from_user.id, """
---- \n
Так выглядит твоя анкета:
Имя - """ + str(permname) + """
Фамилия - """ + str(permsurname) + """
Возраст - """ + str(permage) + """
----
""")
bot.send_location(message.from_user.id,latitude,longitude)
question = 'Хочешь изменить анкету ' + permname + ' ?';
else:
question = 'Хочешь создать а анкету?';
keyboard = types.InlineKeyboardMarkup(); # наша клавиатура
key_yes = types.InlineKeyboardButton(text='Да', callback_data='yes1'); # кнопка «Да»
keyboard.add(key_yes); # добавляем кнопку в клавиатуру
key_no = types.InlineKeyboardButton(text='Нет', callback_data='no1');
keyboard.add(key_no);
global namepromo
namepromo = message
bot.send_message(message.from_user.id, text=question, reply_markup=keyboard)
else:
bot.send_message(message.from_user.id, 'для посмотра комманд введите /commands');
def get_name(message): #получаем фамилию
global name;
name = message.text;
bot.send_message(message.from_user.id, 'Какая у тебя фамилия?');
bot.register_next_step_handler(message, get_surname);
def get_surname(message):
global surname;
surname = message.text;
bot.send_message(message.from_user.id, 'Сколько тебе лет?');
bot.register_next_step_handler(message, get_age);
def get_age(message):
global age;
while True: #проверяем что возраст изменился
try:
age = int(message.text)
except ValueError:
bot.send_message(message.from_user.id,"Цифрами пожалуйста")
bot.register_next_step_handler(message, get_age)
return
if age < 0:
print("Возраст не может быть отрицательным")
continue
else:
bot.send_message(message.from_user.id, 'Пришли мне своё фото');
bot.register_next_step_handler(message, geo(message));
# age was successfully parsed, and we're happy with its value.
# we're ready to exit the loop.
break
def geo(message):
keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
button_geo = types.KeyboardButton(text="Отправить местоположение", request_location=True, )
keyboard.add(button_geo)
bot.send_message(message.chat.id, "Привет! Нажми на кнопку и передай мне свое местоположение", reply_markup=keyboard)
@bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
if call.data == "yes": #call.data это callback_data, которую мы указали при объявлении кнопки
#код сохранения данных, или их обработки
mydata = c.execute("DELETE FROM Users WHERE (id = ?) ",
(call.from_user.id,))
conn.commit()
id = call.from_user.id
add_user(id, name, surname, age, longitude, latitude)
print("""
---- \n
New/Edit User
ID - """+ str(id) +"""
Name - """+ str(name) + """
Surname - """ + str(surname) + """
Age - """ + str(age) + """
Location - latitude: %s; longitude: %s """% (latitude, longitude)+ """
----
""")
key = telebot.types.ReplyKeyboardMarkup(True, False)
user_markup = telebot.types.ReplyKeyboardMarkup(True)
user_markup.row('Поиск пары', 'Найти тренера')
user_markup.row('Посмотреть анкету ')
user_markup.row('Ближайшая открытая тренировка')
bot.send_message(call.from_user.id, 'Запомню)', reply_markup=user_markup)
elif call.data == "no":
bot.send_message(call.message.chat.id, 'Мне пофиг, будешь ' + name + ' ' + surname);
if call.data == "yes1": # call.data это callback_data, которую мы указали при объявлении кнопки
bot.send_message(call.from_user.id, 'Как тебя зовут?');
bot.register_next_step_handler(namepromo, get_name);
elif call.data == "no1":
bot.send_message(call.message.chat.id, 'Хорошо ' + name + ' ' + surname);
@bot.message_handler(content_types=['location'])
def location(message):
if message.location is not None:
print(message.location)
print("latitude: %s; longitude: %s" % (message.location.latitude, message.location.longitude))
global latitude, longitude
latitude = message.location.latitude
longitude = message.location.longitude
user_markup = telebot.types.ReplyKeyboardMarkup(True)
user_markup.row('Поиск пары', 'Найти тренера')
user_markup.row('Посмотреть анкету ')
user_markup.row('Ближайшая открытая тренировка')
bot.send_message(message.from_user.id, 'Геолокация отправлена.', reply_markup=user_markup)
keyboard = types.InlineKeyboardMarkup(); # наша клавиатура
key_yes = types.InlineKeyboardButton(text='Да', callback_data='yes'); # кнопка «Да»
keyboard.add(key_yes); # добавляем кнопку в клавиатуру
key_no = types.InlineKeyboardButton(text='Нет', callback_data='no');
keyboard.add(key_no);
question = 'Тебе ' + str(age) + ' лет, тебя зовут ' + name + ' ' + surname + '?';
bot.send_message(message.from_user.id, text=question, reply_markup=keyboard)
bot.polling(none_stop=True, interval=0) |