Exemple #1
0
def process_response(**kwargs):
    print json.dumps(kwargs)
    # save response
    session = db.get_session(kwargs["session_id"])
    question = db.get_question(session["survey_id"],
                               session["question_ordernumber"])
    question_id = question["id"]
    response = ""
    if str(question_id) in kwargs:
        response = kwargs[str(question_id)]

    if question["type"] in {"1", "M", "O", "JN"}:
        if question["type"] == "M":
            response = ",".join(response)
        db.save_response(session["id"], question_id, response)

    if "next" in kwargs:
        c = db.next_question(kwargs["session_id"])
        print "wat is c?", c
        while c and not check_condition(session["id"]):
            c = db.next_question(kwargs["session_id"])
    if "back" in kwargs:
        c = db.prev_question(kwargs["session_id"])
        while c and not check_condition(session["id"]):
            c = db.prev_question(kwargs["session_id"])
    return render_survey(kwargs["session_id"])
Exemple #2
0
def send_questions(message, test_id, row_num=0):
    telegram_id = message.chat.id
    chat_id = message.chat.id
    time_end = False
    if row_num != 0:
        start_time = sql.check_first_answer_time(test_id, telegram_id)
        diff = datetime.now() - start_time
        diff_minutes = diff.seconds / 60
        if diff_minutes >= config.minutes_to_test:
            time_end = True
    if time_end:
        bot.send_message(chat_id=chat_id,
                         text='Время закончилось, глянем на твои результаты.')
        bot.send_sticker(
            chat_id=chat_id,
            data=
            'CAACAgIAAxkBAAECMg5geq9IrghFjdKmFmEbjTigXmmGeAACMAADNraOCPwLBo-827_NHwQ'
        )
        results = sql.get_test_results(telegram_id, test_id)
        correct = results[0]
        incorrect = results[1]
        num_questions = results[2]
        text = f'Correct answers - {correct}\nIncorrect answers - {incorrect}\nNumber of questions - {num_questions}'
        bot.send_message(chat_id=chat_id, text=text)
    else:
        chat_id = message.chat.id
        telegram_id = message.chat.id
        question = sql.get_question(test_id=test_id, row_num=row_num)
        if question:
            q_id = question[0]
            q_text = question[1]
            variants = sql.get_variants(question_id=q_id)
            markup_inline = InlineKeyboardMarkup()
            text = q_text + '\n'
            for variant in variants:
                v_id = variant[0]
                v_text = variant[1]
                text = text + f'\n• {v_text}'
                markup_inline.add(
                    InlineKeyboardButton(
                        text=f'{v_text}',
                        callback_data=
                        f'v_id={v_id}row_num={row_num}test_id={test_id}'))
            bot.send_message(chat_id=chat_id,
                             text=text,
                             reply_markup=markup_inline)
        else:
            bot.send_message(chat_id=chat_id,
                             text='Тест завершен, глянем на твои результаты.')
            bot.send_sticker(
                chat_id=chat_id,
                data=
                'CAACAgIAAxkBAAECMg5geq9IrghFjdKmFmEbjTigXmmGeAACMAADNraOCPwLBo-827_NHwQ'
            )
            results = sql.get_test_results(telegram_id, test_id)
            correct = results[0]
            incorrect = results[1]
            num_questions = results[2]
            text = f'Correct answers - {correct}\nIncorrect answers - {incorrect}\nNumber of questions - {num_questions}'
            bot.send_message(chat_id=chat_id, text=text)
Exemple #3
0
def game_state2(player):
    global entered_text

    if player.leader:
        display_text.display_text("Waiting for responses", window, pixel_width, pixel_height)
        database.player_ready(player.number, player.game_number)
        if database.are_players_ready(player.game_number):
            database.next_game_state(player.game_number, player.game_state)
    elif not player.leader and player.is_typing:
        question = database.get_question(player.game_number)
        display_text.display_text("Respond to the following: " + str(question),
                                  window, 500, 350)
        entered_text = player.enter_text(entered_text, 150, 250, window)
    elif not player.leader and not player.is_typing:
        database.insert_user_input(player.number, entered_text, player.game_number)
        database.player_ready(player.number, player.game_number)
        display_text.display_text("Waiting on other players", window, 500, 500)
def ask_text(update, context):
    question = update.message.text

    question_id = create_question_document(
        question, context.user_data["user_id"],
        context.user_data["full_name"]).inserted_id

    context.chat_data["unanswered_question"] = database.get_question(
        question_id)

    skip_keyboard = [["Skip"]]
    skip_keyboard_markup = ReplyKeyboardMarkup(skip_keyboard,
                                               one_time_keyboard=True,
                                               resize_keyboard=True)
    update.message.reply_text(
        f"Please upload the associated image of the question (or enter 'Skip' if you don\'t want to.):",
        reply_markup=skip_keyboard_markup)

    return ASK_PHOTO
