def sendall(bot, update):
    if check_username(bot, update) == False:
        return
    query = get_query(bot, update)
    if query.message.chat.username in [
            "ya_thatguy", "Ilyazdorenko", "coach_ilya"
    ]:
        connection = pymongo.MongoClient(os.environ['MONGODB_URI'])
        db = connection["heroku_20w2cn6z"]
        client_list = json.loads(json_util.dumps(db["clients"].find({})))
        for client in client_list:
            logging.info(client["username"])
            text = query.message.text[9:]
            try:
                bot.sendMessage(text=text, chat_id=client["chat_id"])
                logging.info("\tMessage sent")
            except Exception as exc:
                logging.critical(client["username"])
                logging.critical("\t@{}: message WAS NOT sent".format(
                    client["username"]))
                logging.critical(exc)
            sleep(1)
        connection.close()
    else:
        bot.sendMessage(text="Не хочешь выполнять ты команду эту... 👻",
                        chat_id=query.message.chat.id)
def start(bot, update):
    query = get_query(bot, update)
    if check_username(bot, update) == False:
        return
    kb_markup = keyboard()
    bot.send_message(chat_id=query.message.chat.id,
                     text="Добро пожаловать, @{}!".format(
                         query.message.chat.username),
                     reply_markup=kb_markup)
    log_client(bot, update)
def train_details(bot, update, train):
    if check_username(bot, update) == False:
        return
    query = get_query(bot, update)
    kb = []
    try:
        if "attendee" in train and query.message.chat.username in train[
                "attendee"]:
            text_sign = "❌ Не смогу прийти"
            signup = telegram.InlineKeyboardButton(text=text_sign,
                                                   callback_data="101;" +
                                                   str(train["id"]))
        else:
            text_sign = "✅ Записаться"
            signup = telegram.InlineKeyboardButton(text=text_sign,
                                                   callback_data="102;" +
                                                   str(train["id"]))
    except Exception as exc:
        logging.exception(exc)
    text_attendees = "🙏 Участники"
    attendees = telegram.InlineKeyboardButton(text=text_attendees,
                                              callback_data="105;{};".format(
                                                  str(train["id"])))
    kb.append([signup, attendees])
    text_loc = "🗺 Где это?"
    location = telegram.InlineKeyboardButton(text=text_loc,
                                             callback_data="103;" +
                                             str(train["id"]))
    #    text_cal = "🗓 Добавить"
    #    cal = telegram.InlineKeyboardButton(text=text_cal, url=train["htmlLink"] +
    #        "&action=TEMPLATE" +
    #        "&text=" + train["summary"] +
    #        "&dates=" + train["start"]["dateTime"] + "/" + train["end"]["dateTime"] + # Проблема с конвертацией даты
    #        "&trp=false" +
    #        "&sprop=" +
    #        "&sprop=name:" +
    #        "&pprop=HowCreated:QUICKADD&scp=ONE")
    #    logging.critical(cal)
    #    kb.append([location, cal])
    kb.append([location])
    kb_markup = telegram.InlineKeyboardMarkup(kb)
    bot.sendMessage(text="Детали по событию: {} - {}".format(
        train["start"]["date"], train["summary"]),
                    chat_id=query.message.chat.id,
                    reply_markup=kb_markup)
def sign_out(bot, update, db_name, thing_id):
    if check_username(bot, update) == False:
        return
    query = get_query(bot, update)
    thing = get_thing(db_name, thing_id)
    connection = pymongo.MongoClient(os.environ['MONGODB_URI'])
    db = connection["heroku_20w2cn6z"]
    try:
        thing["attendee"].remove(query.message.chat.username)
        db[db_name].update({"id": thing_id},
                           {"$set": {
                               "attendee": thing["attendee"]
                           }})
        bot.sendMessage(
            text=
            "Жаль. Посмотри на другие мероприятия. Возможно, что то подойтет тебе.",
            chat_id=query.message.chat_id)
    except Exception as exc:
        logging.exception(exc)
    connection.close()
def sign_in(bot, update, db_name, thing_id):
    if check_username(bot, update) == False:
        return
    query = get_query(bot, update)
    try:
        thing = get_thing(db_name, thing_id)
    except Exception as exp:
        logging.critical(exp)
    connection = pymongo.MongoClient(os.environ['MONGODB_URI'])
    db = connection["heroku_20w2cn6z"]
    try:
        if "attendee" not in thing or query.message.chat.username not in thing[
                "attendee"]:
            db[db_name].update(
                {"id": thing_id},
                {"$push": {
                    "attendee": query.message.chat.username
                }},
                upsert=True)
            bot.sendMessage(text="Отлично, записались!",
                            chat_id=query.message.chat_id)
            if thing["start"]["dateTime"].split("T")[1][:5] != "00:00":
                bot.sendMessage(text="Ждем тебя {} в {}".format(
                    thing["start"]["dateTime"].split("T")[0],
                    thing["start"]["dateTime"].split("T")[1][:5]),
                                chat_id=query.message.chat_id)
            else:
                bot.sendMessage(text="Ждем тебя {}".format(
                    thing["start"]["dateTime"].split("T")[0]),
                                chat_id=query.message.chat_id)
        else:
            bot.sendMessage(
                text=
                "Ты уже записан на тренировку. Или ты хочешь выполнять в 2 раза больше повторений!? Скажи тренеру об этом перед началом 😉",
                chat_id=query.message.chat_id)
    except Exception as exc:
        logging.exception(exc)
    connection.close()
def event_details(bot, update, event):
    if check_username(bot, update) == False:
        return
    query = get_query(bot, update)
    kb = []
    try:
        if "attendee" in event and query.message.chat.username in event[
                "attendee"]:
            text_sign = "❌ Не смогу прийти"
            signup = telegram.InlineKeyboardButton(text=text_sign,
                                                   callback_data="201;" +
                                                   str(event["id"]))
        else:
            text_sign = "✅ Записаться"
            signup = telegram.InlineKeyboardButton(text=text_sign,
                                                   callback_data="202;" +
                                                   str(event["id"]))
    except Exception as exc:
        logging.exception(exc)
    text_attendees = "🙏 Участники"
    attendees = telegram.InlineKeyboardButton(text=text_attendees,
                                              callback_data="205;{};".format(
                                                  str(event["id"])))
    kb.append([signup, attendees])
    text_loc = "🗺 Где это?"
    location = telegram.InlineKeyboardButton(text=text_loc,
                                             callback_data="203;" +
                                             str(event["id"]))
    text_info = "📋 Информация"
    info = telegram.InlineKeyboardButton(text=text_info,
                                         callback_data="204;" +
                                         str(event["id"]))
    kb.append([info, location])
    kb_markup = telegram.InlineKeyboardMarkup(kb)
    bot.sendMessage(text="Детали по событию: {} - {}".format(
        event["start"]["date"], event["summary"]),
                    chat_id=query.message.chat.id,
                    reply_markup=kb_markup)
def attendee(bot, update):
    query = get_query(bot, update)
    if check_username(bot, update) == False:
        return
    get_trains(bot, update, user=query.message.chat.username)
    get_events(bot, update, user=query.message.chat.username)