コード例 #1
0
def update_job(context):
    with db.connection() as cursor:
        updates = jobs.check_updates(
            jobs.get_last_data(db.get(cursor, "*", "country", multiple=True)),
            jobs.get_current(),
        )

    for country in updates.keys():
        for data in updates[country].keys():
            if "difference" not in data and "today" not in data:
                with db.connection() as cursor:
                    db.update(
                        cursor,
                        "country",
                        data,
                        updates[country][data]["total"],
                        "name",
                        country,
                    )

    with db.connection() as cursor:
        users = db.get_users(cursor)

    messages = jobs.generate_update_message(updates)

    for user in users:
        if user[1] in messages.keys():
            try:
                context.bot.send_message(chat_id=user[0],
                                         text=messages[user[1]])
            except telegram.error.Unauthorized:
                with db.connection() as cursor:
                    db.delete_user(cursor, user[0])
コード例 #2
0
def delete():
    id_ = request.json['id']

    delete_user(id_)
    empty = json.dumps({'msg': 'ユーザーを削除しました。'})

    return jsonify(empty)
コード例 #3
0
    def loggedin(self, username):
        """
        function to handle logged user
        shows menu with actions for logged users
        """

        self.send("Access granted!")

        while True:
            self.send(
                " \nWhat do you want to do? (ls/change_password/logout/delete_account)"
            )  # menu for logged user
            self.send(actions.TYPE_ACTION)
            current_type = self.receive()  # get type
            if current_type is None:  # if
                print "Connection lost"  # error occurred
                return  # leave function
            elif current_type == "change_password":
                self.change_password(username)
            elif current_type == "ls":  # ls - fake function
                self.send(
                    "root home etc lib media mnt")  # to show some directories
            elif current_type == "delete_account":  # give possibility to resign of the account
                database.delete_user(username)  # delete user from database
                self.send("Your account was removed form system")
                return
            elif current_type == "logout":  # end of work
                return  # leave function
            else:
                self.send("unrecognized type")
コード例 #4
0
async def handler(event):
    if event.data == b'polit':
        await event.answer('Успешно!')
        u_choice['politics'] = 1
    if event.data == b'tech':
        await event.answer('Хороший выбор!')
        u_choice['tech'] = 1
    if event.data == b'business':
        await event.answer('Вау!')
        u_choice['business'] = 1
    if event.data == b'ent':
        await event.answer('Успешно!')
        u_choice['entertainment'] = 1
    if event.data == b'sport':
        await event.answer('Успешно!')
        u_choice['sport'] = 1
    if event.data == b'close':
        await event.answer('Успешно')
        sender = await event.get_sender()
        database.create_new_user(sender.id, u_choice=u_choice)
        await bot.send_message(sender,
                               'Категории выбраны!',
                               buttons=Button.clear())

    if event.data == b'yes':
        sender = await event.get_sender()
        database.delete_user(sender.id)
        await bot.send_message(sender, "Выбери категории:", buttons=buttons)
    if event.data == b'no':
        sender = await event.get_sender()
        await bot.send_message(sender, "Ок")
コード例 #5
0
def delete_user_profile():
    """
    On get returns "delete profile" page to confirm if user really wants to delete their profile.
    On post deletes user profile. Note all user's ads will be automatically deleted as well because this
    is how database is setup (there is an automatic delete cascade for user->ad objects).
    :return:
    """
    user = flask_login.current_user
    delete_user_profile_form = FlaskForm()
    if request.method == 'POST' and delete_user_profile_form.validate_on_submit(
    ):
        if not user_is_authorized_to_update_item(user.id):
            flash("You are not authorized to update this page")
            return redirect(url_for("index"))

        user_email = user.email
        user_id = user.id
        database.set_user_authenticated_status(user, False)
        flask_login.logout_user()
        database.delete_user(database.get_user_by_unicode_id(user_id))

        flash("User account for " + user_email +
              "and all ads for this account were deleted.")
        return redirect(url_for("index"))

    return render_template("delete_user_profile.html",
                           user=user,
                           delete_user_profile_form=delete_user_profile_form,
                           page_info=get_page_info())
コード例 #6
0
ファイル: admin.py プロジェクト: thebetabox/orthrus
def delete_user():
    user = {
        "username": request.form["username"]
    }
    if user["username"] == session["username"]:
        abort(409)

    database.delete_user(user)

    return redirect(url_for("admin_users"))
