def sms(bot, update): search_or_save_user(mdb, bot.effective_user, bot.message) while True: if bot.effective_user.id == 392540927: bot.message.reply_text( f'Напоминаю тебе {bot.message.chat.first_name}!\n Не забудь шампунь и гель для душа' ) if bot.effective_user.id == 317928020: bot.message.reply_text( f'Напоминаю тебе {bot.message.chat.first_name}!\n Не забудь взять лопатку и варенье возьми' ) time.sleep(3600)
def sms(bot, update): user = search_or_save_user(mdb, bot.effective_user, bot.message) print(str(user['first_name']) + ' ' + str(user['last_name'])) #print('Кто-то отправил команду /start. Что мне делать?') bot.message.reply_text('Здравствуйте, {}!'.format( bot.message.chat.first_name), reply_markup=get_keyboard())
def sms(bot, update): """Функция вызывается при отправке команды /start""" user = search_or_save_user(mdb, bot.effective_user, bot.message) smile = emojize(choice(SMILE), use_aliases=True) bot.message.reply_text('Привет {} {}'.format(bot.message.chat.first_name, smile), reply_markup=get_keyboard())
def hist_get_answer(bot, update): if bot.message.text == "Похожи": update.user_data['Sim'][-1] = 1 elif bot.message.text == "Не похожи": update.user_data['NonSim'][-1] = 1 else: update.user_data['Dont Know'][-1] = 1 user = search_or_save_user(mdb, bot.effective_user, bot.message) vote_result = save_user_vote(mdb, user, update.user_data) #print(vote_result) update.user_data.update({ 'hist1': [], 'hist2': [], 'Sim': [], 'NonSim': [], 'Dont Know': [], 'Date': [], 'Time': [] }) reply_keyboard = [['Голосовать!', "Закончить"]] bot.message.reply_text( 'Помогите нам собрать больше результатов!' '\nНажмите Голосовать!', reply_markup=ReplyKeyboardMarkup(reply_keyboard, resize_keyboard=False, one_time_keyboard=True)) return "end?"
def step_most_similar(message): try: user = search_or_save_user(mdb, message.from_user, message) user['selected_photo'] = int(message.text) result = most_similar(int(message.text), data) user['the_most_similar_photo'] = int(result) update_user(mdb, user) except Exception as e: pass
def hello_world(message): bot.send_chat_action(message.chat.id, 'typing') # want_to_know_photo = True if message.chat.type == 'private': if message.text == 'Рандомное число': bot.send_message(message.chat.id, str(random.randint(0,100))) elif message.text == 'Как дела?': markup = types.InlineKeyboardMarkup(row_width=2) item1 = types.InlineKeyboardButton('Хорошо', callback_data='good') item2 = types.InlineKeyboardButton('Не очень', callback_data='bad') markup.add(item1, item2) bot.send_message(message.chat.id, 'У меня дела отлично. А у тебя как?', reply_markup=markup) elif message.text == 'Привет' or message.text == 'привет': user = search_or_save_user(mdb, message.from_user, message) if user['first_time'] == True: welcome(message) user['first_time'] = False update_user(mdb, user) else: bot.send_message(message.chat.id, 'Привет! Ознакомиться с командами можно написав /help') elif message.text == 'Самая похожая фотография': try: markup = types.ForceReply(selective=False) replied = bot.send_message(message.chat.id, "Введите номер картинки, для которой вы хотите найти самую похожую фотографию:\n", reply_markup=markup) timing = time.time() bot.register_next_step_handler(replied, step_most_similar) time.sleep(5) user = search_or_save_user(mdb, message.from_user, message) bot.send_message(message.chat.id, 'Выбранная фотография:') DIR_SEL = r'C:/Users/Dmitry/PycharmProjects/telegrambots/first_bot/data/' + str(user['selected_photo']) + '.png' DIR_SIM = r'C:/Users/Dmitry/PycharmProjects/telegrambots/first_bot/data/' + str(user['the_most_similar_photo']) + '.png' bot.send_photo(chat_id=message.chat.id, photo=open(DIR_SEL, 'rb')) while(user['the_most_similar_photo'] == None): user = search_or_save_user(mdb, message.from_user, message) if time.time() - timing > 20.0: bot.send_message(message.chat.id, 'Время ожидания истекло!') if user['the_most_similar_photo'] != None: bot.send_message(message.chat.id, 'IDшник самой похожей на вашу фотографию: {0}'.format(user['the_most_similar_photo'])) bot.send_photo(message.chat.id, photo=open(DIR_SIM, 'rb')) except Exception as e: bot.send_message(message.chat.id, 'ERROR with finding photo') else: bot.send_message(message.chat.id, 'Пока что я не научился отвечать на это =) Update soon.')
def sms(bot, update): user = search_or_save_user(mdb, bot.effective_user, bot.message) # получаем данные из базы данных print(user) smile = emojize(choice(SMILE), use_aliases=True) # для ответа добавили emoji print('Кто-то отправил команду /start. Что мне делать?' ) # вывод сообщения в консоль при отправки команды /start bot.message.reply_text('Здравствуйте, {}! \nПоговорите со мной {}!'.format( bot.message.chat.first_name, smile), reply_markup=get_keyboard()) # отправляем ответ
def sms(bot, update): user = search_or_save_user(mdb, bot.effective_user, bot.message) print(user) smile = emojize(choice(SMILE), use_aliases=True) print('Кто-то отправил команду НАЧАТЬ. Что мне делать?' ) #вывод сообщения в консоль при отправке команды /start bot.message.reply_text('Здравствуйте, {}! \nНажмите'.format( bot.message.chat.first_name), reply_markup=get_keyboard()) # отправим ответ print(bot.message)
def anketa_exit_comment(bot, update): update.user_data['comment'] = None user = search_or_save_user(mdb, bot.effective_user, bot.message) save_user_anketa(mdb, user, update.user_data) text = '''Результат опроса: <b>Имя:</b> {name} <b>Возраст:</b> {age} <b>Оценка:</b> {evaluation}'''.format(**update.user_data) bot.message.reply_text(text, parse_mode = ParseMode.HTML) # текстовое сообщение с форматированием HTML bot.message.reply_text('Спасибо!', reply_markup = get_keyboard()) # отправляем сообщение и возвращаем осн. клаву return ConversationHandler.END # выходим из диалога
def anketa_exit_comment(bot, update): update.user_data['comment'] = None # на случай если пользователь не захочет оставлять комментарий user = search_or_save_user(mdb, bot.effective_user, bot.message) # получаме данные из базы данных save_user_anketa(mdb, user, update.user_data) # передаем и получаем результаты анкеты text = """Результат опроса: <b>Имя:</b> {name} <b>Возраст:</b> {age} <b>Оценка:</b> {evaluation} """.format(**update.user_data) # **в форматировании представляют все значения bot.message.reply_text(text, parse_mode=ParseMode.HTML) # текстовое сообщение с форматированием HTML bot.message.reply_text('Спасибо!', reply_markup=get_keyboard()) # сообщение и возврат основной клавиатуры return ConversationHandler.END # выходим из диалога
def form_exit_comment(bot, update): update.user_data['comment'] = bot.message.text # временно сохраняем ответ user = search_or_save_user(mdb, bot.effective_user, bot.message) # получаем данные из БД save_user_form(mdb, user, update.user_data) # передаем результаты анкеты text = """Результат опроса: <b>Имя:</b> {name} <b>Возраст:</b> {age} <b>Оценка:</b> {evaluation} """.format(**update.user_data) bot.message.reply_text(text, parse_mode=ParseMode.HTML) bot.message.reply_text('Спасибо за комментарии', reply_markup=get_keyboard()) return ConversationHandler.END
def start(bot, update): user = search_or_save_user(mdb, update.effective_user, update.message) print(user) reply_keyboard = [["\U0000270F Create Task", '\U0001F56E List All Tasks'], ["\U00002795 Help", "\U0001F468 Tutorial"], ["\U0001F680 Restart", "\U0000274C Cancel"], ['\U0000FF05 Statistics']] msg = 'Trust in me, (poiled by Rakhat)' + str( update.message.from_user.first_name ) + ' \U0000270C' + patterns.start_text update.message.reply_text(msg, reply_markup=ReplyKeyboardMarkup( reply_keyboard, resize_keyboard=True)) return GET_COMMAND
def anketa_comment(bot, update): update.user_data['comment'] = bot.message.text # временно сохраняет ответ user = search_or_save_user(mdb, bot.effective_user, bot.message) # получаме данные из базы данных anketa = save_user_anketa(mdb, user, update.user_data) # передаем и получаем результаты анкеты print(anketa) text = """Результат опроса: <b>Имя:</b> {name} <b>Возраст:</b> {age} <b>Оценка:</b> {evaluation} <b>Комментарий:</b> {comment} """.format(**update.user_data) # Подключаем в соббщении HTML, для этого необходимо импортировать ParseMode bot.message.reply_text(text, parse_mode=ParseMode.HTML) # текстовое сообщение с форматированием HTML bot.message.reply_text('Спасибо вам за комментарий!', reply_markup=get_keyboard()) # сообщение и возврат основной клавиатуры return ConversationHandler.END # выходим из диалога
def anketa_start(bot, update): user = search_or_save_user(mdb, bot.effective_user, bot.message) if 'anketa' in user: text = '''Ваш предыдущий результат: <b>Имя:</b> {name} <b>Возраст:</b> {age} <b>Оценка:</b> {evaluation} <b>Комментарий:</b> {comment} Данные будут обновлены! Как вас зовут? '''.format(**user['anketa']) bot.message.reply_text(text, parse_mode = ParseMode.HTML, reply_markup = ReplyKeyboardRemove()) return 'user_name' else: bot.message.reply_text('Как вас зовут?', reply_markup = ReplyKeyboardRemove()) # вопрос и убираем основную клавиатуру return 'user_name' # ключ для определения следующего шага
def anketa_start(bot, update): user = search_or_save_user(mdb, bot.effective_user, bot.message) # if 'anketa' in user: text = """Результат опроса: <b>Имя:</b> {name} <b>Возраст:</b> {age} <b>Оценка:</b> {evaluation} <b>Комментарий:</b> {comment} Данные будут обновлены! Как Вас зовут? """.format(**user['anketa']) bot.message.reply_text(text, parse_mode=ParseMode.HTML, reply_markup=ReplyKeyboardRemove()) return 'user_name' else: bot.message.reply_text('Как Вас зовут?', reply_markup=ReplyKeyboardRemove()) return 'user_name'
def welcome(message): bot.send_chat_action(message.chat.id, 'typing') user = search_or_save_user(mdb, message.from_user, message) print(user) sti = open(r'C:\Users\Dmitry\Desktop\AnimatedSticker.tgs', 'rb') bot.send_sticker(message.chat.id, sti) #keyboard markup1 = types.ReplyKeyboardMarkup(resize_keyboard=True,one_time_keyboard=True) item1 = types.KeyboardButton('Рандомное число') item2 = types.KeyboardButton('Как дела?') item3 = types.KeyboardButton('Самая похожая фотография') # markup2 = types.ReplyKeyboardMarkup(resize_keyboard=True) markup1.add(item1, item2, item3) # markup2.add(item3) bot.send_message(message.chat.id, "Добро пожаловать, {0.first_name}!\nЯ - <b>{1.first_name}</b>, бот созданный чтобы быть подопытным кроликом.".format(message.from_user, bot.get_me()), parse_mode='html', reply_markup=markup1)
def add_notification_date(bot, update, job_queue, user_data): notification_time = update.message.text notification_date = user_data["notification_date"] user_data['task_status'] = True try: hour, minutes = map(int, notification_time.split(":")) notification = datetime.datetime(year=notification_date.year, month=notification_date.month, day=notification_date.day, hour=hour, minute=minutes) except ValueError: update.message.reply_text( "Please enter a valid time in format 'HH:MM'") return None user_data["notification_date"] = notification chat_id = update.message.chat_id job_queue.run_once( alarm, notification, context={ "chat_id": chat_id, "task_data": f"""You have a task {user_data['task_title']} to do before {user_data['deadline_date']}!""" }) text = """\nResults: <b>Task: </b> {task_title} <b>Deadline: </b> {deadline_date} <b>Notification date: </b> {notification_date} """.format(**user_data) update.message.reply_text( f"""Thanks! I'll send you a notification on your task on {notification:%A}, {notification} \n""" + text, reply_markup=ReplyKeyboardMarkup(get_keyboard()), parse_mode=ParseMode.HTML) user = search_or_save_user(mdb, update.effective_user, update.message) task = search_or_save_task(mdb, update.effective_user, user_data) return ConversationHandler.END
def sms(bot, update): user = search_or_save_user(mdb, bot.effective_user, bot.message) # получаем данные из базы данных print(user) smile = emojize(choice(SMILE), use_aliases=True) print('Кто-то отправил команду /start. Что мне делать?') # вывод сообщения в консоли при отправке /start bot.message.reply_text(f'Здравствуйте, {bot.message.chat.first_name}! \nПоговорите со мной!{smile}', reply_markup=get_keyboard()) # обращаемся по имени к пользователю отправившего команду /start
def sms(bot, update): user = search_or_save_user(mdb, bot.effective_user, bot.message) print(user) smile = emojize(choice(SMILE), use_aliases = True) print('Кто-то отправил команду /start, что мне делать???') # Вывод сообщения в консоль bot.message.reply_text('Здравствуйте, {}! \nПоговорите со мной {}'.format(bot.message.chat.first_name, smile), reply_markup = get_keyboard())