Exemple #5
0
def render_survey(id, survey_id=0):
    # check if the id is a valid id if invite only
    # if there's no session with this id create it
    try:
        if survey_id != 0:
            db.create_session(id, survey_id)
    except:
        pass

    # get the session
    try:
        session = db.get_session(id)
    except:
        return render("/templates",
                      "error.html",
                      errormessage="Ongeldige toegangscode")

    # load the current question
    question = db.get_question(session["survey_id"],
                               session["question_ordernumber"])

    # get options if needed
    options = {}
    if question["type"] in {"1", "M"}:
        options = db.get_options(question["id"])

    # get the template for the question type
    template = get_template(question["type"])
    # load response of question if any
    response = db.get_response(id, question["id"])
    if question["type"] == "M":
        if response != None and len(response) > 0:
            response = map(int, response.split(","))
        else:
            response = []
    # render question
    return render("/templates",
                  template,
                  session_id=id,
                  question=question,
                  options=options,
                  response=response)
Exemple #6
0
def check_condition(session_id):
    session = db.get_session(session_id)
    #   question_id = session["question_id"]
    # load the current question
    question = db.get_question(session["survey_id"],
                               session["question_ordernumber"])
    # evaluate condition if present
    if question["condition_question_id"] != None:
        print(question["condition_expression"])
        # get the response
        response = db.get_response(session["id"],
                                   question["condition_question_id"])
        if response != None:
            print response
            condition = question["condition_expression"].format(
                response=response)
            print condition, "[", response, "]"
            result = eval(condition)
            print "conditie: ", result
            return result
    return True
