def god_mode(message): bot.clear_step_handler(message) role = check_superuser(login=message.from_user.username) if role in ('superuser', 'admin'): bot.send_message( chat_id=message.chat.id, text="Привет, {}. \nТебе доступны следующие команды:\n" "/add_phrase,\n/delete_phrase,\n/add_moder,\n/delete_moder." "\nEnjoy.".format(message.from_user.username)) elif role == 'moder': bot.send_message( chat_id=message.chat.id, text="Привет, {}. \nТебе доступны следующие команды:\n" "/add_phrase,\n/delete_phrase." "\nEnjoy.".format(message.from_user.username), parse_mode='Markdown') else: bot.send_message( chat_id=message.chat.id, text='Прости, мама запрещает мне общаться с незнакомцами.', parse_mode='Markdown') bot.send_sticker( chat_id=message.chat.id, sticker= 'CAACAgIAAxkBAAIHmF41kWHKUfajjxb0umLKOG-EMWanAALwLgAC4KOCB2bcGHGkwKtzGAQ' )
def process_subscribe_command_callback(query): try: bot.delete_message(query.message.chat.id, query.message.message_id) if query.data == 'subscribe': bot_users_repository.update_is_subscribed(query.message.chat.id, True) text = 'Вы успешно подписаны на!!' elif query.data == 'unsubscribe': bot_users_repository.update_is_subscribed(query.message.chat.id, False) text = 'Вы успешно отписаны от!!' else: return bot.send_message(query.message.chat.id, text) bot.send_sticker(query.message.chat.id, StickerIds.done) finally: requests_notifier.notify(query.message.chat.id, query.data) logs_repository.add({ 'source': 'User message', 'from_id': query.message.chat.id, 'command': query.data, 'time': datetime.utcnow() })
def inline(message): tekUser = Kepper.find(message) if tekUser == -1: Kepper.NewChat(message.chat.id) tekUser = Kepper.find(message) key = types.InlineKeyboardMarkup() but_1 = types.InlineKeyboardButton(text="Меню", callback_data="Меню") but_2 = types.InlineKeyboardButton(text="Акції", callback_data="Акции") but_22 = types.InlineKeyboardButton(text=" Реєстрація", callback_data="Логотип") but_3 = types.InlineKeyboardButton(text="Наш сайт", url="https://beloesuhoe.com.ua/") key.add(but_1, but_2, but_22, but_3) key_3 = types.InlineKeyboardMarkup() key_3.add(but_3) # bot.send_sticker(message.chat.id,'CAACAgIAAxkBAAIPbV7Q2Hy8VKowsa2XtFqd0MGAgkAnAAIEAANKy2YlI5qz2TO7-rUZBA') # bot.send_sticker(message.chat.id,'CAACAgIAAxkBAAIPbl7Q2U07KhAhcJJBKvbrWDRhAnz4AAIFAANKy2Yl_TTZUhVblp4ZBA') # bot.send_sticker(message.chat.id,'CAACAgIAAxkBAAIPal7QsxOw5wJf1UwnmUGBQL9sexgRAAIDAANKy2YlSiKFGzUAAcOgGQQ') bot.send_sticker( message.chat.id, 'CAACAgIAAxkBAAIPzF7944bl5bpEWECDXAmaIkV6hoJaAAIHAANKy2YlW1fzFXBeESoaBA' ) tekUser.Last_message = bot.send_message( message.chat.id, "Ласкаво просимо до нашого telegram bot", reply_markup=key)
def judge_debt_remind(call): user_id = int(call.data.split('/')[1]) user = User.get(user_id) judge = User.get(call.message.chat.id) ru_text_judge = f'Напоминание доставлено' en_text_judge = f'Reminder delivered' text_judge = ru_text_judge if judge.language_code == 'ru' else en_text_judge print(text_judge) ru_text_user = f'Тут {get_user_naming(judge, "твой друг")} попросил передать кое-что.' en_text_user = f'Here {get_user_naming(judge, "your friend")} asked me to convey something.' text_user = ru_text_user if user.language_code == 'ru' else en_text_user print(text_user) ru_where_money_Lebowsky_sticker = 'CAADAgADnQEAAvnkbAABG-jcw1OqPrAWBA' en_where_money_Lebowsky_sticker = 'CAADAgADngEAAvnkbAABHcANeRBqS0QWBA' where_money_Lebowsky_sticker = ru_where_money_Lebowsky_sticker if \ user.language_code == 'ru' else en_where_money_Lebowsky_sticker print(where_money_Lebowsky_sticker) try: bot.send_message(call.message.chat.id, text_judge) except Exception: pass try: bot.send_message(user_id, text_user) bot.send_sticker(user_id, where_money_Lebowsky_sticker) except Exception: pass
def process_ask_question_callback(query): try: if query.data in ['instant_cancel', 'scheduled_cancel']: bot.delete_message(query.message.chat.id, query.message.message_id) return edited_text = 'Спрашиваем...' if query.data == 'instant_question' else 'Планируем...' bot.edit_message_text(chat_id=query.message.chat.id, message_id=query.message.message_id, text=edited_text) message_parts = query.message.text.split('\n', maxsplit=1) text = message_parts[1].strip() full_name, username = UserNamesExtractor.get_fullname_and_username( query.message.chat) added_by_name = full_name if full_name else ( username if username else query.message.chat.id) now = datetime.utcnow() if query.data == 'instant_question': try: QuestionAsker.ask(text) questions_queue_repository.add( QuestionQueueItem( text=text, time_created=now, time_planned=now, time_sent=now, status=QuestionQueueItemStatus.InstantlyInserted, added_by_id=query.message.chat.id, added_by_name=added_by_name, has_answer=False)) except: bot.edit_message_text(chat_id=query.message.chat.id, message_id=query.message.message_id, text='К сожалению, что-то сгнило!') else: regex = re.compile( r'^.+(?P<datetime>\d\d\.\d\d\.\d\d\d\d\s+\d\d\:\d\d).+$') match = regex.match(message_parts[0]) planned_time = DatetimeUtils.parse_dmy_hm(match.group('datetime'), timedelta(hours=-3)) questions_queue_repository.add( QuestionQueueItem(text=text, time_created=now, time_planned=planned_time, time_sent=None, status=QuestionQueueItemStatus.Unprocessed, added_by_id=query.message.chat.id, added_by_name=added_by_name, has_answer=False)) bot.delete_message(query.message.chat.id, query.message.message_id) bot.send_sticker(query.message.chat.id, StickerIds.done) finally: requests_notifier.notify(query.message.chat.id, query.data)
def new_phrase(message): text_exists = select_condition('texts', 'msg', "msg = '{msg}'".format(msg=message.text)) role = check_superuser(login=message.from_user.username) if role in ('superuser', 'moder', 'admin'): if enough(message.text): bot.send_message(chat_id=message.chat.id, text="Ой, больно-то и хотелось!", parse_mode='Markdown') elif message.content_type == 'text' and message.text[ 0] != '/' and not text_exists: result = insert_condition(table='texts', values=(message.text, ), columns='(msg)') if result: bot.send_message( chat_id=message.chat.id, text="Я всё добавил, но если что, можно удалить.", parse_mode='Markdown', reply_to_message_id=message.message_id) else: bot.send_message( chat_id=message.chat.id, text= "Хм, кажется, что-то не так с базой данных. Давай попробуем ещё раз.", parse_mode='Markdown', reply_to_message_id=message.message_id) elif text_exists: bot.send_message( chat_id=message.chat.id, text="Такой текст уже есть, давай попробуем ещё раз. ", parse_mode='Markdown', reply_to_message_id=message.message_id) else: bot.send_message( chat_id=message.chat.id, text= 'Мы так не договаривались! Пришли фразу, пожалуйста, а не вот это вот всё :C', parse_mode='Markdown', reply_to_message_id=message.message_id) else: bot.send_message( chat_id=message.chat.id, text='Прости, мама запрещает мне общаться с незнакомцами.', parse_mode='Markdown') bot.send_sticker( chat_id=message.chat.id, sticker= 'CAACAgIAAxkBAAIHmF41kWHKUfajjxb0umLKOG-EMWanAALwLgAC4KOCB2bcGHGkwKtzGAQ' ) bot.clear_step_handler(message)
def send_text(message): if message.text.lower() == 'привет': bot.send_message(message.chat.id, 'Привет! Напиши мне /start, чтобы узнать, что я умею.') elif message.text.lower() == 'пока': bot.send_message(message.chat.id, 'Пока, хорошего дня!') elif state == 'quotation': file_name = 'example.txt' try: if message.text.lower() == "да": bot.send_sticker(message.chat.id, 'CAACAgIAAxkBAAEBVkRfYOL4e95nsf0BQTNERFzXlRPXCQAC6AIAArVx2gZSDa62VYCCWxsE') bot.send_message(message.chat.id, 'Я рад, что смог Вам помочь. Есть ли еще цитаты для меня?') elif message.text.lower() == "нет": bot.send_sticker(message.chat.id, 'CAACAgIAAxkBAAEBVktfYPUL4o_PjERkI5qn7OAbxX48mQACGgADWbv8JTxSipCGVVnTGwQ') bot.send_message(message.chat.id, 'Попробуйте исправить цитату или прислать мне книжку') else: text = open("downloaded_books/" + file_name, encoding="utf-8").read() keep_alpha_line, offset_list = get_offset(text) lower_words = {word for word in keep_alpha_line.split() if word.islower()} quotation = message.text quotation_author = '' lines_with_quotation = search_qoutation(quotation, file_name) if len(lines_with_quotation) == 0: bot.send_message(message.chat.id, 'Цитата не найдена, дополните или исправите цитату') else: bot.send_message(message.chat.id, 'Вот возможные абзацы с этой цитатой и ее авторы:') for line in lines_with_quotation: potential_authors = [] result_author, result_direct = search_directspeech(line) for sentence in range(len(result_direct)): if result_direct[sentence].find(quotation) != -1: quotation_author = result_author[sentence] capitalize_list = capitalize_words(keep_alpha(quotation_author)) potential_authors = filter_lower_words(capitalize_list, lower_words) bot.send_message(message.chat.id, line) if len(potential_authors) != 0: bot.send_message(message.chat.id, potential_authors[0]) else: while len(potential_authors) == 0: previous_paragraph = list(open("downloaded_books/" + file_name, encoding="utf-8"))[ list(open(file_name, encoding="utf-8")).index(line) - 1] previous_capitalize_list = capitalize_words(keep_alpha(previous_paragraph)) potential_authors = filter_lower_words(previous_capitalize_list, lower_words) bot.send_message(message.chat.id, potential_authors[- 1]) bot.send_message(message.chat.id, 'Нашли ли Вы ответ на свой вопрос?(Да/Нет)') except: bot.send_message(message.chat.id, 'У меня нет этой книги, пришлите пожалуйста файл с ней.') elif state == 'character': text = open('example.txt', encoding="utf-8").read()
def motivate_users_with_Jason_Statham(): users = execute_database_command('SELECT id, language_code FROM users;')[0] for user in users: user_id = user[0] language_code = user[1] quote = random.choice(Jason_Statham_quotes_ru) + '\n\n*Джейсон Стэтхэм*' if language_code == 'ru' else \ random.choice(Jason_Statham_quotes_en) + '\n\n*Jason Statham*' sticker = random.choice(Jason_Statham_sticker_pack) try: bot.send_message(user_id, quote, parse_mode='Markdown') bot.send_sticker(user_id, sticker) except Exception: pass
def process_top_command_callback(query): try: bot.delete_message(query.message.chat.id, query.message.message_id) if query.data == 'top1': count = 1 elif query.data == 'top3': count = 3 elif query.data == 'top5': count = 5 elif query.data == 'top10': count = 10 else: return log = { 'source': 'User message', 'from_id': query.message.chat.id, 'command': query.data, 'result': 'successfully', 'time': datetime.utcnow() } bot.send_message(query.message.chat.id, f'Top {count} записей:') try: parser = SiteParser(URL_FEED) questions = parser.parse(count) except: bot.send_message( query.message.chat.id, f'К сожалению, что-то сгнило! Попробуйте еще раз позже или посетите сайт царицы {URL_FEED}.' ) bot.send_sticker(query.message.chat.id, StickerIds.no_mood) log['result'] = 'parsing failed' return question_sender = QuestionSender(bot) question_sender.send_many(query.message.chat.id, questions) finally: requests_notifier.notify(query.message.chat.id, query.data) logs_repository.add(log)
def start_handler(message): try: bot.send_sticker(message.chat.id, StickerIds.hello) bot.send_message( message.chat.id, 'Вас приветствует Томочка Лапочка!\n\n' '/top - получить несколько первых постов\n\n' '/notifications - подписка на рассылку новых постов\n\n' '/random - показать случайный пост') full_name, username = UserNamesExtractor.get_fullname_and_username( message.chat) bot_users_repository.ensure( BotUser(message.chat.id, full_name, username, True)) finally: requests_notifier.notify(message.chat.id, '/start') logs_repository.add({ 'source': 'User message', 'from_id': message.chat.id, 'command': message.text, 'time': datetime.utcnow() })
def bot_delete_moder(message): bot.clear_step_handler(message) role = check_superuser(login=message.from_user.username) if role in ('superuser', 'admin'): bot.send_message( chat_id=message.chat.id, text= "Напиши логин того, у кого нужно отобрать дополнительные права.\n" "Напиши ___хватит___, если передумал.", parse_mode='Markdown') bot.register_next_step_handler(message, delete_moder) else: bot.send_message( chat_id=message.chat.id, text='Прости, мама запрещает мне общаться с незнакомцами.', parse_mode='Markdown') bot.send_sticker( chat_id=message.chat.id, sticker= 'CAACAgIAAxkBAAIHmF41kWHKUfajjxb0umLKOG-EMWanAALwLgAC4KOCB2bcGHGkwKtzGAQ' )
def bot_delete_phrase(message): bot.clear_step_handler(message) role = check_superuser(login=message.from_user.username) if role in ('superuser', 'moder', 'admin'): bot.send_message( chat_id=message.chat.id, text= "Какую фразу ты хочешь удалить? Учти, нужно полное совпадение.\n" "Напиши ___хватит___, если передумал.", parse_mode='Markdown') bot.register_next_step_handler(message, delete_phrase) else: bot.send_message( chat_id=message.chat.id, text='Прости, мама запрещает мне общаться с незнакомцами.', parse_mode='Markdown') bot.send_sticker( chat_id=message.chat.id, sticker= 'CAACAgIAAxkBAAIHmF41kWHKUfajjxb0umLKOG-EMWanAALwLgAC4KOCB2bcGHGkwKtzGAQ' )
def send_info_to_users(): users = execute_database_command( 'SELECT id, first_name, language_code FROM users;')[0] for user in users: ru_text = f'Привет{", " + user[1] if user[1] else ""}!\n\n' \ f'Я решил больше не церемониться. Теперь разговариваю дерзко и на "ты". ' \ f'Может, хотя бы это поможет тебе побороть свою лень. ' \ f'А ещё я теперь отправляю стикеры.\n\n' \ f'Короче, я теперь не унылый стандартный бот.' en_text = f'Hello{", " + user[1] if user[1] else ""}!\n\n' \ f'I decided to no longer stand on ceremony. Now I speak impertinently. ' \ f'Maybe at least it will help you overcome your laziness. ' \ f'And now I send stickers.\n\n' \ f'In short, I am no longer a dull standard bot.' text = ru_text if user[2] == 'ru' else en_text try: bot.send_message(user[0], text, parse_mode='Markdown') bot.send_sticker(user[0], 'CAADAgADcgADE-ZSAdekz3zzPdFUAg') except Exception as e: print(e)
def handle_kick_lazy_ass_query(call): habit_id = int(call.data.split('/')[1]) habit = Habit.get(habit_id) user = User.get(habit.user_id) judge = User.get(call.message.chat.id) ru_text = f'{get_user_naming(judge, "Твой друг")} ' \ f'напоминает тебе, что ты обещал "*{habit.label}*"' en_text = f'{get_user_naming(judge, "Your friend")} ' \ f'reminds you that you promised "*{habit.label}*"' text = ru_text if user.language_code == 'ru' else en_text try: bot.send_message(user.id, text, parse_mode='Markdown') bot.send_sticker(user.id, random.choice(remind_stickers)) except Exception: pass try: bot.send_message(judge.id, 'Сделано!' if user.language_code == 'ru' else 'Done!') except: pass
def bot_add_phrase(message): bot.clear_step_handler(message) role = check_superuser(login=message.from_user.username) if role in ('superuser', 'moder', 'admin'): bot.send_message( chat_id=message.chat.id, text= "Какую фразу ты хочешь добавить? Пожалуйста, напиши одно предложение в сообщении, " "я не хочу их сам на строчки разбивать :'(\n" "Напиши ___хватит___, если передумал.", parse_mode='Markdown') bot.register_next_step_handler(message, new_phrase) else: bot.send_message( chat_id=message.chat.id, text='Прости, мама запрещает мне общаться с незнакомцами.', parse_mode='Markdown') bot.send_sticker( chat_id=message.chat.id, sticker= 'CAACAgIAAxkBAAIHmF41kWHKUfajjxb0umLKOG-EMWanAALwLgAC4KOCB2bcGHGkwKtzGAQ' )
def promise_receive(message): user = User.get(message.chat.id) habit = Habit(message.chat.id, preparing_habits[message.chat.id]['label'], preparing_habits[message.chat.id]['days_of_week'], preparing_habits[message.chat.id]['time_array'], preparing_habits[message.chat.id]['fine']).save() if preparing_habits[message.chat.id]['with_judge']: ru_text = 'Осталось назначить судью. Просто отправь другу сообщение ниже👇' en_text = 'It remains to assign the judge. Just send the message below to a friend👇' text = ru_text if user.language_code == 'ru' else en_text bot.send_message(message.chat.id, text, reply_markup=types.ReplyKeyboardRemove()) ru_days = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'] en_days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'] days = ru_days if user.language_code == 'ru' else en_days check_days = re.sub( r'\s+', ' ', ' '.join([ day if day_of_week in preparing_habits[message.chat.id]['days_of_week'] else '' for day_of_week, day in enumerate(days) ])) check_time = ' '.join(preparing_habits[message.chat.id]['time_array']) ru_text = f'{get_user_naming(user, "Твой друг")} хочет, ' \ f'чтобы ты стал его судьёй на привычке *{habit.label}*.\n\n' \ f'Дни недели: *{check_days}*\n' \ f'Время проверки: *{check_time}*\n' \ f'Длительность: *3 недели*\n\n' \ f'За каждый провал {get_user_naming(user, "твой друг")} обязуется заплатить тебе *${habit.fine}*' en_text = f'{get_user_naming(user, "Your friend")} wants you ' \ f'to be the judge on the habit *{habit.label}*.\n\n' \ f'Days of week: *{check_days}*\n' \ f'Checks time: *{check_time}*\n' \ f'Duration: *3 weeks*\n\n' \ f'For each fail {get_user_naming(user, "your friend")} agrees to pay you *${habit.fine}*' text = ru_text if user.language_code == 'ru' else en_text bot.send_message(message.chat.id, text, reply_markup=markups.get_judge_markup( user.id, habit.id), parse_mode='Markdown') else: ru_text = 'Ну что ж, посмотрим, какой ты крутой. Удачи!' en_text = "Well, let's see how cool you are. Good luck!" text = ru_text if user.language_code == 'ru' else en_text schedule_native, schedule_utc = get_schedule( preparing_habits[message.chat.id]['days_of_week'], preparing_habits[message.chat.id]['time_array'], User.get(message.chat.id).timezone, ) for check_native, check_utc in zip( schedule_native, schedule_utc): # нужно оптимизировать Check(habit.id, check_native, check_utc).save() bot.send_message(message.chat.id, text, reply_markup=markups.get_main_menu_markup( message.chat.id)) bot.send_sticker(message.chat.id, 'CAADAgADWQIAAsY4fgsQX6OJTX_IOgI') del preparing_habits[message.chat.id]
def handle_check_query(call): data = ast.literal_eval(call.data.split('/')[1]) check = Check.get(data['check_id']) check.status = data['status'] check.save() habit = Habit.get(check.habit_id) user = User.get(call.message.chat.id) called_button_label = call.message.json['reply_markup']['inline_keyboard'][0][0]['text'] if \ data['status'] == CheckStatus.SUCCESS.name else \ call.message.json['reply_markup']['inline_keyboard'][0][1]['text'] try: bot.edit_message_text( chat_id=call.message.chat.id, text=call.message.text, message_id=call.message.message_id, reply_markup=markups.get_check_result_inline_markup( called_button_label), parse_mode='HTML') except: pass if data['status'] == CheckStatus.SUCCESS.name: user.score += habit.fine user.save() ru_text = f'{random.choice(ru_success_phrases)}\n\n*+{habit.fine} очков*' en_text = f'{random.choice(en_success_phrases)}\n\n*+{habit.fine} points*' text = ru_text if user.language_code == 'ru' else en_text try: bot.send_message(call.message.chat.id, text, parse_mode='Markdown') bot.send_sticker(call.message.chat.id, random.choice(success_stickers)) except: pass if habit.judge: judge = User.get(habit.judge) ru_text_judge = f'{get_user_naming(user, "Твой друг")} выполнил обещание *{habit.label}*' en_text_judge = f'{get_user_naming(user, "Your friend")} fulfilled the promise *{habit.label}*' text_judge = ru_text_judge if judge.language_code == 'ru' else en_text_judge try: bot.send_message(judge.id, text_judge, parse_mode='Markdown') except Exception: pass else: if habit.judge: user_violations_with_judge(user.id, habit.judge) else: try: bot.send_sticker(call.message.chat.id, random.choice(fail_stickers)) except: pass user_violations(call.message) suggest_new_habit(user, habit)
def main(message: Message): bot.send_chat_action(action='typing', chat_id=message.from_user.id) if dbm.get_user_language(message.from_user.id) == "NONE" and ( message.text != "English" and message.text != "Русский"): bot.send_message(message.chat.id, text.UNDEFINED_LANGUAGE) elif dbm.get_user_game_state(user_id=message.from_user.id) == "gaming" and \ dbm.get_user_game_combination(user_id=message.from_user.id) != "NONE": if RepresentsInt(message.text) and len(message.text) == 4: message_out = check_matching(message) # bot.send_message(message.chat.id, message_out) bot.reply_to(message, message_out) step = int( dbm.get_user_game_steps(user_id=message.from_user.id)) + 1 dbm.update(user_id=message.from_user.id, item='Steps', new_value=str(step)) if message_out == 'You won!' or message_out == 'Ты выиграл!': bot.send_sticker(chat_id=message.chat.id, data=text.get_random_cat_sticker()) bot.send_document(chat_id=message.chat.id, data=text.get_random_cat_gif()) games = int( dbm.get_user_games_number(user_id=message.from_user.id)) dbm.update(user_id=message.from_user.id, new_value=str(games + 1), item='Games') dbm.append_game_in_table( ID=message.from_user.id, Game_number=games + 1, Number_of_steps=dbm.get_user_game_steps( user_id=message.from_user.id)) dbm.update(user_id=message.from_user.id, new_value='NONE', item='Steps') dbm.update(user_id=message.from_user.id, new_value='NONE', item='Game_comb') dbm.update(user_id=message.from_user.id, new_value='NONE', item='Game_status') if str(dbm.get_user_best_score( user_id=message.from_user.id)) == 'NONE' or step < int( dbm.get_user_best_score( user_id=message.from_user.id)): dbm.update(user_id=message.from_user.id, new_value=str(step), item='Best_score') dbm.update(user_id=message.from_user.id, item='Game_status', new_value=states.NONE) dbm.update(user_id=message.from_user.id, item='Game_comb', new_value=states.NONE) dbm.update(user_id=message.from_user.id, item='Steps', new_value=states.NONE) elif RepresentsInt(message.text) and len(message.text) != 4: message_text = getattr( text, dbm.get_user_language(message.from_user.id) + "_send_correct_comb")() # bot.send_message(message.chat.id, message_text) bot.reply_to(message, message_text) else: message_text = getattr( text, dbm.get_user_language(message.from_user.id) + "_send_your_comb")() # bot.send_message(message.chat.id, message_text) bot.reply_to(message, message_text) else: message_text = getattr( text, dbm.get_user_language(message.from_user.id) + "_undefined_text")() #bot.send_message(message.chat.id, message_text) bot.reply_to(message, message_text)
def promise_receive(message): user = User.get(message.chat.id) # Назначаем привычку habit = Habit(message.chat.id, preparing_habits[message.chat.id]['label'], preparing_habits[message.chat.id]['days_of_week'], preparing_habits[message.chat.id]['time_array'], preparing_habits[message.chat.id]['fine']).save() # Снимаем штрафы с пригласившего if user.referrer: referrer = User.get(user.referrer) referrer.satisfy_fines(CheckStatus.WORKED.name) ru_text_ref = f'{get_user_naming(user, "Твой друг")} ' \ f'назначил свою первую привычку. ' \ f'За успешно проведённые социальные работы ' \ f'с тебя снимаются все обвинения и твои штрафы аннулируются.' en_text_ref = f'{get_user_naming(user, "Your friend")} ' \ f'has assigned his first habit. ' \ f'For successful social work all charges ' \ f'against you and your fines are canceled.' text_ref = ru_text_ref if referrer.language_code == 'ru' else en_text_ref bot.send_message(referrer.id, text_ref) if preparing_habits[message.chat.id]['with_judge']: ru_text = 'Осталось назначить судью. Просто отправь другу сообщение ниже👇' en_text = 'It remains to assign the judge. Just send the message below to a friend👇' text = ru_text if user.language_code == 'ru' else en_text bot.send_message(message.chat.id, text, reply_markup=types.ReplyKeyboardRemove()) ru_days = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'] en_days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'] days = ru_days if user.language_code == 'ru' else en_days check_days = re.sub( r'\s+', ' ', ' '.join([ day if day_of_week in preparing_habits[message.chat.id]['days_of_week'] else '' for day_of_week, day in enumerate(days) ])) check_time = ' '.join(preparing_habits[message.chat.id]['time_array']) ru_text = f'{get_user_naming(user, "Твой друг")} хочет, ' \ f'чтобы ты стал его судьёй на привычке *{habit.label}*.\n\n' \ f'Дни недели: *{check_days}*\n' \ f'Время проверки: *{check_time}*\n' \ f'Длительность: *3 недели*\n\n' \ f'За каждый провал {get_user_naming(user, "твой друг")} обязуется заплатить тебе *${habit.fine}*' en_text = f'{get_user_naming(user, "Your friend")} wants you ' \ f'to be the judge on the habit *{habit.label}*.\n\n' \ f'Days of week: *{check_days}*\n' \ f'Checks time: *{check_time}*\n' \ f'Duration: *3 weeks*\n\n' \ f'For each fail {get_user_naming(user, "your friend")} agrees to pay you *${habit.fine}*' text = ru_text if user.language_code == 'ru' else en_text bot.send_message(message.chat.id, text, reply_markup=markups.get_judge_markup( user.id, habit.id), parse_mode='Markdown') else: schedule_native, schedule_utc = get_schedule( preparing_habits[message.chat.id]['days_of_week'], preparing_habits[message.chat.id]['time_array'], User.get(message.chat.id).timezone, ) for check_native, check_utc in zip( schedule_native, schedule_utc): # нужно оптимизировать Check(habit.id, check_native, check_utc).save() del preparing_habits[message.chat.id] ru_text = 'Ну что ж, посмотрим, какой ты крутой. Удачи!' en_text = "Well, let's see how cool you are. Good luck!" text = ru_text if user.language_code == 'ru' else en_text bot.send_message(message.chat.id, text, reply_markup=markups.get_main_menu_markup( message.chat.id)) bot.send_sticker(message.chat.id, 'CAADAgADWQIAAsY4fgsQX6OJTX_IOgI')
def handle_text(message): try: parsing_result = IncomingMessageParser.parse(message.text) if parsing_result.type == MessageType.UnsupportedCommand: bot.send_message(message.chat.id, 'Неподдерживаемая команда!!') bot.send_sticker(message.chat.id, StickerIds.loh) return if parsing_result.type == MessageType.ZakruzhilasCommand: bot.send_animation(message.chat.id, open('files/zakruzhilas.mp4', 'rb')) return if parsing_result.type == MessageType.InstantQuestion: if parsing_result.is_valid: markup = types.InlineKeyboardMarkup(row_width=2) confirm_button = types.InlineKeyboardButton( 'Задать!!', callback_data='instant_question') cancel_button = types.InlineKeyboardButton( 'Отмена', callback_data='instant_cancel') markup.add(confirm_button, cancel_button) text = 'Подтвердите, что хотите задать вопрос прямо сейчас:\n\n' + parsing_result.question bot.send_message(message.chat.id, text, reply_markup=markup) else: bot.send_message(message.chat.id, parsing_result.comment) return if parsing_result.type == MessageType.ScheduledQuestion: if parsing_result.is_valid: markup = types.InlineKeyboardMarkup(row_width=2) confirm_button = types.InlineKeyboardButton( 'Запланировать!!', callback_data='scheduled_question') cancel_button = types.InlineKeyboardButton( 'Отмена', callback_data='scheduled_cancel') markup.add(confirm_button, cancel_button) time_left = DatetimeUtils.timedelta_to_string( parsing_result.planned_time - (datetime.utcnow() + timedelta(hours=3)), '{days}д {hours}ч {minutes}м') text = f'Подтвердите, что хотите запланировать вопрос на {parsing_result.planned_time_str} (осталось {time_left}):\n\n' + parsing_result.question bot.send_message(message.chat.id, text, reply_markup=markup) else: bot.send_message(message.chat.id, parsing_result.comment) return if parsing_result.type == MessageType.VkStatusRequest: if parsing_result.is_valid: plot_sender = VkStatusPlotSender( bot, VkStatusPlotBuilder(vk_online_status_repository)) plot_sender.send(parsing_result.time_utc_from, parsing_result.time_utc_to, message.chat.id) else: bot.send_message(message.chat.id, parsing_result.comment) return finally: requests_notifier.notify(message.chat.id, message.text) logs_repository.add({ 'source': 'User message', 'from_id': message.chat.id, 'text': message.text, 'time': datetime.utcnow() })
def handle_sticker(message): try: bot.send_sticker(message.chat.id, StickerIds.rachal) finally: requests_notifier.notify(message.chat.id, 'send sticker to bot')