示例#1
0
    def test_get_configuration(self, get):
        config = self.api.get_configuration()

        get.assert_called_once_with('https://api.kik.com/v1/config',
                                    timeout=60,
                                    auth=('mybotusername', 'mybotapikey'))

        self.assertIsInstance(config, Configuration)
        self.assertEqual(config.webhook, 'https://example.com/incoming')
        self.assertEqual(config.features, {'manuallySendReadReceipts': True})
        self.assertIsInstance(config.static_keyboard,
                              SuggestedResponseKeyboard)
        self.assertEqual(
            config.static_keyboard,
            SuggestedResponseKeyboard(responses=[TextResponse('foo')]))
 def test_text_message_with_all_keyboard_types(self):
     message = TextMessage(
         body='Some text',
         to='aleem',
         id='8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0',
         keyboards=[
             SuggestedResponseKeyboard(
                 hidden=True,
                 responses=[
                     PictureResponse('http://foo.bar', {'some': 'data'}),
                     FriendPickerResponse('Foo', 7, 16, ['bar', 'dar']),
                     TextResponse('Bar')
                 ])
         ]).to_json()
     self.assertEqual(
         message, {
             'type':
             'text',
             'to':
             'aleem',
             'body':
             'Some text',
             'id':
             '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0',
             'keyboards': [{
                 'type':
                 'suggested',
                 'hidden':
                 True,
                 'responses': [{
                     'type': 'picture',
                     'picUrl': 'http://foo.bar',
                     'metadata': {
                         'some': 'data'
                     }
                 }, {
                     'type': 'friend-picker',
                     'body': 'Foo',
                     'min': 7,
                     'max': 16,
                     'preselected': ['bar', 'dar']
                 }, {
                     'type': 'text',
                     'body': 'Bar'
                 }]
             }]
         })
示例#3
0
def sendKikMessages(chat_id,from_user,msgs,suggested_responses=[],msg_type=None):
        
    send_these = []
    for msg in msgs:
        send_these.append(abstract_kik_message(
            to=from_user,
            chat_id=chat_id,
            content=msg,
            msg_type=msg_type
            ))
    if msg_type == 'text' and suggested_responses:
        text_resonses = [TextResponse(r) for r in suggested_responses]

        send_these[-1].keyboards.append(
            SuggestedResponseKeyboard(
            responses=text_resonses
            )
        )
    kik.send_messages(send_these)
    def test_to_json(self):
        config = Configuration(webhook='https://mybot.com/incoming',
                               features={'manuallySendReadReceipts': True},
                               static_keyboard=SuggestedResponseKeyboard(
                                   responses=[TextResponse('foo')]))

        self.assertEqual(
            config.to_json(), {
                'webhook': 'https://mybot.com/incoming',
                'features': {
                    'manuallySendReadReceipts': True
                },
                'staticKeyboard': {
                    'type': 'suggested',
                    'responses': [{
                        'type': 'text',
                        'body': 'foo'
                    }]
                }
            })
 def test_from_json(self):
     config = Configuration.from_json({
         'webhook': 'https://mybot.com/incoming',
         'features': {
             'manuallySendReadReceipts': True
         },
         'staticKeyboard': {
             'type': 'suggested',
             'responses': [{
                 'type': 'text',
                 'body': 'foo'
             }]
         }
     })
     self.assertEqual(config.webhook, 'https://mybot.com/incoming')
     self.assertEqual(config.features, {'manuallySendReadReceipts': True})
     self.assertIsInstance(config.static_keyboard,
                           SuggestedResponseKeyboard)
     self.assertEqual(
         config.static_keyboard,
         SuggestedResponseKeyboard(responses=[TextResponse('foo')]))
示例#6
0
    def test_picture_message_complete(self):
        message = PictureMessage(
            pic_url='http://foo.bar/image',
            to='aleem',
            mention='anotherbot',
            chat_id=
            'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
            keyboards=[
                SuggestedResponseKeyboard(hidden=True,
                                          responses=[TextResponse('Foo')])
            ],
            attribution=CustomAttribution(name='Foobar'),
            delay=100).to_json()

        self.assertEqual(
            message, {
                'type':
                'picture',
                'to':
                'aleem',
                'mention':
                'anotherbot',
                'chatId':
                'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
                'picUrl':
                'http://foo.bar/image',
                'keyboards': [{
                    'type': 'suggested',
                    'hidden': True,
                    'responses': [{
                        'type': 'text',
                        'body': 'Foo'
                    }]
                }],
                'attribution': {
                    'name': 'Foobar'
                },
                'delay':
                100
            })
示例#7
0
def SetKeyboard(user):
    if user in adminlist:
        Keyboard = [
            SuggestedResponseKeyboard(to=user,
                                      hidden=True,
                                      responses=[
                                          TextResponse('BENCHMARK ANALYSIS'),
                                          TextResponse('PROBE ANALYSIS'),
                                          TextResponse('INACTIVE ANALYSIS'),
                                          TextResponse('RESET BENCHMARK')
                                      ])
        ]
    else:
        Keyboard = [
            SuggestedResponseKeyboard(to=user,
                                      hidden=True,
                                      responses=[
                                          TextResponse('BENCHMARK ANALYSIS'),
                                          TextResponse('PROBE ANALYSIS'),
                                          TextResponse('INACTIVE ANALYSIS')
                                      ])
        ]
    return Keyboard
