Ejemplo n.º 1
0
def check_all_list_stakes(message):
    wa_group_id = message.conversation.split("@")[0]
    wa_ph_number = message.who.split("@")[0]

    payload = {"wa_group_id": wa_group_id, "wa_ph_number": wa_ph_number}
    check_all_list_stakes_post = requests.post(API_LIST_STAKES, data=payload)
    check_all_list_stakes_data = check_all_list_stakes_post.json()

    if 'error' in check_all_list_stakes_data:
        error_repsonse_handler(check_all_list_stakes_data, message)
        return

    if 'success' in check_all_list_stakes_data:
        player_lists = check_all_list_stakes_data['success']['response']
        # player_stakes_rows= [["Command", "Name Stakes"]]
        # for player in player_lists:
        #     player_stakes_rows.append([player["command_list_stakes"],player["name_list_stakes"]])
        # table = texttable.Texttable()
        # table.add_rows(player_stakes_rows)
        # mac.send_message(table.draw(), message.conversation)
        player_stakes_rows = [["----------------------", ""]]
        player_stakes_rows.append([["Command", "Name Stakes"]])
        player_stakes_rows.append(["----------------------"])
        for player in player_lists:
            player_stakes_rows.append(
                [player["command_list_stakes"], player["name_list_stakes"]])
        player_stakes_rows.append(["----------------------"])
        mac.send_message(tabulate(player_stakes_rows, tablefmt="plain"),
                         message.conversation)
        #print(tabulate(player_stakes_rows))
        mac.send_message(tabulate(player_stakes_rows), message.conversation)
        return
Ejemplo n.º 2
0
def peruutus(message):
    who_name = message.who_name

    if who_name in getNames("sjoki"):
        removeName("sjoki", who_name)
        answer = "*{}*, ilmoittautumisesi on peruutettu.".format(who_name)
        mac.send_message(answer, message.conversation)

    elif who_name in getNames("prisma"):
        removeName("prisma", who_name)
        answer = "*{}*, ilmoittautumisesi on peruutettu.".format(who_name)
        mac.send_message(answer, message.conversation)

    elif who_name in getNames("kovero"):
        removeName("kovero", who_name)
        answer = "*{}*, ilmoittautumisesi on peruutettu.".format(who_name)
        mac.send_message(answer, message.conversation)

    elif who_name in getNames("auto"):
        removeName("auto", who_name)
        answer = "*{}*, ilmoittautumisesi on peruutettu.".format(who_name)
        mac.send_message(answer, message.conversation)

    else:
        answer = "*{}*, et ole vielä ilmoittautunut.".format(who_name)
        mac.send_message(answer, message.conversation)
Ejemplo n.º 3
0
def end_game(message):
    group_id = message.conversation.split("@")[0]
    user_number = message.who.split("@")[0]
    payload = {'wa_group_id': group_id, 'wa_ph_number': user_number}
    end_game_post = requests.post(
        "http://{}/trivia/api/whatsappbot/end_game".format(BASE_IP),
        data=payload)
    end_game_data = end_game_post.json()
    if not end_game_data or not end_game_data['message']:
        mac.send_message("I failed to end the game session, no message field",
                         message.conversation)
        return
    if not helper.isResponseSuccess(end_game_post.status_code):
        mac.send_message(
            'I failed to end the game, here what the server guy say: \n {}'.
            format(end_game_data['message']), message.conversation)
        print(end_game_post.text)
        return
    winner_lists = end_game_data["winner_list"]
    if len(winner_lists) == 0:
        mac.send_message("There isn't any winner in this game",
                         message.conversation)
    winner_rows = [["phone_number", "stakes", "profit"]]
    for winner in winner_lists:
        winner_rows.append(
            [winner["phone_number"], winner["stake"], winner["profit"]])
    table = texttable.Texttable()
    table.add_rows(winner_rows)
    print("winner")
    print(table.draw())
    mac.send_message(
        u'🏁 We have reach the end of the game 🏁 \n '
        u'🥁🥁🥁 Now I\'ll announce the winners! 🥁🥁🥁', message.conversation)
    mac.send_message(table.draw(), message.conversation)