Exemple #7
0
    async def on_message(self, message):
        if message.guild is None:
            await message.author.send(
                "I can only respond to messages in guilds")
            return
        message.content = message.content.replace("  ", " ")
        person_roles = list(map(lambda role: role.id, message.author.roles))
        server_members = list(
            map(lambda member: member.id, message.guild.members))
        server_roles = list(map(lambda role: role.id, message.guild.roles))
        person_id = message.author.id
        if (message.author.bot):
            return
        ##(guild, message,  person_roles,server_members,server_roles,person_id)
        trigger_msg = database.trigger_messages(message.guild, message,
                                                person_roles, server_members,
                                                server_roles,
                                                message.author.id)
        #print(trigger_msg)
        if trigger_msg is not None:
            for i in trigger_msg:
                if (i[1]):
                    if (not i[0]):
                        await message.channel.send(embed=embeds.simple_embed(
                            False,
                            f'<@!{i[2]}> your smart contract was annuled: {i[1]}'
                        ))
                    else:
                        await message.channel.send(embed=embeds.simple_embed(
                            True, f'a smart contract said: {i[1]}'))
        answer = database.answer_question(message.author, message.content,
                                          message.guild)
        if answer is not None:
            await message.channel.send(
                embed=embeds.simple_embed(answer[0], answer[1]))
        if (message.content.startswith("$")):
            if (message.content.startswith("$smart-contract")):
                if (message.content.count("```") == 2):
                    if (message.content.split("```")[0].count(" ") == 2):
                        await message.channel.send(embed=embeds.simple_embed(
                            True,
                            database.write_contract(
                                message.guild, message.author,
                                message.content.split("```")[1],
                                message.content.split(
                                    " ")[1], client, person_roles,
                                server_members, server_roles, person_id)[1]))
                        return
            if (commands.is_valid_command(message)):
                message_array = message.content.split(" ")
                message_command = message_array[0]
                if (message_command == "$help"):
                    await message.channel.send(embed=embeds.simple_embed(
                        "info", '''
- $help - shows all commands
- $send (from wallet) (to wallet) (amount) - sends an amount to a person from that wallet
- $print (wallet name) (amount) - creates an amount of money in that wallet if you have the role "printer"
- $balance (wallet name) - returns the amount of money in the wallet
- $links - show some links related to this bot
- $smart-contract (trigger) (code block) - code a smart contract
- $clear-contracts - delete all your smart contracts.
- $create (ping wallet) - create an account
- $whois (condition) - figure out who is a condition
- $send-each (from wallet) (ammount) (condition) - send each person who meets a condition
- $set-balance (ping wallet) - set the balance of a wallet for admins only
- $set-balance-each (amount) (condition) - set the balance of each person who meets a condition
- $wallet-settings (target person) (ping wallet) (setting name) (boolean) - change the setting, such as view or access, to allow certain people to do more with wallets
- $trade (wallet) (wanted currency) (giving up currency) (optional limitations) - create a trade
- $accept (message id of trade) (wallet) - accept a trade
- $quiz - start a quiz based on a subject
- $shop (item name) (price) - same as trade but only for admins and you can also offer roles as trades
- $work - get an amount of money no strings attached
- $work-conditional (level name) (work reward) (conditional) - allows admins to add levels to working and give different people different work rewards
                    '''))
                if (message_command == "$send"):
                    #send(person_roles, server_members, server_roles, person_id, guild_id, from_wallet, to_wallet, amount)
                    person_roles = list(
                        map(lambda role: role.id, message.author.roles))
                    server_members = list(
                        map(lambda member: member.id, message.guild.members))
                    server_roles = list(
                        map(lambda role: role.id, message.guild.roles))

                    send_result = database.send(message.author.id,
                                                message.guild,
                                                message_array[1],
                                                message_array[2],
                                                message_array[3])
                    await message.channel.send(embed=embeds.simple_embed(
                        send_result[0], send_result[1]))
                    #if  send_result[0]:
                    #   await message.channel.send(send_result[1])
                    #else:
                    #    await message.channel.send(f'an error occured {send_result[1]}')
                if (message_command == "$create"):
                    result = database.create(message.guild, message_array[1])
                    await message.channel.send(
                        embed=embeds.simple_embed(result[0], result[1]))

                if (message_command == "$balance"):
                    ##guild,wallet,server_members, server_roles
                    if len(message_array) == 1:
                        message_array.append(message.author.mention)
                    bal = database.get_balance(message.author, message.guild,
                                               message_array[1])
                    if (bal[0]):
                        res = ""
                        for key, value in bal[1].items():
                            if ("balance" in key):
                                res = res + f'{key}: {value}\n'
                        await message.channel.send(embed=embeds.simple_embed(
                            True, f'the balance is:\n {res}'))
                    else:
                        await message.channel.send(embed=embeds.simple_embed(
                            False, f'there was an error: {bal[1]}'))
                if (message_command == "$print"):
                    ##(discord_client, guild_id, wallet, amount)
                    result = database.print_money(message.author,
                                                  message.guild,
                                                  message_array[1],
                                                  message_array[2])
                    await message.channel.send(
                        embed=embeds.simple_embed(result[0], result[1]))
                if (message_command == "$clear-contracts"):
                    database.clear_contracts(message.guild, message.author.id)
                    await message.channel.send(embed=embeds.simple_embed(
                        "info", "your contracts were all deleted"))
                if (message_command == "$links"):
                    await message.channel.send(embed=embeds.simple_embed(
                        "info",
                        "Github - https://github.com/eulerthedestroyer/EU-Economy-Bot \n Discord link -  https://discord.gg/ghFs7ZM \n Bot link - https://discord.com/api/oauth2/authorize?client_id=716434826151854111&permissions=268503104m&scope=bot \n Web interface - https://economy-bot.atticuskuhn.repl.co"
                    ))
                if (message_command == "$config"):
                    if message.author.guild_permissions.administrator:
                        await message.channel.send(
                            embed=embeds.simple_embed(*database.set_config(
                                message.guild, message_array[1],
                                message_array[2])))
                    else:
                        await message.channel.send(embed=embeds.simple_embed(
                            False,
                            "you must be an administrator to access the config"
                        ))
                if message_command.startswith("$stats"):
                    result = methods.get_wallet(server_members, server_roles,
                                                message.guild.id,
                                                message_array[1])
                    if (result[0]):
                        print(result)
                        found_wallet = database.wallet_by_id(
                            message.guild, result[1])
                        if "record" in found_wallet:
                            fig = plt.figure(figsize=(10, 5))
                            X1 = list(found_wallet["record"].keys())
                            Y1 = list(found_wallet["record"].values())

                            plt.plot(X1, Y1, label="plot 1")
                            fig.savefig('fig.jpg',
                                        bbox_inches='tight',
                                        dpi=150)
                            await message.channel.send(
                                file=discord.File('fig.jpg'))
                            os.remove("fig.jpg")
                            #await message.channel.send(found_wallet["record"])
                        else:
                            await message.channel.send(
                                embed=embeds.simple_embed(
                                    False, "can't find any stats"))
                    else:
                        await message.channel.send("error")
                if message_command == "$whois":
                    people = methods.whois(message_array[1:], message.guild)
                    return_statement = ""
                    symbol = "\n"
                    if len(people) > 7:
                        symbol = ","
                    for index, person in enumerate(people):
                        if len(return_statement) > 700:
                            return_statement += f' and {len(people)-index} others'
                            break
                        return_statement = return_statement + f'<@{person}>{symbol}'
                    if return_statement == "":
                        return_statement = "(no people found)"
                    embedVar = discord.Embed(
                        title="Result",
                        description=f'Found {len(people)} People',
                        color=0x00ff00)
                    embedVar.add_field(name="People",
                                       value=return_statement,
                                       inline=False)
                    await message.channel.send(embed=embedVar)
                if message_command == "$send-each":
                    people = methods.whois(message_array[3:], message.guild)
                    return_statement = ""
                    successful_transfer = True
                    for person in people:
                        send_result = database.send(message.author.id,
                                                    message.guild,
                                                    message_array[1],
                                                    f'<@{person}>',
                                                    message_array[2])
                        if send_result[0]:
                            return_statement = return_statement + f'<@{person}> - success\n'
                        else:
                            return_statement = return_statement + f'<@{person}> - error: {send_result[1]}\n'
                            successful_transfer = False
                    if return_statement == "":
                        return_statement = "(no people found)"
                    if successful_transfer:
                        embedVar = discord.Embed(title="Result",
                                                 color=0x00ff00)
                    else:
                        embedVar = discord.Embed(title="Result",
                                                 color=0xff0000)

                    embedVar.add_field(name="People",
                                       value=return_statement,
                                       inline=False)
                    await message.channel.send(embed=embedVar)
                if message_command == "$set-balance":
                    if (not message.author.guild_permissions.administrator):
                        await message.channel.send(
                            "you do not have administrator permissions")
                        return
                    result = database.set_money(message.guild,
                                                message_array[2],
                                                message_array[1])
                    await message.channel.send(embed=embeds.simple_embed(
                        result[0], f'{result[0]}{result[1]}'))
                if message_command == "$set-balance-each":
                    if (not message.author.guild_permissions.administrator):
                        await message.channel.send(
                            "you do not have administrator permissions")
                        return
                    people = methods.whois(message_array[2:], message.guild)
                    return_statement = ""
                    successful_transfer = True
                    for person in people:
                        send_result = database.set_money(
                            message.guild, message_array[1], f'<@{person}>')
                        if send_result[0]:
                            return_statement = return_statement + f'<@{person}> - success\n'
                        else:
                            return_statement = return_statement + f'<@{person}> - error: {send_result[1]}\n'
                            successful_transfer = False
                    if return_statement == "":
                        return_statement = "(no people found)"
                    if successful_transfer:
                        embedVar = discord.Embed(title="Result",
                                                 color=0x00ff00)
                    else:
                        embedVar = discord.Embed(title="Result",
                                                 color=0xff0000)

                    embedVar.add_field(name="People",
                                       value=return_statement,
                                       inline=False)
                    await message.channel.send(embed=embedVar)
                if message_command == "$wallet-settings":
                    res = database.set_settings(message.guild, message.author,
                                                message_array[1],
                                                message_array[2],
                                                message_array[3],
                                                message_array[4])
                    await message.channel.send(
                        embed=embeds.simple_embed(res[0], res[1]))
                if message_command == "$trade":
                    res = database.insert_trade(message, message.author,
                                                message.guild,
                                                message_array[1],
                                                message_array[2],
                                                message_array[3],
                                                message_array[4:])
                    await message.channel.send(
                        embed=embeds.simple_embed(res[0], res[1]))
                    if res[0]:
                        await message.add_reaction("✅")
                if message_command == "$accept":
                    res = database.fulfill_trade(message_array[1],
                                                 message_array[2],
                                                 message.author, message.guild)
                    await message.channel.send(
                        embed=embeds.simple_embed(res[0], res[1]))
                if message_command == "$quiz":
                    res = database.get_question(message.author, message.guild)
                    await message.channel.send(
                        embed=embeds.simple_embed(res[0], res[1]))
                if message_command == "$shop":
                    if not message.author.guild_permissions.administrator:
                        await message.channel.send(embed=embeds.simple_embed(
                            False,
                            "you must be an administrator to configure the shop"
                        ))
                        return
                    res = database.insert_trade(message, message.author,
                                                message.guild, "admins",
                                                message_array[1],
                                                message_array[2],
                                                message_array[3:])
                    await message.channel.send(
                        embed=embeds.simple_embed(res[0], res[1]))
                    if res[0]:
                        await message.add_reaction("✅")
                if message_command == "$work":
                    res = database.work(message.author, message.guild)
                    await message.channel.send(embed=embeds.simple_embed(*res))
                if message_command == "$work-conditional":
                    if not message.author.guild_permissions.administrator:
                        await message.channel.send(embed=embeds.simple_embed(
                            False,
                            "you must be an administrator to configure conditional work rewards"
                        ))
                        return
                    res = database.work_conditions(message.guild,
                                                   message_array[1],
                                                   message_array[2],
                                                   message_array[3:])
                    await message.channel.send(embed=embeds.simple_embed(*res))
            else:
                await message.channel.send(embed=embeds.simple_embed(
                    False,
                    "not valid command. If you want a list of all commands, type '$help' "
                ))