def location_handler(location): bot.send_message(location.from_user.id, "Три ближайших парка: ", reply_markup=standart_markup()) # Выводим стандартную клавиатуру т.к старая уже не нужна db = sqlite3.connect("MosTourist.db") # Подключаемся к базе данных coordinates = (location.location.latitude, location.location.longitude) # Записываем координаты в переменную cur = db.cursor() cur.execute(f"""SELECT title, ent_objects, rating, latitude, longitude, park_id FROM park ORDER BY ABS((longitude - {coordinates[1]})*(longitude - {coordinates[1]}) + (latitude - {coordinates[0]})*(latitude - {coordinates[0]})) ASC""") # Поиск парков result = cur.fetchmany(3) for row in result: # Вывод результата markup = types.InlineKeyboardMarkup() btn_my_site = types.InlineKeyboardButton(text='Открыть в Google Maps', url=f'https://www.google.com/maps/search/?api=1&query={row[3]},{row[4]}') markup.add(btn_my_site) result_message = f"Парк: {row[0]} \nНа что посмотреть: {row[1]} \nРейтинг: {str(row[2])}" cur.execute(f"""SELECT title FROM restaurant WHERE park_id = {row[5]}""") restaurant_list = cur.fetchall() if restaurant_list[0][0] is not None: # Проверка на наличие ресторанов result_message += "\n\nГде покушать:\n" for restaurant in restaurant_list: result_message += f"{restaurant[0]}, " result_message = result_message[:-2] # Убираем последние два символа в строке (" ,") bot.send_message(location.from_user.id, result_message, reply_markup=markup)
def send_parting(message): chat_id = message.chat.id username = message.left_chat_member.username if username is None: username = message.left_chat_member.first_name msg = "Прощайте, @{0}!".format(username) bot.send_message(chat_id, msg)
def send_greetings(message): chat_id = message.chat.id username = message.new_chat_member.username if username is None: username = message.new_chat_member.first_name msg = "Ласкаво просимо, @{0}!".format(username) bot.send_message(chat_id, msg)
def default_location_handler(message): active_user = get_active_user(message.from_user.id) bot.send_message(message.chat.id, f'Your current default location is -> {active_user.default_location}') bot.send_message(message.chat.id, 'You can choose another one from list above', reply_markup=user_locations(active_user.locations)) bot.register_next_step_handler(message, handle_default_location_choise)
def send_updates(): sce = db.get_search_collection_entries() for i in sce: tracking_urls = [] for url in i['tracking_urls']: old_ads = url['ads'] actual_ads = get_ads_list(url['url']) new_ads = get_new_ads(actual_ads, old_ads) for n_a in new_ads: msg = n_a['title'].rstrip() + '\n' + n_a['price'].rstrip() + \ '\n' + n_a['url'] # if n_a['img']: # from utils import get_img_file_by_url # # img_file = get_img_file_by_url(n_a['img']) # if img_file: # bot.send_photo(i['uid'], img_file) bot.send_message(i['uid'], msg) url['ads'] = actual_ads tracking_urls.append(url) import random time.sleep(random.randint(1, 15) / 10) db.set_actual_ads(i['uid'], tracking_urls)
def send_text(message): bot.send_message(message.chat.id, strings.sourse_question, reply_markup=markup_sourses) global answer answer = message.text.lower() @bot.callback_query_handler(func=lambda call: True) def callback_query(call): global answer answ = answer if call.data == "UralSib_A": answ += " УралСиб_А" elif call.data == "Sber_A": answ += " Сбер_А" elif call.data == "Nal_A": answ += " Нал_А" elif call.data == "Sber_I": answ += " Сбер_И" elif call.data == "Nal_I": answ += " Нал_И" elif call.data == "Nal_kv": answ += " Нал_кв" try: # write_to_db(get_info_from_mess(answ)[0],get_info_from_mess(answ)[1], get_info_from_mess(answ)[2]) bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id) bot.send_message(message.chat.id, strings.success_msg) except Exception: print("Какая-то ошибочка") print(Exception) # bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id) bot.send_message(message.chat.id, "Какая-то ошибочка")
def callback_query(call): global answer answ = answer if call.data == "UralSib_A": answ += " УралСиб_А" elif call.data == "Sber_A": answ += " Сбер_А" elif call.data == "Nal_A": answ += " Нал_А" elif call.data == "Sber_I": answ += " Сбер_И" elif call.data == "Nal_I": answ += " Нал_И" elif call.data == "Nal_kv": answ += " Нал_кв" try: # write_to_db(get_info_from_mess(answ)[0],get_info_from_mess(answ)[1], get_info_from_mess(answ)[2]) bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id) bot.send_message(message.chat.id, strings.success_msg) except Exception: print("Какая-то ошибочка") print(Exception) # bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id) bot.send_message(message.chat.id, "Какая-то ошибочка")
def select_birthday(active): """ Получить все активные/неактивные дни рождения из базы. active = True/False """ connection.ping() if active: try: data = "" cursor = connection.cursor() sql = f"SELECT * FROM `happy_birthdays` WHERE active = '1';" cursor.execute(sql) birthdays = cursor.fetchall() for birthday in birthdays: data += f"{birthday['id']}. {birthday['name']} - {date_convert_from_mysql_format(birthday['date'])}\n" return data except Exception as e: bot.send_message(adm_id, f"При выполнении select_birthday(if active) возникла ошибка: {e}") else: try: data = "" cursor = connection.cursor() sql = f"SELECT * FROM `happy_birthdays` WHERE active = '0';" cursor.execute(sql) birthdays = cursor.fetchall() for birthday in birthdays: data += f"{birthday['id']}. {birthday['name']} - {date_convert_from_mysql_format(birthday['date'])}\n" return data except Exception as e: bot.send_message(adm_id, f"При выполнении select_birthday(else) возникла ошибка: {e}")
def wrapped(message): if not storage.user_exist(message.chat.id): bot.send_message(chat_id=message.chat.id, text='✨ Вас нет в базе данных, нажмите /start для регистрации') return return func(message)
def send_add_refuse(message): chat_id = message.chat.id username = message.from_user.username if username is None: username = message.from_user.first_name msg = "@{0}, ви вже є у списку!".format(username) bot.send_message(chat_id, msg)
def send_member_removed(message): chat_id = message.chat.id content = message.text rm_username = get_username_from_text(content) msg = "@{0} вилучено зі списку. Повернутись до списку можна лише за виконанням відповідної команди самим юзером".format( rm_username) bot.send_message(chat_id, msg)
def handle_default_location_choise(message): active_user = get_active_user(message.from_user.id) if message.text != 'Back': new_location = message.text ds.set_default_location(active_user.telegram_id, new_location) bot.send_message(message.chat.id, f'Your new default location is {new_location}', reply_markup=main_keyboard()) else: bot.send_message(message.chat.id, 'Returned to main Menu', reply_markup=main_keyboard())
def search_products(update, user): logging.debug('saving location {}'.format(update.message.location)) user.location_updated = datetime.datetime.now() user.lat = update.message.location.latitude user.lon = update.message.location.longitude user.put() bot.send_message(chat_id=update.message.chat_id, text=u'What would you like to eat? \n')
def menu(update, user): user.location_updated = datetime.datetime.now() user.lat = update.message.location.latitude user.lon = update.message.location.longitude user.put() bot.send_message(chat_id=update.message.chat_id, reply_markup=ReplyKeyboardRemove(), text=u'Thanks!')
def send_refuse(message): chat_id = message.chat.id username = message.from_user.username if username is None: username = message.from_user.first_name msg = "Вибачте, @{0}, дана команда доступна лише для адміністраторів".format( username) bot.send_message(chat_id, msg)
def got_payment(message): bot.send_message( message.chat.id, 'Hoooooray! Thanks for payment! We will proceed your order for `{} {}` as fast as possible! ' 'Stay in touch.\n\nUse /buy again to get a Puma THUNDER for your friend!' .format(message.successful_payment.total_amount / 100, message.successful_payment.currency), parse_mode='Markdown')
def send_rules(message): chat_id = message.chat.id msg = "Всім привіт! Даний бот призначений для обирання випадкогово учасника чату, який належить до відповідного списку."\ " Даний список формується автоматично - юзер додається до нього, коли приєднується до чату та вилучається у випадку покидання." \ " Також ці команди доступі мануально: додати юзера - це може зробити лише сам юзер; вилучити юзера - це може зробити лише адміністратор групи"\ " (отже, щоб самостійно не доводилось додавати кожного юзера, під час створення групи до учасників требя включити лише Punisher'a, а потім додати всіх людей)."\ " Жоден бот не може бути в списку. Використовуйте відповідну команду для обирання випадкового учасника чату." bot.send_message(chat_id, msg)
def send_participant_added(message): chat_id = message.chat.id username = message.from_user.username if username is None: username = message.from_user.first_name msg = "@{0}, вас додано до списку. Тепер вилучити вас може лише адміністратор!".format( username) bot.send_message(chat_id, msg)
def default(update, user): search_request = update.message.text chat_id = update.message.chat_id bot.send_message(chat_id=chat_id, text='searching...') searchResults = search.find_products(search_request) for result in searchResults: # type: SearchedProduct result bot.send_message(chat_id=chat_id, text=result.SearchedProduct + '\n') bot.send_photo(chat_id=chat_id, photo=result.image)
def notify(group, user_id, flag): try: bot.send_message( user_id, text=prefix + get_schedule("Завтра", group, bot, user_id, flag), parse_mode="html", disable_web_page_preview=True ) except ApiException: pass
def handle_left_member(message): try: if mem.allow_remove_member(message): mem.remove_member(message) rw.save_stats_in_file(mem.file_of_members, mem.members) rw.delete_first__line_in_file(mem.file_of_members) mem.send_parting(message) except Exception as e: bot.send_message(message.chat.id, e)
def wikiButtonAction(chatContext): article = getWikiArticle(chatContext.word, 'simple') if article: formattedWord = "<b>" + chatContext.word + "</b>" formattedMessage = article.summary formattedURL = "<a href=\"" + article.url + "\">" + article.url + "</a>" message = formattedWord + "\n" + formattedMessage + "\n" + formattedURL return bot.send_message(chatContext.chatId, message, parse_mode = "HTML") else: return bot.send_message(chatContext.chatId, "Sorry, no results for " + chatContext.word)
def insert_birthday(name, date, telephone, gender): """Добавить день рождения в базу.""" connection.ping() try: cursor = connection.cursor() sql = f"INSERT INTO `happy_birthdays` (id, name, date, telephone, gender, active) " \ f"VALUES (DEFAULT, '{name}', '{date}', '{telephone}', '{gender}', '1');" cursor.execute(sql) connection.commit() except Exception as e: bot.send_message(adm_id, f"При выполнении insert_birthday произошла ошибка: {e}")
def wrapped(message): if not storage.admin_exist(message.chat.id): bot.send_message( chat_id=message.chat.id, text='You are not admin. This accident will be reported.') for admin_id in storage: bot.send_message(chat_id=admin_id, text='Func usage attempt from @{}'.format( message.from_user.username)) return return func(message)
def get_current_date(): """Получить текущую дату из базы данных.""" connection.ping() try: cursor = connection.cursor() sql = f"SELECT CURRENT_DATE FROM `happy_birthdays`;" cursor.execute(sql) return cursor.fetchone()["CURRENT_DATE"] except Exception as e: print(e) bot.send_message(adm_id, f"При выполнении get_current_date возникла ошибка: {e}")
def lnk(c): bot.delete_message(chat_id=c.message.chat.id, message_id=c.message.message_id) db_vote_set(c.from_user.id, db_vote_get(c.from_user.id) - 5) bot.send_message(c.message.chat.id, "*ID:" + str(c.from_user.id) + " Profile*" + "\n" + "Vote points: " + str(db_vote_get(c.from_user.id)) + "\n" + constants.LIKE_DISLIKE + str(db_value_get(c.from_user.id, "like")) + "|" + str(db_value_get(c.from_user.id, "dislike")), parse_mode="Markdown", reply_markup=prof_keyboard())
def select_active_birthdays(): """Активные дни рождения в сыром виде из базы.""" connection.ping() try: cursor = connection.cursor() sql = f"SELECT * FROM `happy_birthdays` WHERE active = '1';" cursor.execute(sql) birthdays = cursor.fetchall() return birthdays except Exception as e: print(e) bot.send_message(adm_id, f"При выполнении select_active_birthdays возникла ошибка: {e}")
def daily_weather_handler(message): active_user = get_active_user(message.from_user.id) if active_user.subscribed: bot.send_message(message.chat.id, f'You are subscribed to daily weather, your default city is {active_user.default_location}', reply_markup=daily_weather(active_user.subscribed)) bot.register_next_step_handler(message, handle_subscribe_choise) else: bot.send_message(message.chat.id, 'You are not subscribed to daily weather :(', reply_markup=daily_weather(active_user.subscribed)) bot.register_next_step_handler(message, handle_subscribe_choise)
def handle_new_member(message): try: if not mem.is_chat_registered(message): mem.add_chat(message) if mem.allow_add_member(message): mem.add_member(message) rw.save_stats_in_file(mem.file_of_members, mem.members) rw.delete_first__line_in_file(mem.file_of_members) mem.send_greetings(message) except Exception as e: bot.send_message(message.chat.id, e)
def run_dispatch(message): received = 0 users = Student.select() for user in users: try: bot.send_message(user.student_id, text=message) received += 1 print(received) except ApiException: pass sleep(TIMEOUT) return f"{received}/{len(users)}"