示例#8
0
def incoming():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        if isinstance(message, TextMessage):
            if message.body == 'Hi':
                body = 'What\'s the motive?'
                kik.send_messages([
                        VideoMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            video_url=getGiphy.getGiphy('Hello'),
                            autoplay=True,
                            loop=True,
                        ),
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=body,
                            keyboards=[
                                SuggestedResponseKeyboard(
                                    responses=[
                                        TextResponse('Staying in'),
                                        TextResponse('Going out'),
                                    ]
                                )
                            ]
                        )
                    ])
                message = TextResponse

        if isinstance(message, TextMessage):
            if message.body == 'Going out':
                body = 'What day though?'
                kik.send_messages([
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=body,
                            keyboards=[
                                SuggestedResponseKeyboard(
                                    responses=[
                                        TextResponse('Sunday'),
                                        TextResponse('Monday'),
                                        TextResponse('Tuesday'),
                                        TextResponse('Wednesday'),
                                        TextResponse('Thursday'),
                                        TextResponse('Friday'),
                                        TextResponse('Saturday'),
                                    ]
                                )
                            ]
                        )
                    ])
                message = TextResponse

        if isinstance(message, TextMessage):
            if message.body == 'Friday':
                body = ('This is what\'s gucci tonight:\nChainsaw: $3 shots\nEthel\'s: $8 for 1.5lbs wings')
                kik.send_messages([
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=body,
                            keyboards=[
                                SuggestedResponseKeyboard(
                                    responses=[
                                        TextResponse('Chainsaw'),
                                        TextResponse('Ethel\'s'),
                                    ]
                                )
                            ]
                        )
                    ])
                message = TextResponse

        if isinstance(message, TextMessage):
            if message.body == 'Chainsaw':
                kik.send_messages([
                        PictureMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            pic_url='http://thecord.ca/wp-content/uploads/2014/09/Chainsaw-Heather-Davidson.jpg',
                        ),
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body='Address: 28 King St N,\n Waterloo, ON N2J 2W6\nPhone:(519) 954-8660'
                        )
                ])

        return Response(status=200)
示例#9
0
    def incoming(self):
        """Handle incoming messages to the bot. All requests are authenticated using the signature in
        the 'X-Kik-Signature' header, which is built using the bot's api key (set in main() below).
        :return: Response
        """
        # verify that this is a valid request
        if not self.kik_api.verify_signature(
                request.headers.get("X-Kik-Signature"), request.get_data()):
            return Response(status=403)

        messages = messages_from_json(request.json["messages"])

        response_messages = []

        for message in messages:
            user = self.kik_api.get_user(message.from_user)
            # Check if its the user's first message. Start Chatting messages are sent only once.
            if isinstance(message, StartChattingMessage):

                response_messages.append(
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Hey {}, how are you?".format(user.first_name),
                        # keyboards are a great way to provide a menu of options for a user to respond with!
                        keyboards=[
                            SuggestedResponseKeyboard(responses=[
                                TextResponse("Good"),
                                TextResponse("Bad")
                            ])
                        ]))

            # Check if the user has sent a text message.
            elif isinstance(message, TextMessage):
                user = self.kik_api.get_user(message.from_user)
                message_body = message.body.lower()

                if message_body.split()[0] in ["hi", "hello"]:
                    response_messages.append(
                        TextMessage(to=message.from_user,
                                    chat_id=message.chat_id,
                                    body="Hey {}, how are you?".format(
                                        user.first_name),
                                    keyboards=[
                                        SuggestedResponseKeyboard(responses=[
                                            TextResponse("Good"),
                                            TextResponse("Bad")
                                        ])
                                    ]))

                elif message_body == "good":
                    response_messages.append(
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body="That's Great! :) Wanna see your profile pic?",
                            keyboards=[
                                SuggestedResponseKeyboard(responses=[
                                    TextResponse("Sure! I'd love to!"),
                                    TextResponse("No Thanks")
                                ])
                            ]))

                elif message_body == "bad":
                    response_messages.append(
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body="Oh No! :( Wanna see your profile pic?",
                            keyboards=[
                                SuggestedResponseKeyboard(responses=[
                                    TextResponse("Yep! I Sure Do!"),
                                    TextResponse("No Thank You")
                                ])
                            ]))

                elif message_body in ["yep! i sure do!", "sure! i'd love to!"]:

                    # Send the user a response along with their profile picture (function definition is below)
                    response_messages += self.profile_pic_check_messages(
                        user, message)

                elif message_body in ["no thanks", "no thank you"]:
                    response_messages.append(
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=
                            "Ok, {}. Chat with me again if you change your mind."
                            .format(user.first_name)))
                else:
                    response_messages.append(
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=
                            "Sorry {}, I didn't quite understand that. How are you?"
                            .format(user.first_name),
                            keyboards=[
                                SuggestedResponseKeyboard(responses=[
                                    TextResponse("Good"),
                                    TextResponse("Bad")
                                ])
                            ]))

            # If its not a text message, give them another chance to use the suggested responses
            else:

                response_messages.append(
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body=
                        "Sorry, I didn't quite understand that. How are you, {}?"
                        .format(user.first_name),
                        keyboards=[
                            SuggestedResponseKeyboard(responses=[
                                TextResponse("Good"),
                                TextResponse("Bad")
                            ])
                        ]))

            # We're sending a batch of messages. We can send up to 25 messages at a time (with a limit of
            # 5 messages per user).

            self.kik_api.send_messages(response_messages)

        return Response(status=200)