コード例 #7
0
def test_delete_user(req_context):
    from database import insert_user, make_list, add_list_user
    from database import delete_user
    insert_user("Test User", "password", "*****@*****.**")
    insert_user("Test User2", "password2", "*****@*****.**")
    user_id1 = run_independent_query("SELECT user_id FROM users")[0][0]
    user_id2 = run_independent_query("SELECT user_id FROM users")[1][0]
    make_list("Title", "Description", user_id1)
    list_id = run_independent_query("SELECT * FROM lists")[0][0]
    add_list_user(list_id, user_id2)
    delete_user(user_id2)
    users = run_independent_query("SELECT * FROM users")
    print users
    assert len(users) == 1
コード例 #8
0
ファイル: test_database.py プロジェクト: markableidinger/wist
def test_delete_user(req_context):
    from database import insert_user, make_list, add_list_user
    from database import delete_user
    insert_user("Test User", "password", "*****@*****.**")
    insert_user("Test User2", "password2", "*****@*****.**")
    user_id1 = run_independent_query("SELECT user_id FROM users")[0][0]
    user_id2 = run_independent_query("SELECT user_id FROM users")[1][0]
    make_list("Title", "Description", user_id1)
    list_id = run_independent_query("SELECT * FROM lists")[0][0]
    add_list_user(list_id, user_id2)
    delete_user(user_id2)
    users = run_independent_query("SELECT * FROM users")
    print users
    assert len(users) == 1
コード例 #9
0
def users_page():
    if request.method == 'GET':
        users = db.get_info("users")
        return render_template("users.html", users=users)
    elif request.method == 'POST':
        if request.form.get("action") == "edit":
            data = {
                "user_id": request.form.get("user_id"),
                "name": request.form.get('name'),
                "surname": request.form.get('surname')
            }
            db.edit_user(data)
            print(data)
        elif request.form.get("action") == "delete":
            db.delete_user(request.form.get("user_id"))
        users = db.get_info("users")
        return render_template("users.html", users=users)
コード例 #10
0
def start(update, context):
    """Default command that is run when a user starts a bot

    Raises:
        telegram.error.Unauthorized: If message cannot be sent, that means user no longer uses the bot, then delete their data.
    """
    try:
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text=texts.welcome(),
        )
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text=texts.github(),
            reply_markup=keyboards.github(),
        )
    except telegram.error.Unauthorized:
        with db.connection() as cursor:
            db.delete_user(cursor, update.effective_chat.id)
コード例 #11
0
def main():
    options = int(input("1: Add User"
                        "\n2: Delete User"
                        "\n3: Check User"
                        "\n4: Display Db"
                        "\n5: Create Db\n"))

    if options == 1:
        try:
            database.new_user()
        except Exception as error:
            print("ERROR:", error)
        finally:
            print("\n")
            main()
    if options == 2:
        try:
            database.delete_user()
        except Exception as error:
            print("ERROR:", error)
        finally:
            print("\n")
            main()
    if options == 3:
        try:
            database.check_user()
        except Exception as error:
            print("ERROR:", error)
        finally:
            print("\n")
            main()
    if options == 4:
        database.display_db()
        print("\n")
        main()
    if options == 5:
        try:
            database.create_db()
            print("Database created\n")
        except Exception as error:
            print("Error", error)
        finally:
            main()
コード例 #12
0
ファイル: users.py プロジェクト: xang555/face_recon
def del_user():
    if not request.is_json:
        return jsonify(msg="Missing JSON in request"), 400

    user_id = request.json.get('user_id', None)

    if not user_id:
        return jsonify(msg="Bad request"), 400

    if not delete_user(user_id):
        return jsonify(msg="Delete user failed"), 400

    return jsonify(msg='Delete user Success'), 200
コード例 #13
0
 def remove(id: int):
     """Delete specific user"""
     with create_connection() as connection:
         delete_user(connection, id)
コード例 #14
0
def delete_user(user_id):
    rows_affected = db.delete_user(user_id)
    if(rows_affected):
        return make_response('', 204)
    else:
        make_response(jsonify({'error': "couldn't delete user"}), 404)
