-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
348 lines (279 loc) · 15.1 KB
/
main.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
import sys
import csv
from collections import OrderedDict
from loguru import logger
import telebot
from telebot import types
import settings
bot = telebot.TeleBot(settings.TOKEN)
logger.add("bot.log", format="[{time}] {level}: {message}", level="INFO", backtrace=True, diagnose=True)
logger.configure()
def get_next_game_info(callback):
bot.answer_callback_query(callback.id)
try:
with open('data/location.txt', encoding='utf-8') as file:
content = file.read()
if content != '':
bot.send_message(callback.from_user.id, content)
with open('data/image.jpg', 'rb') as photo:
bot.send_photo(callback.from_user.id, photo)
else:
bot.send_message(callback.from_user.id, 'Информации нет!')
except FileNotFoundError:
bot.send_message(callback.from_user.id, 'Информации нет!')
except IndexError:
pass
def get_players_list_for_next_game(callback):
bot.answer_callback_query(callback.id)
try:
with open('data/players.csv', encoding='utf-8') as cvsfile:
reader = csv.reader(cvsfile)
spisok = [' '.join(map(str, i)) for i in reader]
players_list = [f'{i + 1}) {spisok[i]}' for i in range(len(spisok))]
if spisok == []:
bot.send_message(callback.from_user.id, f"Состав на ближайшую игру:\n-")
else:
players_list = '\n'.join(players_list)
bot.send_message(callback.from_user.id, f"Состав на ближайшую игру:\n{players_list}")
except FileNotFoundError:
bot.send_message(callback.from_user.id, 'Состав на ближайшую игру:\n-')
except IndexError:
pass
def vote_i_play(callback):
bot.answer_callback_query(callback.id)
# bot.send_message(callback.from_user.id, callback.data)
# сразу формируем список игроков в формате:
# [{'id':<id>, 'name': <name},...]
# будем в этот список сперва считывать данные, затем его дополнять и
# на его основе формировать новое содержимое файла
players_list = []
try:
with open('data/players.csv', encoding='utf-8', mode="r", newline='') as csvfile:
reader = csv.reader(csvfile)
players_list = [{'id': i[0], 'name': i[1]} for i in reader]
for el in players_list:
if int(el['id']) == callback.from_user.id:
# если мы уже в списке, то вызываем return, чтобы дальше не исполнять код!
# и тогда дальше можно обойтись без лишних if-ов и т.д.
return bot.send_message(
callback.from_user.id,
f"{callback.from_user.first_name}, ты уже есть в списке"
)
except FileNotFoundError:
pass
except IndexError:
pass
players_list.append({
'id': callback.from_user.id,
'name': callback.from_user.first_name
})
with open('data/players.csv', 'w', encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
for player in players_list:
writer.writerow([player['id'], player['name']])
bot.send_message(callback.from_user.id, f"{callback.from_user.first_name}, добавлен в список")
def vote_i_dont_play(callback):
bot.answer_callback_query(callback.id)
players_list = []
try:
with open('data/players.csv', encoding='utf-8', mode="r", newline='') as csvfile:
reader = csv.reader(csvfile)
players_list = [{'id': i[0], 'name': i[1]} for i in reader]
if {'id': str(callback.from_user.id), 'name': callback.from_user.first_name} not in players_list:
# если мы уже в списке, то вызываем return, чтобы дальше не исполнять код!
# и тогда дальше можно обойтись без лишних if-ов и т.д.
return bot.send_message(
callback.from_user.id,
f"{callback.from_user.first_name}, тебя нет в списке"
)
except FileNotFoundError:
pass
except IndexError:
pass
players_list.remove({
'id': str(callback.from_user.id),
'name': callback.from_user.first_name
})
with open('data/players.csv', 'w', encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
for player in players_list:
writer.writerow([player['id'], player['name']])
bot.send_message(callback.from_user.id, f"{callback.from_user.first_name}, удален из списка")
# Ключ словаря - текстовая команда, занчение по ключу - функция обработчий этой команды
common_commands_with_handlers = OrderedDict()
common_commands_with_handlers["Информация о ближайшей игре"] = get_next_game_info
common_commands_with_handlers["Состав на ближайшую игру"] = get_players_list_for_next_game
common_commands_with_handlers["Я играю"] = vote_i_play
common_commands_with_handlers["Я не играю"] = vote_i_dont_play
def get_common_commands_keyboard():
keyboard = types.InlineKeyboardMarkup()
for command in common_commands_with_handlers:
keyboard.add(types.InlineKeyboardButton(text=command, callback_data=command))
return keyboard
def change_next_game_info(callback):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
btn1 = types.KeyboardButton("Изменить фото")
btn2 = types.KeyboardButton("Изменить текст")
btn3 = types.KeyboardButton("Отмена")
markup.add(btn1, btn2, btn3)
bot.send_message(callback.from_user.id, text='Что изменить?', reply_markup=markup)
def edit_description(message):
if message.from_user.id in settings.ADMINS_LIST:
try:
if message.text != 'Отмена':
with open('data/location.txt', 'w', encoding='utf-8') as file:
file.write(message.text)
bot.send_message(message.chat.id, 'Сохранил текст')
else:
bot.send_message(message.chat.id, text=f'Процесс прерван')
except:
bot.send_message(message.chat.id, 'Что-то пошло не так, процесс прерван')
else:
bot.send_message(message.chat.id, 'Что-то пошло не так, процесс прерван')
def edit_photo(message):
if message.from_user.id in settings.ADMINS_LIST:
if message.text != 'Удалить':
try:
file_info = bot.get_file(message.photo[len(message.photo) - 1].file_id)
downloaded_file = bot.download_file(file_info.file_path)
with open('data/image.jpg', 'wb') as new_file:
new_file.write(downloaded_file)
bot.send_message(message.chat.id, 'Сохранил фото')
except:
bot.send_message(message.chat.id, 'Что-то пошло не так, процесс прерван')
else:
with open('data/image.jpg', 'w') as new_file:
pass
bot.send_message(message.chat.id, 'Фото удалено')
else:
bot.send_message(message.chat.id, 'Процесс прерван')
def back(callback):
bot.answer_callback_query(callback.id)
bot.edit_message_reply_markup(callback.from_user.id, callback.message.id,
reply_markup=get_admin_commands_keyboard())
def remove_player(callback):
bot.answer_callback_query(callback.id)
try:
with open('data/players.csv', encoding='utf-8') as cvsfile:
reader = csv.reader(cvsfile)
spisok = [' '.join(map(str, i)) for i in reader]
players_list = [f'{spisok[i]}' for i in range(len(spisok))]
if spisok == []:
return bot.send_message(callback.from_user.id, f"Список пуст")
else:
bot.edit_message_reply_markup(callback.from_user.id, callback.message.id,
reply_markup=get_players(players_list))
except FileNotFoundError:
pass
def refresh_players_list(callback):
bot.answer_callback_query(callback.id)
with open('data/players.csv', encoding='utf-8', mode="w") as csvfile:
csv.reader(csvfile)
bot.send_message(callback.from_user.id, 'Список обновлен')
def send_message_all_users(callback):
bot.answer_callback_query(callback.id)
users = []
with open('data/users.txt', encoding='utf-8') as file:
for i in file.readlines():
users.append(i.rstrip())
for i in users:
try:
bot.send_message(i, '''Привет!
Мы все тебя ждем в рядах нашей команды!
Не забывай отмечаться, а именно нажимать кнопку "Я играю"
Вся подробная информация о предстоящей игре располагается в разделе "Информация о ближайшей игре"''')
except:
pass
admin_commands_with_handlers = OrderedDict()
admin_commands_with_handlers["Изменить инф-цию о следующей игре"] = change_next_game_info
admin_commands_with_handlers["Удалить игрока"] = remove_player
admin_commands_with_handlers["Рассылка сообщения"] = send_message_all_users
admin_commands_with_handlers["Удалить всех игроков"] = refresh_players_list
edit_info_commands_with_handlers = OrderedDict()
edit_info_commands_with_handlers["<-- назад"] = back
def get_admin_commands_keyboard():
keyboard = types.InlineKeyboardMarkup()
for command in admin_commands_with_handlers:
keyboard.add(types.InlineKeyboardButton(text=command, callback_data=command))
return keyboard
def players_list_command_delete(callback):
bot.answer_callback_query(callback.id)
data = callback.data.split()
players_list = []
try:
with open('data/players.csv', encoding='utf-8', mode="r") as csvfile:
reader = csv.reader(csvfile)
players_list = [{'id': i[0], 'name': i[1]} for i in reader]
if {'id': data[0], 'name': data[1]} not in players_list:
# если мы уже в списке, то вызываем return, чтобы дальше не исполнять код!
# и тогда дальше можно обойтись без лишних if-ов и т.д.
return bot.send_message(
callback.from_user.id,
f"{callback.from_user.first_name}, скорее всего список устарел"
)
except FileNotFoundError:
pass
try:
players_list.remove({
'id': data[0],
'name': data[1]
})
with open('data/players.csv', 'w', encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
for player in players_list:
writer.writerow([player['id'], player['name']])
bot.send_message(callback.from_user.id, f"{data[1]}, удален из списка")
except ValueError:
pass
def get_players(players: list):
keyboard = types.InlineKeyboardMarkup()
for command in players:
keyboard.add(types.InlineKeyboardButton(text=command, callback_data=command))
keyboard.add(types.InlineKeyboardButton(text='<-- назад', callback_data='<-- назад'))
return keyboard
@bot.message_handler(commands=['start'])
def open_common_commands(message):
logger.info(f"User {message.from_user.id} asks for commands")
bot.send_message(message.chat.id, 'Выберите команду', reply_markup=get_common_commands_keyboard())
# @bot.message_handler(content_types=['text', 'photo'])
@bot.message_handler(commands=['admin'])
def open_admin_commands(message):
if message.from_user.id in settings.ADMINS_LIST:
logger.info(f"User {message.from_user.id} asks for admin commands")
return bot.send_message(message.chat.id, 'Выберите команду', reply_markup=get_admin_commands_keyboard())
logger.warning(f"User {message.from_user.id} tried to get admin commands without permissions!")
bot.send_message(message.chat.id, text='Недостаточно прав')
@bot.callback_query_handler(func=lambda message: True)
def process_callback(callback):
logger.info(f"Callback command '{callback.data}' from User {callback.from_user.id}")
if callback.data in common_commands_with_handlers:
common_commands_with_handlers[callback.data](callback)
elif callback.data == 'Изменить инф-цию о следующей игре' and callback.from_user.id in settings.ADMINS_LIST:
change_next_game_info(callback)
elif callback.data in admin_commands_with_handlers and callback.from_user.id in settings.ADMINS_LIST:
admin_commands_with_handlers[callback.data](callback)
elif callback.data in edit_info_commands_with_handlers and callback.from_user.id in settings.ADMINS_LIST:
edit_info_commands_with_handlers[callback.data](callback)
elif callback.from_user.id in settings.ADMINS_LIST:
players_list_command_delete(callback)
else:
bot.send_message(callback.from_user.id,
f'{callback.from_user.first_name}, недостаточно прав для выполнения операции')
@bot.message_handler(content_types=['text', 'photo'])
def text_message_handler(message):
logger.info(f"Text command '{message.text}' from User {message.from_user.id}")
remove = telebot.types.ReplyKeyboardRemove()
if message.text == '@football_tatarlar_Bot':
open_common_commands(message)
elif message.text == 'Изменить фото' and message.from_user.id in settings.ADMINS_LIST:
bot.send_message(message.chat.id, text='Отправьте новое фото, если хотите удалить, введите "Удалить"', reply_markup=remove)
bot.register_next_step_handler(message, edit_photo)
elif message.text == "Изменить текст" and message.from_user.id in settings.ADMINS_LIST:
bot.send_message(message.chat.id, text='Введите новую информацию , если передумали, введите "Отмена"', reply_markup=remove)
bot.register_next_step_handler(message, edit_description)
elif message.text == "Отмена" and message.from_user.id in settings.ADMINS_LIST:
bot.send_message(message.chat.id, text='Убрал', reply_markup=remove)
else:
pass
if __name__ == '__main__':
bot.infinity_polling(timeout=10, long_polling_timeout = 5)