示例#10
0
resetUser = ""
MessageHandler = MessageBuilder()
app = Flask(__name__)
kik = KikApi('BOTID', 'API_KEY')

#-------------------------KIK BOT CONFIG------------------------------------------------------

afeatures = {
    "manuallySendReadReceipts": False,
    "receiveReadReceipts": True,
    "receiveDeliveryReceipts": False,
    "receiveIsTyping": False
}

staticKeyboard = SuggestedResponseKeyboard(responses=[
    TextResponse('BENCHMARK ANALYSIS'),
    TextResponse('PROBE ANALYSIS'),
    TextResponse('INACTIVE ANALYSIS'),
    TextResponse('HELP')
])

kik.set_configuration(
    Configuration(webhook='WEBHOOK',
                  features=afeatures,
                  static_keyboard=staticKeyboard))

banlist = ""

#list of users to have privadged access to reset benchmark
adminlist = {}
示例#11
0
def buyThis(chat_id, context):
    """
    User has selected a picture she likes, and would like to visit the
    store webpage
    """
    from_user = context['from_user']
    prev_context = retrieveContext(chat_id, from_user)
    if 'image_query_result' not in prev_context and 'text_query_result' not in prev_context:
        say(chat_id, context,
            canned_responses.error_message() + 'query results issue')
    elif 'selected_outfit' not in prev_context:
        say(chat_id, context,
            canned_responses.error_message() + 'selection issuse')
    else:
        i = int(prev_context['selected_outfit']) - 1
        if prev_context['search_type'] == 'image':
            i = int(
                prev_context['image_query_result_index']) - SHOW_THIS_MANY + i
            link = prev_context['image_query_result']['images'][i]['pageUrl']
            title = prev_context['image_query_result']['images'][i]['title']
            img_url = prev_context['image_query_result']['images'][i][
                'imageUrl']
            # using a text message to send fitroom results because Kik breaks out links by putting a trailing "/"
            link_message = TextMessage(to=from_user,
                                       chat_id=chat_id,
                                       body=link)


#            link_message = LinkMessage(to=from_user,chat_id=chat_id,url=link,title=title)
        elif prev_context['search_type'] == 'text':

            i = int(
                prev_context['text_query_result_index']) - SHOW_THIS_MANY + i
            img_url = prev_context['text_query_result']['products'][i][
                'image']['sizes']['IPhone']['url']
            link = prev_context['text_query_result']['products'][i]['clickUrl']
            title = prev_context['text_query_result']['products'][i][
                'brandedName']
            link_message = LinkMessage(to=from_user,
                                       chat_id=chat_id,
                                       url=link,
                                       title=title)
        if context['platform'] == 'KIK':
            here = TextMessage(to=from_user,
                               chat_id=chat_id,
                               body="Here ya go:")
            tip = TextMessage(
                to=from_user,
                chat_id=chat_id,
                body=
                "Remember you can search again anytime by sending me a pic ;)")
            tip.keyboards.append(
                SuggestedResponseKeyboard(responses=[
                    TextResponse('See more results'),
                    TextResponse('Search with this pic'),
                    TextResponse('New search')
                ]))
            kik.send_messages([here, link_message, tip])
        elif context['platform'] == 'FB':
            dispatchMessage(context,
                            'link',
                            chat_id,
                            from_user, [link],
                            suggested_responses=[title],
                            extras=[img_url])
示例#12
0
 def register_group_sr(self, name, sr_names):
     self.grouped_srs[name] = [TextResponse(sr) for sr in sr_names]
示例#13
0
文件: main.py 项目: tcbuddy/home-ai
from workers.voice import VoiceProcessor
from workers.web_server import get_worker as generate_web_worker

logging.getLogger().setLevel(logging.DEBUG)

# Check if super user (if yes, GTFO)
if os.geteuid() == 0:
    logging.error('This is not meant to be run as root')
    sys.exit(1)

# Outputs
kik = KikApi(config.KIK_BOT_USERNAME, config.KIK_BOT_API_KEY)
bot_output = KikBotOutput(
    kik=kik,
    default_keyboard=SuggestedResponseKeyboard(responses=[
        TextResponse('Check Running'),
        TextResponse('Tunnel URL'),
        TextResponse('Alarm Clock'),
        TextResponse('Picture'),
        TextResponse('Quote'),
        TextResponse('Headlines'),
        TextResponse('Weather'),
        TextResponse('Calendar'),
        TextResponse('Kill'),
        TextResponse('Restart')
    ]))

speech_output = SpeechOutput(speaker_mac_address=config.SPEAKER_MAC_ADDRESS,
                             sink_name=config.SINK_NAME)