コード例 #15
0
def bot(request):
    body = json.loads(request.body)
    owner_id = -194135879
    print(body)

    # Подтверждение сервера
    if body == {
            "type": "confirmation",
            "group_id": 194135879,
            "secret": "very1secre2tkey3vk4bota"
    }:  #Берем запрос и ответ в CallBack API
        return HttpResponse("771a5e5c")

    # Обработчик сообщений
    if body["type"] == "message_new":

        user_id = body["object"]["message"]["from_id"]
        split_body = body["object"]["message"]["text"].split(maxsplit=3)
        query_msg = database.get("answer", "msg")
        query_group = database.get("groups", "group_name")
        user_msg = body["object"]["message"]["text"]

        if "payload" in body["object"]["message"]:
            payload = body["object"]["message"]["payload"]

            if payload == """{"command":"start"}""":
                keyboard_start(request, user_id)

            try:

                if payload == """{"command":"sempai"}""":
                    database.insert_into_users(user_id, 1)
                    msg = f"Отлично, теперь вы {query_group[0][0]}! ⛩️"
                    attachment = f"photo{owner_id}_457239021"
                    send_message(user_id, msg, attachment)

                elif payload == """{"command":"moder"}""":
                    database.insert_into_users(user_id, 2)
                    msg = f"Отлично, теперь вы {query_group[1][0]}! 🛡️"
                    attachment = f"photo{owner_id}_457239020"
                    send_message(user_id, msg, attachment)

                elif payload == """{"command":"user"}""":
                    database.insert_into_users(user_id, 3)
                    msg = f"Отлично, теперь вы {query_group[2][0]}! ♟️"
                    attachment = f"photo{owner_id}_457239022"
                    send_message(user_id, msg, attachment)

            # Если пользователь уже есть в db
            except sqlite3.IntegrityError:
                msg = "Вы уже состоите в группе пользователей! 💢"
                send_message(user_id, msg)

        elif user_msg in query_msg[0][0] and user_msg == "/list":
            msg = database.get("answer")
            print(query_msg[1])
            send_message(user_id, msg)

        elif user_msg in query_msg[2][0] and user_msg == "/start":
            msg = database.get("answer", "answ")[0]
            send_message(user_id, msg)

        # elif user_msg in query_msg[4][0] and user_msg == 'привет':
        #     # hello_text = f'Ну привет-привет, {get_user_name(user_id)}'
        #     # msg = database.update("answer", "answ", hello_text, 5)[0]
        #     msg = "Ну привет-привет"
        #     send_message(user_id, msg)

        elif split_body[0] == '/say':
            if len(split_body) == 2:
                text = split_body[1]
            elif len(split_body) == 3:
                text = f"{split_body[1]} {split_body[2]}"
            else:
                text = f"{split_body[1]} {split_body[2]} {split_body[3]}"
            msg = text
            send_message(user_id, msg)

        elif user_msg in query_msg[1][0] and user_msg == "/post":
            msg = database.get("answer", "answ")[2]
            attachment = f"wall{owner_id}_2"
            send_message(user_id, msg, attachment)

        elif user_msg == "/change_group":
            user_list = database.get("users")
            # if user_id in user_id_list:
            #удалить пользователя из базы
            #вызвать клаву
            #обработать запрос

            database.delete_user(user_id)
            keyboard_start(request, user_id)

        elif split_body[0] == '/teach':
            if len(split_body) == 4:
                db_msg = split_body[1]
                db_answ = split_body[2]

                database.insert_into("answer", db_msg, db_answ)
                msg = database.get("answer", "answ")[3]
                send_message(user_id, msg)
            else:
                msg = "При обучении бота что-то пошло не так. Проверь правильность написания команды"
                send_message(user_id, msg)

        # elif "attachments" in body["object"]["message"]:
        #     if body["object"]["message"]["attachments"][0]["type"] == "sticker":
        #         msg = 'Че стикеры шлешь?! 😡'
        #         send_message(user_id, msg)

        # else:
        #     msg = 'Чет не понимаю, что ты мне пишешь, но ты можешь обучить меня с помощью команды /teach'
        #     send_message(user_id, msg)

    return HttpResponse("ok")
コード例 #16
0
# -*- coding: utf-8 -*-
import database
import slack

print "ユーザーを削除します。"
# inputして古い名前を取得
student_id = raw_input("削除するユーザーの学籍番号を入力してください:").upper()
# エラー処理
try:
    name = database.find_name(student_id)
except UnboundLocalError:
    print "学籍番号が不正または登録されていません。"
    exit(1)
print "削除する方の名前は %s です。" % name
# 確認
answer = input("本当に削除しますか?\n削除する場合は1を入力してください:")
if answer is 1:
    # データベースに反映
    database.delete_user(student_id)
    slack.delete_user(student_id, name)
    print "削除しました。"
