new fixes for main.py

This commit is contained in:
KerradKerridi
2022-09-15 22:06:33 +03:00
parent 7dc23a63c2
commit 9814d1510d

165
main.py
View File

@@ -67,24 +67,23 @@ def telegram_bot():
item1 = types.KeyboardButton("📢Предложить свой пост") item1 = types.KeyboardButton("📢Предложить свой пост")
item2 = types.KeyboardButton("📩Связаться с админами") item2 = types.KeyboardButton("📩Связаться с админами")
item3 = types.KeyboardButton("❌Удалить пост") item3 = types.KeyboardButton("❌Удалить пост")
item4 = types.KeyboardButton("🎧Войти в режим стендапа")
if BotDB.user_exists(user_id): if BotDB.user_exists(user_id):
is_need_sticker = BotDB.get_info_about_stickers(user_id=message.from_user.id) is_need_sticker = BotDB.get_info_about_stickers(user_id=message.from_user.id)
if is_need_sticker == 0: if is_need_sticker == 0:
item5 = types.KeyboardButton("🤪Хочу стикеры") item5 = types.KeyboardButton("🤪Хочу стикеры")
BotDB.update_info_about_stickers(user_id=message.from_user.id) BotDB.update_info_about_stickers(user_id=message.from_user.id)
markup.add(item1, item2, item3, item4, item5) markup.add(item1, item2, item3, item5)
else: else:
markup.add(item1, item2, item3, item4) markup.add(item1, item2, item3)
else: else:
BotDB.add_new_user_in_db(user_id, first_name, full_name, username, is_bot, language_code, date_added, date_changed) BotDB.add_new_user_in_db(user_id, first_name, full_name, username, is_bot, language_code, date_added, date_changed)
is_need_sticker = BotDB.get_info_about_stickers(user_id=message.from_user.id) is_need_sticker = BotDB.get_info_about_stickers(user_id=message.from_user.id)
if is_need_sticker == 0: if is_need_sticker == 0:
item5 = types.KeyboardButton("🤪Хочу стикеры") item5 = types.KeyboardButton("🤪Хочу стикеры")
BotDB.update_info_about_stickers(user_id=message.from_user.id) BotDB.update_info_about_stickers(user_id=message.from_user.id)
markup.add(item1, item2, item3, item4, item5) markup.add(item1, item2, item3, item5)
else: else:
markup.add(item1, item2, item3, item4) markup.add(item1, item2, item3)
hello_message = BotDB.get_message_from_db('start_message', first_name) hello_message = BotDB.get_message_from_db('start_message', first_name)
bot.send_message(message.chat.id, hello_message, parse_mode='html', reply_markup=markup, disable_web_page_preview=not PREVIEW_LINK) bot.send_message(message.chat.id, hello_message, parse_mode='html', reply_markup=markup, disable_web_page_preview=not PREVIEW_LINK)
except: except:
@@ -98,9 +97,8 @@ def telegram_bot():
item1 = types.KeyboardButton("📢Предложить свой пост") item1 = types.KeyboardButton("📢Предложить свой пост")
item2 = types.KeyboardButton("📩Связаться с админами") item2 = types.KeyboardButton("📩Связаться с админами")
item3 = types.KeyboardButton("❌Удалить пост") item3 = types.KeyboardButton("❌Удалить пост")
item4 = types.KeyboardButton("🎧Войти в режим стендапа")
item5 = types.KeyboardButton("👋🏼Сказать пока!") item5 = types.KeyboardButton("👋🏼Сказать пока!")
markup.add(item1, item2, item3, item4, item5) markup.add(item1, item2, item3, item5)
bot.send_message(message.chat.id, bot.send_message(message.chat.id,
"Выбери нужную кнопку внизу экрана".format( "Выбери нужную кнопку внизу экрана".format(
message.from_user, bot.get_me()), message.from_user, bot.get_me()),
@@ -140,45 +138,6 @@ def telegram_bot():
message_id=message.message_id) message_id=message.message_id)
bot.register_next_step_handler(msg, resend_message_in_group_for_message) bot.register_next_step_handler(msg, resend_message_in_group_for_message)
elif message.text == "🎧Войти в режим стендапа":
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
item1 = types.KeyboardButton("🎤Высказаться")
item2 = types.KeyboardButton("🎧Послушать")
item3 = types.KeyboardButton("🔙Вернуться в меню")
markup.add(item1, item2, item3)
first_name = message.from_user.first_name
message_for_standup = BotDB.get_message_from_db('message_for_standup', first_name)
#logging
if LOGS:
bot.forward_message(chat_id=GROUP_FOR_LOGS,
from_chat_id=message.chat.id,
message_id=message.message_id)
bot.send_message(message.chat.id, message_for_standup, parse_mode='html', reply_markup=markup,
disable_web_page_preview=not PREVIEW_LINK)
#функция с отображением сообщения "Последнее сообщение было записано"
date_from_db = BotDB.last_date_audio()
parse_date = datetime.strptime(date_from_db, "%Y-%m-%d %H:%M:%S")
last_voice_time_timestamp = time.mktime(parse_date.timetuple())
time_now_timestamp = time.time()
date_difference = time_now_timestamp - last_voice_time_timestamp
# считаем минуты, часы, дни
much_minutes_ago = round(date_difference / 60, 0)
much_hour_ago = round(date_difference / 3600, 0)
much_days_ago = int(round(much_hour_ago / 24, 0))
message_with_date = ''
if much_minutes_ago <= 60:
word_minute = plural_time(1, much_minutes_ago)
message_with_date = f'<b>Последнее сообщение было записано {word_minute} назад</b>'
elif much_minutes_ago > 60 and much_hour_ago <= 24:
word_hour = plural_time(2, much_hour_ago)
message_with_date = f'<b>Последнее сообщение было записано {word_hour} назад</b>'
elif much_hour_ago > 24:
word_day = plural_time(3, much_days_ago)
message_with_date = f'<b>Последнее сообщение было записано {word_day} назад</b>'
msg = bot.send_message(chat_id=message.chat.id, text=message_with_date, parse_mode="html")
bot.register_next_step_handler(msg, standup)
elif message.text == "❌Удалить пост": elif message.text == "❌Удалить пост":
#TODO: требует автоматизации. На входе говорим пришли мне пост, на выходе получаем идентификатор поста, удаляем из ТГ. Насчет удаления из ВК надо подумать #TODO: требует автоматизации. На входе говорим пришли мне пост, на выходе получаем идентификатор поста, удаляем из ТГ. Насчет удаления из ВК надо подумать
@@ -222,9 +181,8 @@ def telegram_bot():
item1 = types.KeyboardButton("📢Предложить свой пост") item1 = types.KeyboardButton("📢Предложить свой пост")
item2 = types.KeyboardButton("📩Связаться с админами") item2 = types.KeyboardButton("📩Связаться с админами")
item3 = types.KeyboardButton("❌Удалить пост") item3 = types.KeyboardButton("❌Удалить пост")
item4 = types.KeyboardButton("🎧Войти в режим стендапа")
item5 = types.KeyboardButton("👋🏼Сказать пока!") item5 = types.KeyboardButton("👋🏼Сказать пока!")
markup.add(item1, item2, item3, item4, item5) markup.add(item1, item2, item3, item5)
try: try:
if LOGS: if LOGS:
bot.forward_message(chat_id=GROUP_FOR_LOGS, bot.forward_message(chat_id=GROUP_FOR_LOGS,
@@ -250,117 +208,6 @@ def telegram_bot():
message_id=message.message_id) message_id=message.message_id)
bot.register_next_step_handler(message, callback=go_send_messages) bot.register_next_step_handler(message, callback=go_send_messages)
def standup(message):
# Клавиатуру добавляем
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
item1 = types.KeyboardButton("🎤Высказаться")
item2 = types.KeyboardButton("🎧Послушать")
item3 = types.KeyboardButton("🔙Вернуться в меню")
markup.add(item1, item2, item3)
try:
if message.text == '🎤Высказаться' or message.text == '🎤Высказаться еще':
markup = types.ReplyKeyboardRemove()
if TEST:
bot.forward_message(chat_id=GROUP_FOR_LOGS, from_chat_id=message.chat.id, message_id=message.id)
msg = bot.send_message(chat_id=message.chat.id, text='Хорошо, теперь пришли мне свое голосовое сообщение', reply_markup=markup)
bot.register_next_step_handler(msg, save_voice_message)
elif message.text == '🎧Послушать':
check_audio = BotDB.check_listen_audio(user_id=message.from_user.id)
list_audio = list(check_audio)
if TEST:
bot.forward_message(chat_id=GROUP_FOR_LOGS, from_chat_id=message.chat.id, message_id=message.id)
if list_audio == []:
msg = bot.send_message(message.chat.id, 'Прости, ты прослушал все аудио😔. Возвращайся позже, возможно наша база пополнится', reply_markup=markup)
bot.register_next_step_handler(msg, standup)
else:
number_element = random.randint(0, len(list_audio) - 1)
audio_for_user = check_audio[number_element]
path = Path(f'voice_users/{audio_for_user}.ogg')
voice = open(path, 'rb')
#Маркируем сообщение как прослушанное
BotDB.mark_listened_audio(audio_for_user, user_id=message.from_user.id)
msg = bot.send_voice(message.chat.id, voice=voice, reply_markup=markup)
bot.register_next_step_handler(msg, standup)
elif message.text == '🔙Вернуться в меню':
if TEST:
bot.forward_message(chat_id=GROUP_FOR_LOGS, from_chat_id=message.chat.id, message_id=message.id)
after_post(message=message)
else:
msg = bot.send_message(chat_id=message.chat.id, text='Я тебя не понял, воспользуйся меню', reply_markup=markup)
bot.register_next_step_handler(msg, standup)
except:
if LOGS:
bot.send_message(chat_id=IMPORTANT_LOGS, text=BotDB.get_error_message_from_db(4))
def plural_time(type, n):
word = []
if type == 1:
word = ['минуту', 'минуты', 'минут']
elif type == 2:
word = ['час', 'часа', 'часов']
elif type == 3:
word = ['день', 'дня', 'дней']
else:
pass
if n % 10 == 1 and n % 100 != 11:
p = 0
elif 2 <= n % 10 <= 4 and (n % 100 < 10 or n % 100 >= 20):
p = 1
else:
p = 2
return str(n) + ' ' + word[p]
def save_voice_message(message):
if message.content_type == 'voice':
if TEST:
bot.forward_message(chat_id=GROUP_FOR_LOGS, from_chat_id=message.chat.id, message_id=message.id)
file_name = ''
file_id = 1
#Проверяем что запись о файле есть в базе данных
is_having_audio_from_user = BotDB.get_last_user_audio_record(user_id=message.from_user.id)
if is_having_audio_from_user is False:
#Если нет, то генерируем имя файла
file_name = f'message_from_{message.from_user.id}_number_{file_id}'
else:
#Иначе берем последнюю запись из БД, добавляем к ней 1, и создаем новую запись
file_name = BotDB.get_path_for_audio_record(user_id=message.from_user.id)
file_id = BotDB.get_id_for_audio_record(message.from_user.id) + 1
path = Path(f'voice_users/{file_name}.ogg')
if path.exists():
file_name = f'message_from_{message.from_user.id}_number_{file_id}'
else:
pass
#Собираем инфо о сообщении
author_id = message.from_user.id
time_UTC = int(time.time())
date_added = datetime.fromtimestamp(time_UTC)
#Сохраняем в базку
BotDB.add_audio_record(file_name, author_id, date_added, 0, file_id)
#Сохраняем файл на сервер
file_info = bot.get_file(message.voice.file_id)
downloaded_file = bot.download_file(file_info.file_path)
with open(f'voice_users/{file_name}.ogg', 'wb') as new_file:
new_file.write(downloaded_file)
#инициализируем кнопки
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
item1 = types.KeyboardButton("🔙Вернуться в меню")
markup.add(item1)
bot.send_message(chat_id=message.chat.id, text='Окей, сохранил!👌', reply_markup=markup)
#menu_standup(message=message)
bot.register_next_step_handler(message, standup)
else:
#TODO: Если пришлют фото, он не работает
if TEST:
bot.forward_message(chat_id=GROUP_FOR_LOGS, from_chat_id=message.chat.id, message_id=message.id)
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
item1 = types.KeyboardButton("🔙Вернуться в меню")
markup.add(item1)
msg = bot.send_message(chat_id=message.chat.id, text='Я тебя не понимаю🤷‍♀️ запиши голосовое', reply_markup=markup)
bot.register_next_step_handler(msg, standup)
def resend_message_in_group_for_post(message): def resend_message_in_group_for_post(message):
markup = types.InlineKeyboardMarkup(row_width=1) markup = types.InlineKeyboardMarkup(row_width=1)
item1 = types.InlineKeyboardButton("Опубликовать", callback_data='post_post_post') item1 = types.InlineKeyboardButton("Опубликовать", callback_data='post_post_post')