static_folder = '{}/{}'.format(os.path.dirname(os.path.abspath(__file__)),
示例#14
0
    def new_keyboard(self, *args):
        if not len(args):
            return False

        return SuggestedResponseKeyboard(
            responses=[TextResponse(x) for x in args])
示例#15
0
 def make_keyboard(self):
     keyboard = SuggestedResponseKeyboard(
         hidden=False,
         responses=[TextResponse(x) for x in self.keyboard_entries])
     return keyboard
示例#16
0
    def incoming(self):
        """Handle incoming messages to the bot. All requests are authenticated using the signature in
        the 'X-Kik-Signature' header, which is built using the bot's api key (set in main() below).
        :return: Response
        """
        # verify that this is a valid request
        if not self.kik_api.verify_signature(
                request.headers.get("X-Kik-Signature"), request.get_data()):
            return Response(status=403)

        messages = messages_from_json(request.json["messages"])

        response_messages = []

        for message in messages:
            user = self.kik_api.get_user(message.from_user)
            # Check if its the user's first message. Start Chatting messages are sent only once.
            if isinstance(message, StartChattingMessage):

                response_messages.append(
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="haloo {}, pilihlah salah satu?".format(
                            user.first_name),
                        # keyboards are a great way to provide a menu of options for a user to respond with!
                        keyboards=[
                            SuggestedResponseKeyboard(responses=[
                                TextResponse("Good"),
                                TextResponse("ga")
                            ])
                        ]))

            # Check if the user has sent a text message.
            elif isinstance(message, TextMessage):
                user = self.kik_api.get_user(message.from_user)
                message_body = message.body.lower()
                print(message_body)
                sql = """insert into tb_inbox(user, message)
                        values ('%s','%s')""" % (user.first_name, message_body)
                print("Berhasil Menginputkan")

                curs.execute(sql)

                conn.commit()

                if message_body.split()[0] in ["hi", "hello", "hallo"]:
                    query = "SELECT in_message FROM tb_perintah"
                    curs.execute(query)
                    menu = curs.fetchall()
                    print(message_body)
                    print(menu)
                    msg = "List Menu !!\n"
                    iterasi = 1
                    for x in menu:
                        for y in x:
                            print(y)
                            msg = msg + "" + str(iterasi) + ". " + y + "\n"
                        iterasi += 1
                    response_messages.append(
                        TextMessage(to=message.from_user,
                                    chat_id=message.chat_id,
                                    body=msg.format(user.first_name),
                                    keyboards=[
                                        SuggestedResponseKeyboard(responses=[
                                            TextResponse("1"),
                                            TextResponse("2"),
                                            TextResponse("3"),
                                            TextResponse("4"),
                                            TextResponse("5")
                                        ])
                                    ]))

                    query = "INSERT INTO tb_outbox (user,message,status) VALUES('%s','%s','1')" % (
                        user.first_name, message_body)
                    curs.execute(query)
                    conn.commit()

                elif message_body.startswith("#"):

                    msg = message_body.split()

                    print(msg[0])

                    query = "SELECT query FROM tb_perintah WHERE marker = '%s' " % (
                        msg[0])

                    print(query)

                    try:

                        curs.execute(query)

                    except:

                        print("ERROR")

                    menu = curs.fetchone()

                    print(menu[0])

                    if menu != None:

                        try:

                            msgProdi = msg[6] + " " + msg[7]

                            print(msgProdi)

                            qry = menu[0] % ("%" + msg[3] + "%",
                                             "%" + msgProdi + "%")

                        except:

                            print("INDEX MESSAGE TIDAK DITEMUKAN")

                            qry = menu[0]

                        print(qry)

                        curs.execute(qry)

                        data = curs.fetchall()

                        iterasi = 0

                        teks = ""

                        msgNew = ""

                        for row in data:

                            for i in curs.description:
                                print(i[0])

                                print(row[iterasi])

                                msgNew = msgNew + (i[0] + " = " +
                                                   str(row[iterasi]) + "\n")

                                iterasi += 1

                                # if iterasi == i*4:

                                #     msgNew = "\n"

                                # else:

                                #     msgNew = ""

                            iterasi = 0

                    query = "INSERT INTO tb_outbox (user,message,status) VALUES('%s','%s','0')" % (
                        user.first_name, message_body)

                    print(query)

                    curs.execute(query)

                    conn.commit()

                    response_messages.append(
                        TextMessage(to=message.from_user,
                                    chat_id=message.chat_id,
                                    body=msgNew))

                else:
                    print(int(message_body))
                    query = "SELECT * FROM tb_perintah WHERE id_perintah = %i " % (
                        int(message_body))
                    curs.execute(query)
                    menu = curs.fetchone()
                    print(message.from_user)
                    print(message.chat_id)
                    print(menu[2])
                    response_messages.append(
                        TextMessage(to=message.from_user,
                                    chat_id=message.chat_id,
                                    body=menu[2].format(user.first_name)))

                query = "INSERT INTO tb_outbox (user,message,status) VALUES('%s','%s','1')" % (
                    user.first_name,
                    message_body,
                )
                curs.execute(query)
                conn.commit()

            else:

                response_messages.append(
                    TextMessage(to=message.from_user,
                                chat_id=message.chat_id,
                                body="maaf itu apa ya {}?".format(
                                    user.first_name),
                                keyboards=[
                                    SuggestedResponseKeyboard(responses=[
                                        TextResponse("Good"),
                                        TextResponse("Bad")
                                    ])
                                ]))

            # We're sending a batch of messages. We can send up to 25 messages at a time (with a limit of
            # 5 messages per user).

            self.kik_api.send_messages(response_messages)

        return Response(status=200)