Ejemplo n.º 4
0
def handle(message):
    index = message.who.index('@')
    who_number = message.who[:index]
    who_name = message.who_name

    session_id = who_number
    request = apiai.ApiAI(
        client_token).text_request()  # Токен API к Dialogflow
    request.lang = 'ru'  # На каком языке будет послан запрос
    request.session_id = session_id  # ID Сессии диалога (нужно, чтобы потом учить бота)
    request.query = message.text  # Посылаем запрос к ИИ с сообщением от юзера
    responseJson = json.loads(request.getresponse().read().decode('utf-8'))
    response = responseJson['result']['fulfillment']['messages'][0]['speech']
    mac.send_message(response, message.conversation)

    if message.text == "@":
        link_whatsapp = "https://wa.me/" + who_number
        text_msg = "Заявка из Whatsapp\nИмя: " + who_name + "\nНомер: " + who_number + "\nНачать чат: " + link_whatsapp

        for contact in config.contacts.keys():
            mac.send_message_to(text_msg, contact)

    seq = difflib.SequenceMatcher(a=client_word.lower(),
                                  b=message.text.lower())

    if seq.ratio() >= 0.5:
        link_whatsapp = "https://wa.me/" + who_number
        text_msg = "Начат чат с ботом\nИмя: " + who_name + "\nНомер: " + who_number + "\nНачать чат: " + link_whatsapp

        for contact in config.contacts.keys():
            mac.send_message_to(text_msg, contact)
Ejemplo n.º 5
0
def create_group(message):
    params = message.predicate
    print(params)
    if len(params) == 0:
        ambigous("You need to initiate group name", message)
        return
    if len(params) > 24:
        ambigous(
            "Group Name maximal character is 24. Yours is {}".format(
                len(params)), message)
        return
    group_name = params
    ph_number = message.who.split("@")[0]
    group_id = '{}_{}'.format(ph_number, group_name)
    payload = {"wa_group_name": group_name, "wa_ph_number": ph_number}
    group_check_post = requests.post(
        'http://{}/api/whatsappbot/create_group'.format(BASE_IP), data=payload)
    group_check_data = group_check_post.json()
    is_successful = helper.isResponseSuccess(group_check_post.status_code)
    if not is_successful:
        mac.send_message(
            'Sorry you are failed to create group. the error is: \n',
            message.conversation)
        mac.send_message(group_check_data['message'], message.conversation)
        return

    mac.create_group(ph_number,
                     group_name,
                     message.conversation,
                     callback=update_group)
Ejemplo n.º 6
0
def check_credit_member(message):
    wa_group_id = message.conversation.split("@")[0]
    wa_ph_number = message.who.split("@")[0]

    payload = {"wa_group_id": wa_group_id, "wa_ph_number": wa_ph_number}
    check_credit_member_post = requests.post(API_CHECK_CREDIT_MEMBER,
                                             data=payload)
    check_credit_member_data = check_credit_member_post.json()

    if 'error' in check_credit_member_data:
        error_repsonse_handler(check_credit_member_data, message)
        return

    if 'success' in check_credit_member_data:
        player_lists = check_credit_member_data['success']['response']
        check_credit_member_rows = [[
            "Name Groups", "Start Sessions", "Credit Register", "End Sessions"
        ]]
        for player in player_lists:
            check_credit_member_rows.append([
                player["name_groups"], player["start_sessions"],
                str(player["credit_register_members"]), player["end_sessions"]
            ])
        table = texttable.Texttable()
        table.add_rows(check_credit_member_rows)
        mac.send_message(table.draw(), message.who)
        return
Ejemplo n.º 7
0
def register_user(message):
    user_number = message.who.split("@")[0]
    group_id = message.conversation.split("@")[0]
    if (not user_number or not group_id):
        message.send_message("Error when registering user",
                             message.conversation)
        return
    payload = {'wa_group_id': group_id, 'wa_ph_number': user_number}
    register_post = requests.post(
        'http://{}/trivia/api/whatsappbot/register_group'.format(BASE_IP),
        data=payload)
    register_data = register_post.json()
    is_successful = helper.isResponseSuccess(register_post.status_code)
    if not register_data:
        mac.send_message('Sorry I Failed connecting to server',
                         message.conversation)
        return
    if not is_successful:
        mac.send_message(
            'Sorry Failed to register You to server, your error is \n ',
            message.conversation)
        mac.send_message(register_data['message'], message.conversation)
        print(register_post.text)
        return
    mac.send_message("Great !", message.conversation)
    mac.send_message(register_data['message'], message.conversation)
    print(register_post.text)
Ejemplo n.º 8
0
def handle(message):
    if message.command == "hi":
        hi(message)
    elif message.command == "help": 
        help(message)
    elif message.command.lower() == "hola":
        mac.send_message("Tu eres caga", message.conversation)
