/
bot.py
executable file
·169 lines (130 loc) · 7.85 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""An example Kik bot implemented in Python.
It's designed to greet the user, send a suggested response and replies to them with their profile picture.
Remember to replace the BOT_USERNAME_HERE, BOT_API_KEY_HERE and WEBHOOK_HERE fields with your own.
See https://github.com/kikinteractive/kik-python for Kik's Python API documentation.
Apache 2.0 License
(c) 2016 Kik Interactive Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
"""
from flask import Flask, request, Response
from kik import KikApi, Configuration
from kik.messages import messages_from_json, TextMessage, PictureMessage, \
SuggestedResponseKeyboard, TextResponse, StartChattingMessage
class KikBot(Flask):
""" Flask kik bot application class"""
def __init__(self, kik_api, import_name, static_path=None, static_url_path=None, static_folder="static",
template_folder="templates", instance_path=None, instance_relative_config=False,
root_path=None):
self.kik_api = kik_api
super(KikBot, self).__init__(import_name, static_path, static_url_path, static_folder, template_folder,
instance_path, instance_relative_config, root_path)
self.route("/incoming", methods=["POST"])(self.incoming)
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)
@staticmethod
def profile_pic_check_messages(user, message):
"""Function to check if user has a profile picture and returns appropriate messages.
:param user: Kik User Object (used to acquire the URL the profile picture)
:param message: Kik message received by the bot
:return: Message
"""
messages_to_send = []
profile_picture = user.profile_pic_url
if profile_picture is not None:
messages_to_send.append(
# Another type of message is the PictureMessage - your bot can send a pic to the user!
PictureMessage(
to=message.from_user,
chat_id=message.chat_id,
pic_url=profile_picture
))
profile_picture_response = "Here's your profile picture!"
else:
profile_picture_response = "It does not look like you have a profile picture, you should set one"
messages_to_send.append(
TextMessage(to=message.from_user, chat_id=message.chat_id, body=profile_picture_response))
return messages_to_send
if __name__ == "__main__":
""" Main program """
kik = KikApi('prodfriend', '958137de-1eac-4b5c-a440-5bc5c36d769a')
# For simplicity, we're going to set_configuration on startup. However, this really only needs to happen once
# or if the configuration changes. In a production setting, you would only issue this call if you need to change
# the configuration, and not every time the bot starts.
kik.set_configuration(Configuration(webhook='http://bdc639a1.ngrok.io/incoming'))
app = KikBot(kik, __name__)
app.run(port=8080, host='127.0.0.1', debug=True)