示例#17
0
文件: bot.py 项目: andresgr20/JobHunt
    def incoming(self):
        """Handle incoming messages to the bot. All requests are authenticated using the signature in
        the 'X-Kik-Signature' header, which is built using the bot's api key (set in main() below).
        :return: Response
        """
        # verify that this is a valid request
        if not self.kik_api.verify_signature(
                request.headers.get("X-Kik-Signature"), request.get_data()):
            return Response(status=403)

        messages = messages_from_json(request.json["messages"])

        response_messages = []
        job=""
        location=""
        
        for message in messages:
            user = self.kik_api.get_user(message.from_user)
            # Check if its the user's first message. Start Chatting messages are sent only once.
            if isinstance(message, StartChattingMessage):
                print("body is " + message_body)
                response_messages.append(TextMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    body="Hey {}, Welcome to Job Hunt! You can search for technical internships here! What type of intership are you looking for?".format(user.first_name),
                    # keyboards are a great way to provide a menu of options for a user to respond with!
                    keyboards=[SuggestedResponseKeyboard(responses=[TextResponse("Web Developer"), TextResponse("iOS Developer"),
                                                                        TextResponse("Android Developer"),TextResponse("Full Stack Developer"), TextResponse("BackEnd Developer"),
                                                                        TextResponse("FrontEnd Developer")])]))

            # Check if the user has sent a text message.
            elif isinstance(message, TextMessage):
                user = self.kik_api.get_user(message.from_user)
                message_body = message.body.lower()
                
                if message_body.split()[0] in ["hi","hello","hey" ]:
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Hey {}, what type of internship are you looking for?".format(user.first_name),
                        keyboards=[SuggestedResponseKeyboard(responses=[TextResponse("Web Developer"), TextResponse("iOS Developer"),
                                                                        TextResponse("Android Developer"),TextResponse("Full Stack Developer"), TextResponse("BackEnd Developer"),
                                                                        TextResponse("FrontEnd Developer")])]))
                    
                elif message_body == "web developer":
                    job="web developer"
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Where would you like to work?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Toronto,ON"), TextResponse("Waterloo,ON"), TextResponse("California"), TextResponse("Ottawa,ON"),TextResponse("Austin,TX"), TextResponse("Vancouver,BC"),TextResponse("London,UK"),TextResponse("Himalayas"),TextResponse("Mars"),TextResponse("Atlantis")])]))
                    
                elif message_body == "ios developer":
                    job="ios developer"
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Where would you like to work?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Toronto,ON"), TextResponse("Waterloo,ON"), TextResponse("California"), TextResponse("Ottawa,ON"),TextResponse("Austin,TX"), TextResponse("Vancouver,BC"),TextResponse("London,UK"),TextResponse("Himalayas"),TextResponse("Mars"),TextResponse("Atlantis")])]))   
                    
                elif message_body == "full stack developer":
                    job="full stack developer"
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Where would you like to work?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Toronto,ON"), TextResponse("Waterloo,ON"), TextResponse("California"), TextResponse("Ottawa,ON"),TextResponse("Austin,TX"), TextResponse("Vancouver,BC"),TextResponse("London,UK"),TextResponse("Himalayas"),TextResponse("Mars"),TextResponse("Atlantis")])]))
                    
                elif message_body == "android developer":
                    job="android developer"
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Where would you like to work?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Toronto,ON"), TextResponse("Waterloo,ON"), TextResponse("California"), TextResponse("Ottawa,ON"),TextResponse("Austin,TX"), TextResponse("Vancouver,BC"),TextResponse("London,UK"),TextResponse("Himalayas"),TextResponse("Mars"),TextResponse("Atlantis")])]))                         
                    
                elif message_body == "backend developer":
                    job="backend developer"
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Where would you like to work?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Toronto,ON"), TextResponse("Waterloo,ON"), TextResponse("California"), TextResponse("Ottawa,ON"),TextResponse("Austin,TX"), TextResponse("Vancouver,BC"),TextResponse("London,UK"),TextResponse("Himalayas"),TextResponse("Mars"),TextResponse("Atlantis")])]))     
                    
                elif message_body == "frontend developer":
                    job="frontend developer"
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Where would you like to work?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Toronto,ON"), TextResponse("Waterloo,ON"), TextResponse("California"), TextResponse("Ottawa,ON"),TextResponse("Austin,TX"), TextResponse("Vancouver,BC"),TextResponse("London,UK"), TextResponse("Himalayas"),TextResponse("Mars"),TextResponse("Atlantis")])])) 


                elif message_body == "toronto,on":
                    location=message_body
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Here is the link for the website: " + jobSearch(job,location) + ". Can I help you with something else?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Yes"),TextResponse("No")])])) 
                    
                elif message_body == "waterloo,on":
                    location=message_body
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Here is the link for the website: " + jobSearch(job,location) + ". Can I help you with something else?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Yes"),TextResponse("No")])])) 
                    
                elif message_body == "california":
                    location=message_body
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Here is the link for the website: " + jobSearch(job,location) + " . Can I help you with something else?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Yes"),TextResponse("No")])]))
                    
                elif message_body == "ottawa,on":
                    location=message_body
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Here is the link for the website: " + jobSearch(job,location) + ". Can I help you with something else?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Yes"),TextResponse("No")])])) 
                    
                elif message_body == "austin,tx":
                    location=message_body
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Here is the link for the website: " + jobSearch(job,location) + ". Can I help you with something else?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Yes"),TextResponse("No")])])) 
                    
                elif message_body == "vancouver,on":
                    location=message_body
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Here is the link for the website: " + jobSearch(job,location) + ". Can I help you with something else?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Yes"),TextResponse("No")])])) 
                    
                elif message_body == "london,uk":
                    location=message_body
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Here is the link for the website: " + jobSearch(job,location) + ". Can I help you with something else?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Yes"),TextResponse("No")])]))
                    
                elif message_body == "himalayas":
                    location=message_body
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body= "It is super cold there! " +jobSearch(job,location) + " Can I help you with something else?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Yes"),TextResponse("No")])]))
                elif message_body == "mars":
                    location=message_body
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body= "There is no oxygen there! " + jobSearch(job,location) + " Can I help you with something else?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Yes"),TextResponse("No")])])) 
                    
                elif message_body == "atlantis":
                    location=message_body
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body= "Under the sea, under the sea. Ok, Ariel "+ jobSearch(job,location) + " Can I help you with something else?",
                        keyboards=[SuggestedResponseKeyboard(
                            responses=[TextResponse("Yes"),TextResponse("No")])]))  
                    
                elif message_body == "yes":
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Perfect! {}, what type of internship are you looking for?".format(user.first_name),
                        keyboards=[SuggestedResponseKeyboard(responses=[TextResponse("Web Developer"), TextResponse("iOS Developer"),
                                                                        TextResponse("Android Developer"),TextResponse("Full Stack Developer"), TextResponse("BackEnd Developer"),
                                                                        TextResponse("FrontEnd Developer")])]))                    
                    
                elif message_body in ["WN", "sure! i'd love to!"]:

                    # Send the user a response along with their profile picture (function definition is below)
                    response_messages += self.profile_pic_check_messages(user, message)

                elif message_body in ["no", "no thank you", "nope","cancel","bye"]:
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Ok, {}. Chat with me again if you change your mind.".format(user.first_name)))
                else:
                    response_messages.append(TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Sorry {}, I didn't quite understand that.".format(user.first_name),
                        keyboards=[SuggestedResponseKeyboard(responses=[TextResponse("Web Developer"), TextResponse("iOS Developer"),
                                                                        TextResponse("Android Developer"),TextResponse("Full Stack Developer"), TextResponse("BackEnd Developer"),
                                                                        TextResponse("FrontEnd Developer")])]))

            # If its not a text message, give them another chance to use the suggested responses
            else:

                response_messages.append(TextMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    body="Sorry, I didn't quite understand that. What are you looking for, {}?".format(user.first_name),
                    keyboards=[SuggestedResponseKeyboard(responses=[TextResponse("Web Developer"), TextResponse("iOS Developer"),
                                                                        TextResponse("Android Developer"),TextResponse("Full Stack Developer"), TextResponse("BackEnd Developer"),
                                                                        TextResponse("FrontEnd Developer")])]))

            # We're sending a batch of messages. We can send up to 25 messages at a time (with a limit of
            # 5 messages per user).

            self.kik_api.send_messages(response_messages)

        return Response(status=200)
