-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
438 lines (387 loc) · 20.8 KB
/
bot.py
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
from telebot.types import InlineKeyboardButton, InlineKeyboardMarkup
from telebot import types
import telebot
import config
from modules.scripts import *
from modules.commands import *
bot = telebot.TeleBot(config.API) # создание бота
# КЛАВИАТУРЫ
btn_return_settings = InlineKeyboardButton("< Назад", callback_data='settings')
btn_settings = InlineKeyboardButton("⚙️Настройки", callback_data='settings')
btn_return_main = InlineKeyboardButton(text="< Назад", callback_data='return:main')
keyboard_link = InlineKeyboardMarkup()
btn_link = InlineKeyboardButton("Перейти в бота", url='https://t.me/mood_jar_bot')
keyboard_link.add(btn_link)
def send_message(message, mood, call, topic_list=None):
message_id = call.message.message_id
add_mood(message.chat.id, mood, message.text, topic_list)
bot.delete_message(message.chat.id, message.message_id)
keyboard_main = create_keyboard_main(message.chat.id)
bot.edit_message_text(chat_id=message.chat.id, message_id=message_id, text="Добавить настроение", reply_markup=keyboard_main)
send_mood_friend(message.chat.id, mood, message.text, topic_list)
bot.answer_callback_query(call.id, "Настроение сохранено!")
def get_value(message, edit, smile, message_id):
get_text = message.text
result = edit_value(message.chat.id, edit, smile, get_text)
bot.delete_message(message.chat.id, message.message_id)
keyboard = InlineKeyboardMarkup()
btn = InlineKeyboardButton("< Назад", callback_data=f"edit:{edit}")
keyboard.add(btn)
keyboard_edit(edit, message.chat.id, message_id)
def send_mood_friend(user_id, mood, text=None, topics=None):
text = mood_message_friends(user_id, mood, text, topics)
keyboard = keyboard_notif()
for user_id, message_text in text:
try:
friend_id = SQL_request("SELECT telegram_id FROM users WHERE id = ?", (int(user_id),))
bot.send_message(friend_id[0], message_text, reply_markup=keyboard)
except Exception as e:
print(f"Чат {friend_id[0]} не найден")
print(e)
def keyboard_edit(find, user_id, message_id):
keyboard = InlineKeyboardMarkup(row_width=2)
result = SQL_request(f"SELECT {find} FROM users WHERE telegram_id = ?", (user_id,))
result = result[0]
if result == None:
result = "{}"
result = json.loads(result)
type_edit = "настроение"
if find == "friends":
type_edit = "друга"
data = result
btn_add = InlineKeyboardButton(text="Пригласить друга", switch_inline_query="")
elif find == "topics":
type_edit = "топик"
data = result
btn_add = InlineKeyboardButton("Добавить +", callback_data=f'add:{find}')
else:
btn_add = InlineKeyboardButton("Добавить +", callback_data=f'add:{find}')
data = {}
for key, value in result.items():
new_value = f"{key} {value}"
data[new_value] = key
buttons = create_buttons(data, f'rename_{find}')
keyboard.add(*buttons)
keyboard.add(btn_return_settings, btn_add)
bot.edit_message_text(chat_id=user_id, message_id=message_id, text=f"Выберите {type_edit}, что бы его изменить", reply_markup=keyboard)
def create_buttons(data, prefix):
buttons = []
for text, callback in data.items():
if not isinstance(text, str):
text = str(text)
if callback == "":
callback = text
if prefix == "rename_friends" or prefix == "profile" or prefix == 'rename_topics' or prefix == "topics" or prefix == "select_topics":
button = types.InlineKeyboardButton(callback, callback_data=f'{prefix}:{text}')
elif prefix == "mood":
button = types.InlineKeyboardButton(text, callback_data=f'{prefix}:{text}')
else:
button = types.InlineKeyboardButton(text, callback_data=f'{prefix}:{callback}')
buttons.append(button)
return buttons
def create_keyboard_main(user_id):
user = SQL_request("SELECT * FROM users WHERE telegram_id = ?", (int(user_id),))
mood = user[7]
if mood is None or mood == "{}" or mood == json.dumps({}):
buttons = []
btn_add_mood = InlineKeyboardButton("Добавить настроение +", callback_data='add:mood')
buttons.append(btn_add_mood)
else:
mood_dict = json.loads(mood)
buttons = create_buttons(mood_dict, "mood")
btn_profile = InlineKeyboardButton(text="👤 Профиль", callback_data=f"profile:{user[0]}")
keyboard_main = InlineKeyboardMarkup(row_width=3)
keyboard_main.add(*buttons)
if user[2] == None or user[2] == json.dumps({}):
btn_my_friends = InlineKeyboardButton(text="Пригласить друга", switch_inline_query="")
else:
btn_my_friends = InlineKeyboardButton(text="👥 Друзья", callback_data='friends')
keyboard_main.add(btn_my_friends, btn_profile)
return keyboard_main
def create_keyboard_mood_settings(user_id, select_topics=False):
user = SQL_request("SELECT * FROM users WHERE telegram_id = ?", (int(user_id),))
topics = user[5]
if topics is None or topics == "{}" or topics == json.dumps({}):
buttons = []
btn_add_mood = InlineKeyboardButton("Добавить топик +", callback_data='add:topics')
buttons.append(btn_add_mood)
else:
topics_dict = json.loads(topics)
if select_topics:
for key, value in topics_dict.items():
if value in select_topics:
topics_dict[key] = "✅ " + value
buttons = create_buttons(topics_dict, "select_topics")
keyboard = InlineKeyboardMarkup(row_width = 3)
btn_skip = InlineKeyboardButton(text="Пропустить >", callback_data='skip')
keyboard.add(*buttons)
keyboard.add(btn_return_main, btn_skip)
return keyboard
def create_keyboard_profile(user_id):
keyboard = InlineKeyboardMarkup(row_width=2)
btn_info = InlineKeyboardButton("ℹ️ Информация", callback_data=f'info:{user_id}')
btn_reasons = InlineKeyboardButton("Подробнее", callback_data=f'more_reasons:{user_id}')
keyboard.add(btn_info, btn_reasons)
return keyboard
def create_keyboard_settings(user_id):
emojis = ["😊", "😂", "🥳", "😎", "😢", "😡", "😍", "🤔", "🤯", "🤗"]
random_emoji = random.choice(emojis)
keyboard = InlineKeyboardMarkup(row_width=2)
btn_edit_mood = InlineKeyboardButton(f"{random_emoji} Настроения", callback_data='edit:mood')
btn_edit_topics = InlineKeyboardButton("Ⓜ️ Топики", callback_data='edit:topics')
btn_edit_friends = InlineKeyboardButton("👥 Друзья", callback_data='edit:friends')
btn_return_profile = InlineKeyboardButton("< Назад", callback_data=f'profile:{user_id}')
keyboard.add(btn_edit_mood, btn_edit_friends, btn_edit_topics)
keyboard.add(btn_return_profile)
return keyboard
def keyboard_notif():
btn = InlineKeyboardButton("Прочитано", callback_data="send")
keyboard = InlineKeyboardMarkup()
keyboard.add(btn)
return keyboard
def keyboard_return(back):
btn = InlineKeyboardButton("< Назад", callback_data=back)
keyboard = InlineKeyboardMarkup()
keyboard.add(btn)
return keyboard
# КОМАНДЫ
@bot.message_handler(commands=['start']) # обработка команды start
def start(message):
menu_id = registration(message)
keyboard_main = create_keyboard_main(message.chat.id)
text = "Добавить настроение"
if message.chat.id == config.ADMIN:
text = f"{VERSION}\n\n{text}"
bot.send_message(message.chat.id, text, reply_markup=keyboard_main)
bot.delete_message(message.chat.id, message.id)
if menu_id:
bot.delete_message(message.chat.id, menu_id)
@bot.inline_handler(lambda query: query.query == '' or not query.query)
def default_query(inline_query):
user_id = inline_query.from_user.id
user = SQL_request("SELECT * FROM users WHERE telegram_id = ?", (int(user_id),))
date, time = now_time()
text = get_mood_data(user[0], date)
results = [
types.InlineQueryResultArticle(
id='my_mood',
title='Моя банка',
thumbnail_url="https://falbue.github.io/classroom-code/icons/registr.png",
description='Отправить мою банку',
input_message_content=types.InputTextMessageContent(
message_text=text
)
),
types.InlineQueryResultArticle(
id='invite',
title='Приглашение',
thumbnail_url="https://falbue.github.io/classroom-code/icons/registr.png",
description='Отправить приглашение',
input_message_content=types.InputTextMessageContent(
message_text="Приглашение, добавления в друзья"
),
reply_markup=types.InlineKeyboardMarkup().add(
types.InlineKeyboardButton(
text='Принять',
callback_data=f"invite:{user[0]}"
)
)
)
]
bot.answer_inline_query(inline_query.id, results, cache_time=0)
# ОБРАБОТКА ВЫЗОВОВ
@bot.callback_query_handler(func=lambda call: True)
def callback_query(call): # работа с вызовами inline кнопок
if (call.data).split(":")[0] == 'invite':
user_id = call.from_user.id
my_id = call.data.split(":")[1]
result = add_friends(my_id, user_id, call)
if result != False:
bot.edit_message_text(chat_id=None, inline_message_id=call.inline_message_id, text=result, reply_markup=keyboard_link)
else:
user_id = call.message.chat.id
bot.clear_step_handler_by_chat_id(chat_id=user_id)
message_id = call.message.message_id
user = SQL_request("SELECT * FROM users WHERE telegram_id = ?", (int(user_id),))
SQL_request("UPDATE users SET username = ? WHERE telegram_id = ?", (call.from_user.username, user_id))
print(f"{user_id}: {call.data}")
if ((call.data).split(":")[0]).split("-")[0] == 'profile':
profile_id = (call.data).split(":")[1]
user = SQL_request("SELECT * FROM users WHERE id = ?", (int(profile_id),))
my_id = SQL_request("SELECT id FROM users WHERE telegram_id = ?", (int(user_id),))
btn_check_another_day = InlineKeyboardButton("Другие дни", callback_data=f"another_day:{profile_id}")
if len(((call.data).split(":")[0]).split("-")) > 1:
if ((call.data).split(":")[0]).split("-")[1] == "notif_friend":
notif_friend((call.data).split(":")[1], ((call.data).split(":")[0]).split("-")[2], my_id[0])
date, time = now_time()
text = get_mood_data(user[0], date)
keyboard = create_keyboard_profile(user[0])
if int((call.data).split(":")[1]) == int(my_id[0]):
keyboard.add(btn_settings, btn_check_another_day)
keyboard.add(btn_return_main)
else:
list_friends = InlineKeyboardButton(text="< Назад", callback_data='friends')
data = SQL_request("SELECT notif_friends FROM users WHERE id = ?", (int(profile_id),))
if data[0]:
data = json.loads(data[0])
try:
if data[f"{my_id[0]}"] == 'close':
btn_friend_notif = InlineKeyboardButton(text="❌ Уведомления", callback_data=f'profile-notif_friend-add:{(call.data).split(":")[1]}')
else:
btn_friend_notif = InlineKeyboardButton(text="✅ Уведомления", callback_data=f'profile-notif_friend-close:{(call.data).split(":")[1]}')
except:
btn_friend_notif = InlineKeyboardButton(text="❌ Уведомления", callback_data=f'profile-notif_friend-add:{(call.data).split(":")[1]}')
else:
btn_friend_notif = InlineKeyboardButton(text="❌ Уведомления", callback_data=f'profile-notif_friend-add:{(call.data).split(":")[1]}')
keyboard.add(btn_friend_notif, btn_check_another_day)
keyboard.add(list_friends)
try:
bot.edit_message_text(chat_id=user_id, message_id=message_id, text=text, reply_markup=keyboard)
except:
bot.edit_message_reply_markup(chat_id=user_id, message_id=message_id, reply_markup=keyboard)
if (call.data).split(":")[0] == 'info':
text = info_user((call.data).split(":")[1])
bot.answer_callback_query(callback_query_id=call.id, show_alert=True, text=text)
if (call.data).split(":")[0] == 'mood':
mood = (call.data).split(":")[1]
text = f"Вы выбрали: {mood}\n\nВведите причину такого настроения"
keyboard = create_keyboard_mood_settings(user_id)
bot.edit_message_text(chat_id=user_id, message_id=message_id, text=text, reply_markup=keyboard)
bot.register_next_step_handler(call.message, send_message, mood, call)
if call.data == 'skip':
text = call.message.text
if "Выбранные топики: " in text:
existing_topics = text.split("Выбранные топики: ")[1]
topic_list = existing_topics.split(", ")
else: topic_list = None
mood = (call.message.text).split(": ")[1].split("\n")[0]
add_mood(user_id, mood, "", topic_list)
keyboard_main = create_keyboard_main(user_id)
text = "Добавить настроение"
bot.edit_message_text(chat_id=user_id, message_id=message_id, text=text, reply_markup=keyboard_main)
send_mood_friend(user_id, mood, topics=topic_list)
if (call.data).split(":")[0] == 'more_reasons':
date, time = now_time()
text = get_mood_data((call.data).split(":")[1], date, "text")
bot.edit_message_text(chat_id=user_id, message_id=message_id, text=text, reply_markup=types.InlineKeyboardMarkup().add(types.InlineKeyboardButton(text='< Назад', callback_data=f'profile:{(call.data).split(":")[1]}')))
if call.data == "friends":
text = user[2]
text = json.loads(text)
buttons = create_buttons(text, "profile")
keyboard = InlineKeyboardMarkup(row_width=2)
keyboard.add(*buttons)
keyboard.add(btn_return_main)
bot.edit_message_text(chat_id=user_id, message_id=message_id, text="Ваши друзья", reply_markup=keyboard, parse_mode="MarkdownV2")
if call.data == 'settings':
user = SQL_request("SELECT * FROM users WHERE telegram_id = ?", (int(user_id),))
keyboard = create_keyboard_settings(user[0])
bot.edit_message_text(chat_id=user_id, message_id=message_id, text="Выберите, что хотите настроить", reply_markup=keyboard)
if (call.data).split(":")[0] == 'edit':
find = (call.data).split(":")[1]
keyboard_edit(find, user_id, message_id)
if (call.data).split("_")[0] == 'rename':
edit = (call.data).split("_")[1]
edit = (edit).split(":")[0]
find = (call.data).split(":")[1]
if edit == "mood":
text = f"Введите новое настроение для {find}"
elif edit == 'friends':
text = f"Введите новое имя для друга"
elif edit == "topics":
text = f"Введите новое название топика"
keyboard = InlineKeyboardMarkup()
btn = InlineKeyboardButton("< Назад", callback_data=f"edit:{edit}")
btn_delete = InlineKeyboardButton("Удалить", callback_data=f'delete_{edit}:{find}')
keyboard.add(btn, btn_delete)
bot.edit_message_text(chat_id=user_id, message_id=message_id, text=text, reply_markup=keyboard)
bot.register_next_step_handler(call.message, get_value, edit, find, message_id)
if (call.data).split("_")[0] == 'delete':
edit = (call.data).split("_")[1]
edit = (edit).split(":")[0]
value = (call.data).split(":")[1]
delete_value(user_id, value, edit)
keyboard_edit(edit, user_id, message_id)
if (call.data).split(":")[0] == "add":
edit = (call.data).split(":")[1]
def next_step(message, edit):
result = add_value(message, edit, edit)
bot.delete_message(message.chat.id, message.message_id)
bot.answer_callback_query(call.id, result["notification"])
keyboard_edit(edit, user_id, message_id)
bot.register_next_step_handler(call.message, next_step, edit)
text = f"Введите смайлик, что бы добавить новое настроение"
keyboard = InlineKeyboardMarkup()
btn = InlineKeyboardButton("< Назад", callback_data=f"edit:{edit}")
keyboard.add(btn)
bot.edit_message_text(chat_id=user_id, message_id=message_id, text=text, reply_markup=keyboard, parse_mode="MarkdownV2")
if call.data.split(":")[0] == "select_topics":
topic_dict = json.loads(user[5])
bot.clear_step_handler_by_chat_id(chat_id=user_id)
topic_id = call.data.split(":")[1]
new_topic = topic_dict.get(topic_id, topic_id)
text = call.message.text
updated_topics = []
if "Выбранные топики: " not in text:
text += f"\n\nВыбранные топики: {new_topic}"
topic_list = [new_topic]
else:
existing_topics = text.split("Выбранные топики: ")[1]
topic_list = existing_topics.split(", ")
if new_topic in topic_list:
topic_list.remove(new_topic)
else:
topic_list.append(new_topic)
text_topic = ", ".join(topic_list)
text = text.split("Выбранные топики: ")[0] + f"Выбранные топики: {text_topic}"
mood = text.split(": ")[1].split("\n")[0]
keyboard = create_keyboard_mood_settings(user_id, topic_list)
bot.edit_message_text(chat_id=user_id, message_id=message_id, text=text, reply_markup=keyboard)
bot.register_next_step_handler(call.message, send_message, mood, call, topic_list)
if (call.data).split(":")[0] == 'return':
if (call.data).split(":")[1] == 'main':
keyboard_main = create_keyboard_main(user_id)
text = "Добавить настроение"
bot.edit_message_text(chat_id=user_id, message_id=message_id, text=text, reply_markup=keyboard_main)
if ((call.data).split(":")[0]).split("-")[0] == 'notif_friend':
type = ((call.data).split(":")[0]).split("-")[1]
friend_id = (call.data).split(":")[1]
if (call.data).split(":")[0] == 'another_day':
profile_id = (call.data).split(":")[1]
jar = SQL_request("SELECT * FROM users WHERE id = ?", (int(profile_id),))
jar = jar[6]
if jar:
jar = json.loads(jar)
dates_list = {date: date for date in jar.keys()}
keyboard = InlineKeyboardMarkup(row_width=3)
buttons = create_buttons(dates_list, f"check_date-{profile_id}")
keyboard.add(*buttons)
btn_return_profile = InlineKeyboardButton("< Назад", callback_data=f'profile:{profile_id}')
keyboard.add(btn_return_profile)
text = "Выберите нужный вам день:"
bot.edit_message_text(chat_id=user_id, message_id=message_id, text=text, reply_markup=keyboard)
else:
text = "Настроение в другие дни не найдено :("
keyboard = keyboard_return(f"profile:{profile_id}")
bot.edit_message_text(chat_id=user_id, message_id=message_id, text=text, reply_markup=keyboard)
if ((call.data).split(":")[0]).split("-")[0] == 'check_date':
date = (call.data).split(":")[1]
profile_id = ((call.data).split(":")[0]).split("-")[1]
text = get_mood_data(profile_id, date, "text")
text = f"{date}\n\n{text}"
keyboard = keyboard_return(f"another_day:{profile_id}")
bot.edit_message_text(chat_id=user_id, message_id=message_id, text=text, reply_markup=keyboard)
if call.data == "send":
bot.delete_message(user_id, message_id)
@bot.message_handler(func=lambda message: True)
def handle_text_message(message): # удаляет сообщения от пользователя
bot.delete_message(message.chat.id, message.message_id)
print(f"бот запущен...")
def start_polling():
while True:
try:
bot.polling(none_stop=True, timeout=60) # Установите таймаут для перезапуска
except Exception as e:
print(f"Ошибка при подключении: {e}")
if __name__ == "__main__":
# start_polling()
bot.polling(none_stop=True, timeout=60)