Ejemplo n.º 9
0
def end_game(message):
    wa_ph_number = message.who.split("@")[0]
    wa_group_name = message.predicate

    groupname_payload = {
        'wa_group_name': wa_group_name,
        "wa_ph_number": wa_ph_number
    }
    group_id_post = requests.post(API_GET_GROUP_INFO, data=groupname_payload)
    group_id_data = group_id_post.json()

    print(group_id_data)

    if 'success' not in group_id_data:
        return

    mac.send_message(
        "Game will End in 10 seconds",
        group_id_data['success']['response']['wa_group_id'] + "@g.us")
    t = threading.Thread(target=end_api_thread,
                         args=(
                             message,
                             wa_group_name,
                             wa_ph_number,
                         ))
    t.start()
Ejemplo n.º 10
0
def check_all_stakes_in_game(message):
    wa_group_id = message.conversation.split("@")[0]
    wa_ph_number = message.who.split("@")[0]

    payload = {"wa_group_id": wa_group_id, "wa_ph_number": wa_ph_number}
    check_all_stakes_in_game_post = requests.post(API_CHECK_STAKES_MEMBERS,
                                                  data=payload)
    check_all_stakes_in_game_data = check_all_stakes_in_game_post.json()

    if 'error' in check_all_stakes_in_game_data:
        error_repsonse_handler(check_all_stakes_in_game_data, message)
        return

    if 'success' in check_all_stakes_in_game_data:
        player_lists = check_all_stakes_in_game_data['success']['response'][
            'check_stakes_members']
        # player_stakes_rows= [["phone_number", "stakes", "value"]]
        # for player in player_lists:
        #     player_stakes_rows.append([player["phone_number"], player["name_list_stakes"], player["value_stakes"]])
        # table = texttable.Texttable()
        # table.add_rows(player_stakes_rows)
        # mac.send_message(table.draw(), message.conversation)
        player_stakes_rows = [["----------------------", "", ""]]
        player_stakes_rows.append(["phone_number", "stakes", "value"])
        player_stakes_rows.append(["----------------------"])
        for player in player_lists:
            player_stakes_rows.append([
                player["phone_number"], player["name_list_stakes"],
                player["value_stakes"]
            ])
        player_stakes_rows.append(["----------------------"])
        mac.send_message(tabulate(player_stakes_rows, tablefmt="plain"),
                         message.conversation)
        return
Ejemplo n.º 11
0
def lista(message):

    sjokiList = getNames("sjoki")
    prismaList = getNames("prisma")
    koveroList = getNames("kovero")
    carList = getNames("auto")

    total = len(sjokiList) + len(prismaList) + len(koveroList) + len(carList)
    totalSjoki = len(sjokiList)
    totalPrisma = len(prismaList)
    totalKovero = len(koveroList)
    totalCars = len(carList)

    sjokiString = "\n ".join(sjokiList)
    prismaString = "\n ".join(prismaList)
    koveroString = "\n ".join(koveroList)
    carString = "\n ".join(carList)
    answer = """*Yhteensä tulossa: {}*
    \n*Kivistön S-Market: {}*
    {}
    \n*Prisman ramppi: {}*
    {}
    \n*Koveron Shell: {}*
    {}
    \n*Autolliset: {}*
    {}""".format(total, totalSjoki, sjokiString, totalPrisma, prismaString,
                 totalKovero, koveroString, totalCars, carString)
    mac.send_message(answer, message.conversation)
Ejemplo n.º 12
0
def create_sessions(message):
    wa_ph_number = message.who.split("@")[0]
    params = message.predicate.split(" ")

    if len(params) < 3:
        mac.send_message(helper.INVALID_MESSAGE, message.conversation)
        return

    wa_group_name = ' '.join(params[:-2])
    credit_member = params[-2]
    duration = params[-1]

    if not wa_group_name:
        mac.send_message(helper.INVALID_MESSAGE, message.who)
        return

    if not duration:
        duration = "null"

    payload = {
        "wa_group_name": wa_group_name,
        "wa_ph_number": wa_ph_number,
        'credit_member': credit_member,
        'day_duration': duration
    }
    _post = requests.post(API_CREATE_SESSIONS, data=payload)
    _data = _post.json()

    repsonse_handler(_data, message)