示例#18
0
def incoming():
    global state
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)
    messages = messages_from_json(request.json['messages'])
    for message in messages:
        if isinstance(message, TextMessage):
            print("aaaaa")
            b = TextMessage(to=message.from_user,
                            body="lalalalal",
                            chat_id=message.chat_id)
            print("bbbbbb")
            b.keyboards.append(
                SuggestedResponseKeyboard(to=message.from_user,
                                          hidden=False,
                                          responses=[TextResponse("aaa")]))
            print("ccccccc")
            kik.send_messages([b])
            '''
            if state==1:
                sql = "INSERT INTO comment (date, menu_id, name, comment) VALUES (%s, %s, %s, %s)"
                val = (today.date, today.menu_id, message.from_user, message.body)
                mycursor.execute(sql, val)
                mydb.commit()
                kik.send_messages([
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Okay, got that!")])
                state = 0
            elif message.body.lower() in ["hi", "hello", "hi!", "hello!", "hey"]:
                kik.send_messages([
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Hi, I'm your rating lunch bot, if you wanna rate your lunch, type\"rate lunch\", if you wanna see the menu, type\"see menu\"")])
                state = 0
            elif message.body.lower() == "rate lunch":
                kik.send_messages([
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Here is your lunch menu: "+today.menu+"\nhow do you like your lunch?")])
                state = 1
                print(state)
            elif message.body.lower() == "see menu":
            	kik.send_messages([
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Here is your lunch menu: "+today.menu)])#need to communicate with database
            	state = 0
            else:
                kik.send_messages([
                TextMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    body="I don't understand, you can type\"rate lunch\" to rate your lunch or \"see menu\" to see the menu")])
                state=0
                '''
        return Response(status=200)
    def test_suggested_keyboard_message(self):
        message = TextMessage.from_json({
            'to':
            'aleem',
            'participants': ['aleem'],
            'chatId':
            'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2',
            'body':
            'Some text',
            'id':
            '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0',
            'timestamp':
            1458336131,
            'readReceiptRequested':
            True,
            'keyboards': [{
                'to':
                'aleem',
                'type':
                'suggested',
                'hidden':
                False,
                'responses': [{
                    'type': 'picture',
                    'picUrl': 'http://foo.bar',
                    'metadata': {
                        'some': 'data'
                    }
                }, {
                    'type': 'text',
                    'body': 'Ok!'
                }, {
                    'type': 'text',
                    'body': 'No way!'
                }, {
                    'type': 'friend-picker',
                    'body': 'Pick a friend!',
                    'min': 1,
                    'max': 5,
                    'preselected': ['foo', 'bar']
                }]
            }]
        })

        self.assertEqual(message.to, 'aleem')
        self.assertEqual(message.participants, ['aleem'])
        self.assertEqual(
            message.chat_id,
            'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2')
        self.assertEqual(message.body, 'Some text')
        self.assertEqual(message.id, '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0')
        self.assertEqual(message.timestamp, 1458336131)
        self.assertIs(True, message.read_receipt_requested)
        responses = [
            PictureResponse('http://foo.bar', {'some': 'data'}),
            TextResponse('Ok!'),
            TextResponse('No way!'),
            FriendPickerResponse('Pick a friend!', 1, 5, ['foo', 'bar'])
        ]
        self.assertEqual(message.keyboards, [
            SuggestedResponseKeyboard(
                to='aleem', hidden=False, responses=responses)
        ])