else:
    print "終了します。"
    exit(0)
コード例 #17
0
 def on_delete(self, req, resp, username):
     tokenUsername = req.context['username']
     db.delete_user(tokenUsername)
     resp.body = json.dumps({'Success': 'User record deleted'})
コード例 #18
0
ファイル: manage.py プロジェクト: baranyak/workshop
    print('  ~:$ python3 manage.py load_default')
    sys.exit(1)


if __name__ == '__main__':
    if len(sys.argv) == 2 and sys.argv[1] == 'load_default':
        connection = database.connect()
        for table_name in 'users', 'tasks':
            database.drop_table(connection, table_name)
            database.create_table(connection, table_name)
            database.load_default(connection, table_name)
        connection.close()
    elif len(sys.argv) == 2 and sys.argv[1] == 'getusers':
        connection = database.connect()
        for user, password in database.get_user_credentials(connection):
            print('user:password -> {0}:{1}'.format(user, password))
        connection.close()
    elif len(sys.argv) == 3 and sys.argv[1] == 'adduser':
        connection = database.connect()
        database.insert_user(connection, sys.argv[2])
        connection.close()
    elif len(sys.argv) == 3 and sys.argv[1] == 'userdel':
        connection = database.connect()
        database.delete_user(connection, sys.argv[2])
        connection.close()
    else:
        print_usage()
        sys.exit(1)


コード例 #19
0
ファイル: dropboxdb.py プロジェクト: tarun0409/dropbox
 def delete_user(self, user_id):
     db.delete_user(self.db_obj, self.db_cursor, user_id)
コード例 #20
0
def delete_user(username):
    """delete an existing user by name"""
    return database.delete_user(username)