Ejemplo n.º 13
0
def start_game(message, is_auto=False):
    wa_ph_number = message.who.split("@")[0]
    params = message.predicate.split(" ")
    wa_group_name = ' '.join(params[:-1])

    if not wa_group_name:
        wa_group_name = params[0]
        duration = '10'
    else:
        duration = params[-1]

    payload = {
        "wa_group_name": wa_group_name,
        "wa_ph_number": wa_ph_number,
        'minutes_duration': duration
    }
    print(payload)
    _post = requests.post(API_START_GAME, data=payload)
    _data = _post.json()

    if 'error' in _data:
        error_repsonse_handler(_data, message)
        # indicate not success running
        return 0

    if 'successgroup' in _data and not is_auto:
        mac.send_message(_data['successgroup']['response'],
                         _data['successgroup']['value'] + "@g.us")

    if 'successprivate' in _data:
        mac.send_message(_data['successprivate']['response'],
                         message.conversation)
        # indicate success running
        return 1
Ejemplo n.º 14
0
def help(message):
    answer = "*Bot called mac* \nWhatsapp framework made in Python"+
    "\n*Version:* 1.0.0 \n*Status:* Beta "+
    "\nhttps://github.com/danielcardeenas/whatsapp-framework"+
    "\nhttps://github.com/tgalal/yowsup"+
    "\nhttps://github.com/devalexanderdaza/yowsapp-framework"
    mac.send_message(answer, message.conversation)
Ejemplo n.º 15
0
    def get_info(result):
        group_name = result.subject
        payload = {'wa_group_id': group_id, 'wa_ph_number': ph_number}
        register_post = requests.post(
            'http://{}/api/whatsappbot/register_group'.format(BASE_IP),
            data=payload)
        register_data = register_post.json()
        is_successful = helper.isResponseSuccess(register_post.status_code)
        if not register_data:
            mac.send_message('Sorry I Failed connecting to server',
                             message.conversation)
            return
        if not is_successful:
            #mac.send_message('Sorry you are already registered in {} Group \n '.format(group_name), message.who)
            mac.send_message(register_data['message'], message.who)
            print(register_post.text)
            return

        mac.send_message(
            "{} Success join the game! Good luck!".format(user_phone_star),
            message.conversation)
        mac.send_message(register_data['message'], message.who)
        if not register_data['init_point']:
            return
        mac.send_message(
            "Congratz! You successfully join {} Group. Your initial balance is {}  "
            .format(group_name, register_data['init_point']), message.who)
Ejemplo n.º 16
0
def handle_command(message):
    actions = [
        '😛☁️🔫 CLICK', '😛☁️🔫 CLICK', '😛☁️🔫 CLICK', '😛☁️🔫 CLICK', '😛☁️🔫 CLICK',
        '😵💥🔫 BAAANG!'
    ]
    response = random.choice(actions)
    mac.send_message(response, message.conversation)
Ejemplo n.º 17
0
def start_game(message):
    ph_number = message.who.split("@")[0]
    params = message.predicate.split(" ")
    if len(params) != 1:
        mac.send_message(
            'Sorry there is something wrong in your stake command!')
        return
    (group_name) = params
    mac.send_message(
        u"📡 Ok, let's play ! But first, wait me to contact the server guy",
        message.conversation)
    payload = {'wa_group_name': group_name, 'wa_ph_number': ph_number}
    start_game_post = requests.post(
        "http://{}/api/whatsappbot/start".format(BASE_IP), data=payload)
    start_game_data = start_game_post.json()
    if not start_game_data or not start_game_data['message']:
        mac.send_message(
            "I failed to start the game session, no message field",
            message.conversation)
        return
    if not helper.isResponseSuccess(start_game_post.status_code):
        mac.send_message(
            'I failed to start the game, here some error \n {}'.format(
                start_game_data['message']), message.conversation)
        return
    mac.send_message(GAME_STARTED, message.who)
Ejemplo n.º 18
0
def check_group(message, callback=None):
    """
    #TODO [UNUSED]
    Check whether the user are the admin of the group
    it needed for some command that can only be call by admin
    :param message:
    :param callback:
    :return:
    """
    is_in_group = helper.conversationIsGroup(message)
    if not is_in_group:
        mac.send_message(
            "Hello, I can't do it from here, please do it from your group.",
            message.conversation)
        return

    def callback_check_group(isAdmin):
        if not callback:
            return
        callback(isAdmin)
        print(isAdmin)

    mac.get_group_info(message.conversation,
                       message.who,
                       callback=callback_check_group)