示例#20
0
文件: bot.py 项目: zippyy/KokiBot
import requests
reset = False
resetUser = ""
MessageHandler = MessageBuilder()
app = Flask(__name__)
kik = KikApi('BOTNAME', 'APIKEY')

#-------------------------KIK BOT CONFIG------------------------------------------------------

afeatures = {"manuallySendReadReceipts" : False,
            "receiveReadReceipts": True,
            "receiveDeliveryReceipts": False,
            "receiveIsTyping": False}
            
staticKeyboard = SuggestedResponseKeyboard(
                         responses=[TextResponse('Set Probe'),
                                    TextResponse('Benchmark Analysis'),
                                    TextResponse('Probe Analysis'),
                                    TextResponse('Inactive Analysis'),
                                    TextResponse('Help')]
                          )            
            
kik.set_configuration(Configuration(webhook='webhook',features = afeatures,static_keyboard = staticKeyboard))

banlist = ""
adminlist ={'kokimetsu','houtarou_','originalparakeet',"svennyberg","gaytheistjake","icancamelcase","adminship","xitulk"}
userList = {'kokimetsu','houtarou_','originalparakeet',"svennyberg","gaytheistjake","muzzysquad"}

#-----------------Returns Keyboard based on if user in in adminlist or not
def SetKeyboard(user):
    if user in adminlist:
示例#21
0
def keyboard_recipient_default():
    """
    Create keyboard responses that are sent to a message recipient.
    :return: An array with the responses that should be sent on the present message.
    """
    return [TextResponse(BUTTONS['recipient_request_feel'])]
示例#22
0
def incoming():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        if isinstance(message, TextMessage):
            if message.body == 'Hi':
                body = 'What\'s the motive?'
                kik.send_messages([
                        VideoMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            video_url=getGiphy.getGiphy('Hello'),
                            autoplay=True,
                            loop=True,
                        ),
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=body,
                            keyboards=[
                                SuggestedResponseKeyboard(
                                    responses=[
                                        TextResponse('Staying in'),
                                        TextResponse('Going out'),
                                    ]
                                )
                            ]
                        )
                    ])
                message = TextResponse

        if isinstance(message, TextMessage):
            if message.body == 'Going out':
                body = 'What day though?'
                kik.send_messages([
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=body,
                            keyboards=[
                                SuggestedResponseKeyboard(
                                    responses=[
                                        TextResponse('Sunday'),
                                        TextResponse('Monday'),
                                        TextResponse('Tuesday'),
                                        TextResponse('Wednesday'),
                                        TextResponse('Thursday'),
                                        TextResponse('Friday'),
                                        TextResponse('Saturday'),
                                    ]
                                )
                            ]
                        )
                    ])
                message = TextResponse

        if isinstance(message, TextMessage):
            if message.body == 'Friday':
                body = ('This is what\'s gucci tonight:\nChainsaw: $3 shots\nEthel\'s: $8 for 1.5lbs wings')
                kik.send_messages([
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=body,
                            keyboards=[
                                SuggestedResponseKeyboard(
                                    responses=[
                                        TextResponse('Chainsaw'),
                                        TextResponse('Ethel\'s'),
                                    ]
                                )
                            ]
                        )
                    ])
                message = TextReponse

        if isinstance(message, TextMessage):
            if message.body == 'Chainsaw':







        return Response(status=200)