コード例 #21
0
ファイル: main.py プロジェクト: skywinder/travelcombot
def callback_inline(call):
    cid = call.message.chat.id
    uid = call.from_user.id

    print(call.data)

    try:
        bot.answer_callback_query(call.id, '✅')
    except Exception as e:
        print(e)

    # Обработка подтверждения\отклонения новых анкет админом
    if call.data.startswith('confirmanket'):
        anket_id = int(call.data.split('_')[1])
        user_id = int(call.data.split('_')[2])
        database.confirm_user(anket_id)

        # Выслать уведомление пользователю
        try:
            bot.send_message(user_id, texts.success_confirm_anket_text)
        except Exception as e:
            print(e)

        return bot.edit_message_caption(texts.success_register,
                                        chat_id=cid,
                                        message_id=call.message.message_id)
    elif call.data.startswith('refuseanket'):
        anket_id = int(call.data.split('_')[1])
        user_id = int(call.data.split('_')[2])
        database.delete_all_user_events(anket_id)
        database.delete_user(anket_id)

        # Выслать уведомление пользователю
        try:
            bot.send_message(user_id, texts.unsuccess_confirm_anket_text)
        except Exception as e:
            print(e)

        return bot.edit_message_caption(texts.unsuccess_register,
                                        chat_id=cid,
                                        message_id=call.message.message_id)

    # Обработка выбора мероприятий при регистрации
    if call.data.startswith('selecttypeofevent'):
        typeofevent_id = int(call.data.split('_')[1])
        events = database.get_events_by_event_type_id(typeofevent_id)
        keyboard = types.InlineKeyboardMarkup()
        for x in events:
            month_name = util.get_month_name_by_number(
                x['date_of_the_event'].month)
            country = database.get_country_by_id(x['country'])
            event_name = '{!s}, {!s}, {!s} {!s}'.format(
                x['name'], country['name'], month_name,
                x['date_of_the_event'].year)
            keyboard.add(
                types.InlineKeyboardButton(
                    text=event_name,
                    callback_data='selectevent_{!s}'.format(x['id'])))
        keyboard.add(
            types.InlineKeyboardButton(text='↪️ Назад',
                                       callback_data='selectalltypeevents'))
        return bot.edit_message_text(texts.register_events_question_text,
                                     chat_id=cid,
                                     message_id=call.message.message_id,
                                     reply_markup=keyboard)
    elif call.data.startswith('selectevent'):
        event_id = int(call.data.split('_')[1])
        if uid not in READY_TO_REGISTER:
            text = 'Отправьте /start и повторите регистрацию'
            return bot.edit_message_text(text,
                                         chat_id=cid,
                                         message_id=call.message.message_id,
                                         reply_markup=None)
        event = database.get_event_by_id(event_id)
        text = 'Вы выбрали мероприятие {!s}'.format(event['name'])
        READY_TO_REGISTER[uid]['event_ids'].append(event_id)
        READY_TO_REGISTER[uid]['events_text'] += '{!s}\n'.format(event['name'])
        bot.edit_message_text(text,
                              chat_id=cid,
                              message_id=call.message.message_id,
                              reply_markup=None)
        text = 'Желаете отметить ещё мероприятия?'
        keyboard = types.InlineKeyboardMarkup()
        keyboard.add(
            types.InlineKeyboardButton(text='➕ Добавить ещё',
                                       callback_data='selectalltypeevents'))
        keyboard.add(
            types.InlineKeyboardButton(text='➡️ Далее',
                                       callback_data='nextactionsafterevents'))
        return bot.send_message(cid, text, reply_markup=keyboard)
    elif call.data == 'selectalltypeevents':
        typeofevents = database.get_all_typeofevents()
        keyboard = types.InlineKeyboardMarkup()
        for x in typeofevents:
            keyboard.add(
                types.InlineKeyboardButton(
                    text=x['name'],
                    callback_data='selecttypeofevent_{!s}'.format(x['id'])))
        return bot.edit_message_text(texts.register_type_events_question_text,
                                     chat_id=cid,
                                     message_id=call.message.message_id,
                                     reply_markup=keyboard)
    elif call.data == 'nextactionsafterevents':
        if uid not in READY_TO_REGISTER:
            text = 'Отправьте /start и повторите регистрацию'
            return bot.edit_message_text(text,
                                         chat_id=cid,
                                         message_id=call.message.message_id,
                                         reply_markup=None)
        READY_TO_REGISTER[uid]['events'] = True
        return bot.send_message(cid, texts.register_confirm_people_text)

    # Обработка добавления новых мероприятий
    if call.data.startswith('addselecttypeofevent'):
        typeofevent_id = int(call.data.split('_')[1])
        events = database.get_events_by_event_type_id(typeofevent_id)
        user = database.get_user(uid)
        user_event_ids = [
            x['event'] for x in database.get_user_events(user['id'])
        ]
        keyboard = types.InlineKeyboardMarkup()
        for x in events:
            if x['id'] in user_event_ids:
                continue
            month_name = util.get_month_name_by_number(
                x['date_of_the_event'].month)
            country = database.get_country_by_id(x['country'])
            event_name = '{!s}, {!s}, {!s} {!s}'.format(
                x['name'], country['name'], month_name,
                x['date_of_the_event'].year)
            keyboard.add(
                types.InlineKeyboardButton(
                    text=event_name,
                    callback_data='addselectevent_{!s}'.format(x['id'])))
        keyboard.add(
            types.InlineKeyboardButton(text='↪️ Назад',
                                       callback_data='addselectalltypeevents'))
        return bot.edit_message_text(texts.register_events_question_text,
                                     chat_id=cid,
                                     message_id=call.message.message_id,
                                     reply_markup=keyboard)
    elif call.data.startswith('addselectevent'):
        event_id = int(call.data.split('_')[1])
        event = database.get_event_by_id(event_id)
        text = 'Вы добавили мероприятие {!s}'.format(event['name'])
        user = database.get_user(uid)
        database.add_user_event(user['id'], event_id)
        bot.edit_message_text(text,
                              chat_id=cid,
                              message_id=call.message.message_id,
                              reply_markup=None)
        text = 'Желаете отметить ещё мероприятия?'
        keyboard = types.InlineKeyboardMarkup()
        keyboard.add(
            types.InlineKeyboardButton(text='➕ Добавить ещё',
                                       callback_data='addselectalltypeevents'))
        return bot.send_message(cid, text, reply_markup=keyboard)
    elif call.data == 'addselectalltypeevents':
        typeofevents = database.get_all_typeofevents()
        keyboard = types.InlineKeyboardMarkup()
        for x in typeofevents:
            keyboard.add(
                types.InlineKeyboardButton(
                    text=x['name'],
                    callback_data='addselecttypeofevent_{!s}'.format(x['id'])))
        return bot.edit_message_text(texts.register_type_events_question_text,
                                     chat_id=cid,
                                     message_id=call.message.message_id,
                                     reply_markup=keyboard)
コード例 #22
0
 def delete_user(self, instance):
     self.dismiss()
     database.delete_user(manager.CURRENT_USER)
     manager.CURRENT_USER = None
     manager.menu.clear_info_panel()
     manager.menu.show_users()