Ejemplo n.º 19
0
    def handle_command(self, message):
        args = [x.strip() for x in message.predicate.split(',')]
        # Case: Invalid arguments
        if len(args) <= 0:
            mac.send_message("_Invalid arguments for poll_",
                             message.conversation)

        # Case: Valid arguments
        elif len(args) >= 1:
            # Case: finish poll
            if args[0] == "finish":
                WAPoll.finish_my_poll(message.who, message.conversation)
                return
            # Case: create poll (default vote identifier)
            elif len(args) == 1:
                title = args[0]
                poll = WAPoll(message.conversation, message.who, title)
                poll.send()

            # Case: create poll (vote identifier specified)
            elif len(args) >= 2:
                title = args[0]
                identifier = args[1]
                poll = WAPoll(message.conversation, message.who, title,
                              identifier)
                poll.send()
Ejemplo n.º 20
0
def success_repsonse_handler(data, message):
    if data['success']['target'] != 'private':
        mac.send_message(data['success']['response'],
                         data['success']['value'] + "@g.us")
        return
    else:
        mac.send_message(data['success']['response'], message.who)
        return
Ejemplo n.º 21
0
 def finish_my_poll(self, creator, conversation):
     poll = poll_from_user_conversation(creator, conversation)
     if poll:
         message = "*" + poll.title + ":*\n"
         message += "Total: " + str(len(poll.voters))
         message += poll.voters_print()
         mac.send_message(message, poll.conversation)
         active_polls.remove(poll)
Ejemplo n.º 22
0
def finish_my_poll(self, creator, conversation):
    poll = poll_from_user_conversation(creator, conversation)
    if poll:
        message = "*" + poll.title + ":*\n"
        message += "Total: " + str(len(poll.voters))
        message += poll.voters_string()
        mac.send_message(self, message, poll.conversation)
        poll.destroy()
Ejemplo n.º 23
0
def uusilista(message):
    emptyList("sjoki")
    emptyList("prisma")
    emptyList("kovero")
    emptyList("auto")

    answer = "*Lista tyhjennetty, uudet ilmoittautumiset voi alkaa.*"
    mac.send_message(answer, message.conversation)
Ejemplo n.º 24
0
def audio(message):
    print("nombre audio ." + message.conversation[:11] + ".")
    print("link es ." + message.command[5:] + ".")
    os.system(
        "youtube-dl -f bestaudio --extract-audio --audio-format mp3 -o " +
        message.conversation[:11] + ".mp3 " + message.command[5:])
    mac.send_message("Ya tengo el audio, te lo mando", message.conversation)
    mac.send_audio(message.conversation[:11] + ".mp3", message.conversation)
Ejemplo n.º 25
0
 def make_title(self, predicate):
     args = [x.strip() for x in predicate.split(',')]
     # If no args
     if len(args) <= 0:
         mac.send_message(self.instance, "_Argumentos invalidos_",
                          self.conversation)
         return
     else:
         return args[0]
Ejemplo n.º 26
0
def video(message):
    os.system(
        "youtube-dl -f \'bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4\' -o " +
        message.conversation[:11] + " " + message.command[5:])
    mac.send_message("Ya lo baje... Lo envio ahorita", message.conversation)
    print(Back.BLUE + "EL NOMBRE DEL VIDEO ES... " +
          message.conversation[:11] + ".mp4")
    print(Style.RESET_ALL)
    mac.send_video(message.conversation[:11] + ".mp4", message.conversation)
Ejemplo n.º 27
0
    def send_yesno(self):
        # Converts gif to mp4 and sends as video
        # mac.send_video(self.instance, self.conversation, gif_to_video(self.image_path, self.caption), self.caption)

        # Sends gif as image
        #mac.send_image(self.instance, self.conversation, self.image_path, self.caption)

        # Sends just the answer
        mac.send_message("*" + self.caption + "*", self.conversation)
Ejemplo n.º 28
0
    def initialize_game(self):
        if chat_has_game(self.conversation):
            mac.send_message("There is already a game going on",
                             self.conversation)
            return

        answer = "*Texas Hold'em*" + "\n" + self.join_identifier + " to join"
        mac.send_message(answer, self.conversation)
        active_games.append(self)
Ejemplo n.º 29
0
    def send_poll(self):
        answer = "*" + self.title + "*"
        number = 1
        for candidate in self.candidates:
            answer += "\n"
            answer += get_unicode_number(number)
            answer += " " + candidate
            number += 1

        mac.send_message(self.instance, answer, self.conversation)
Ejemplo n.º 30
0
def handle_elo(message):
    args = [x.strip() for x in message.predicate.split(',')]

    if args[0] == "query":
        query = message.predicate.split(', ', 1)[-1]
        results = elo.query(query)
        mac.send_message(results, message.conversation)
    else:
        ranks = elo.ranks(message.predicate)
        mac.send_message(ranks, message.conversation)