示例#23
0
    def incoming(self):
        """Handle incoming messages to the bot. All requests are authenticated using the signature in
        the 'X-Kik-Signature' header, which is built using the bot's api key (set in main() below).
        :return: Response
        """
        # verify that this is a valid request
        if not self.kik_api.verify_signature(
                request.headers.get("X-Kik-Signature"), request.get_data()):
            return Response(status=403)

        messages = messages_from_json(request.json["messages"])

        response_messages = []

        for message in messages:
            user = self.kik_api.get_user(message.from_user)
            # Check if its the user's first message. Start Chatting messages are sent only once.
            if isinstance(message, StartChattingMessage):
                response_messages.append(
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Hey {}, how are you?".format(user.first_name),
                        # keyboards are a great way to provide a menu of options for a user to respond with!
                        keyboards=[
                            SuggestedResponseKeyboard(responses=[
                                TextResponse("Good"),
                                TextResponse("Bad")
                            ])
                        ]))

            # Check if the user has sent a text message.
            elif isinstance(message, TextMessage):
                user = self.kik_api.get_user(message.from_user)
                message_body = message.body.lower()

                try:
                    cekpesan = message_body.lower()
                    cekpesan1 = cekpesan[0:6]
                    print(cekpesan1)
                except:
                    cekpesan1 = message_body
                    print(cekpesan1)

                if message_body == "kumal":
                    url = 'https://kucingpedia.com/wp-content/uploads/2017/08/Gambar-Harga-Kucing-Persia-Warna-Abu-Abu.jpg'
                    print(str(url))
                    response_messages.append(
                        PictureMessage(to=message.from_user,
                                       chat_id=message.chat_id,
                                       pic_url=str(url)))

                elif cekpesan1 == "gambar":
                    userid = message.from_user
                    pesan = message_body
                    chatid = message.chat_id
                    sql = "INSERT INTO tb_inbox (id_inbox, id_user, id_chat, in_msg, tipee, flag) VALUES (NULL, '%s', '%s', '%s', 'img', '1')" % (
                        userid, chatid, pesan)
                    curs.execute(sql)
                    conn.commit()
                    print("1 pesan img handle")

                    sql1 = "SELECT id_outbox, id_user, id_chat, out_msg FROM tb_outbox WHERE flag = '1' AND tipee = 'img' ;"
                    cirs.execute(sql1)
                    results = cirs.fetchall()
                    print("Tables : ", cirs.rowcount)
                    for row in results:
                        print(row[0])
                        print(row[1])
                        print(row[2])
                        print(row[3], "\n")

                        url = row[3]
                        print(str(url))
                        response_messages.append(
                            PictureMessage(to=message.from_user,
                                           chat_id=message.chat_id,
                                           pic_url=str(url)))

                        sql2 = "UPDATE tb_outbox SET flag='2' WHERE id_outbox='%s';" % (
                            str(row[0]))
                        curs.execute(sql2)
                        conn.commit()

                elif cekpesan1 != "gambar":
                    # Insert Pesan ke tabel inbox
                    userid = message.from_user
                    pesan = message_body
                    chatid = message.chat_id
                    sql = "INSERT INTO tb_inbox (id_inbox, id_user, id_chat, in_msg, tipee, flag) VALUES (NULL, '%s', '%s', '%s', 'msg', '1')" % (
                        userid, chatid, pesan)
                    curs.execute(sql)
                    conn.commit()
                    print("1 pesan msg handle")

                    # Select Pesan dari tabel outbox
                    sql1 = "SELECT id_outbox, id_user, id_chat, out_msg FROM tb_outbox WHERE flag = '1' AND tipee = 'msg';"
                    cirs.execute(sql1)
                    results = cirs.fetchall()
                    print("Tables : ", cirs.rowcount)
                    for row in results:
                        print(row[0])
                        print(row[1])
                        print(row[2])
                        print(row[3], "\n")

                        response_messages.append(
                            TextMessage(to=message.from_user,
                                        chat_id=message.chat_id,
                                        body=str(row[3])))

                        sql2 = "UPDATE tb_outbox SET flag='2' WHERE id_outbox='%s';" % (
                            str(row[0]))
                        curs.execute(sql2)
                        conn.commit()

                else:
                    response_messages.append(
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=
                            "Sorry {}, I didn't quite understand that. How are you?"
                            .format(user.first_name),
                            keyboards=[
                                SuggestedResponseKeyboard(responses=[
                                    TextResponse("Good"),
                                    TextResponse("Bad")
                                ])
                            ]))

                # If its not a text message, give them another chance to use the suggested responses.

            else:
                response_messages.append(
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body=
                        "Sorry, I didn't quite understand that. How are you, {}?"
                        .format(user.first_name),
                        keyboards=[
                            SuggestedResponseKeyboard(responses=[
                                TextResponse("Good"),
                                TextResponse("Bad")
                            ])
                        ]))
                # We're sending a batch of messages. We can send up to 25 messages at a time (with a limit of
                # 5 messages per user).

            self.kik_api.send_messages(response_messages)

            return Response(status=200)