I created a Kik messenger bot using Flask microframework and python that accepts POST requests on the provided webhook and then responds appropriately. I have excluded custom module imports because they are not relevant in my problem.
import os
from flask import Flask, request, Response
from flask import Flask, request, Response, url_for
from kik import KikApi, Configuration
from kik.messages import LinkMessage, PictureMessage, VideoMessage
from kik.messages import StartChattingMessage, ScanDataMessage, StickerMessage
from kik.messages import SuggestedResponseKeyboard, TextResponse
from kik.messages import messages_from_json
app = Flask(__name__)
BOT_USERNAME = os.environ['BOT_USERNAME']
BOT_API_KEY = os.environ['BOT_API_KEY']
WEBHOOK = os.environ['WEBHOOK']
features = {'manuallySendReadReceipts': False,
'receiveReadReceipts': True,
'receiveDeliveryReceipts': False,
'receiveIsTyping': False}
static_keyboard = SuggestedResponseKeyboard(
responses=[TextResponse('PLACEHOLDER1'),
TextResponse('PLACEHOLDER2')
])
kik = KikApi(BOT_USERNAME, BOT_API_KEY)
kik.set_configuration(Configuration(
webhook=WEBHOOK, static_keyboard=static_keyboard, features=features))
@app.route('/incoming', methods=['POST'])
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:
user = message.from_user
chat_id = message.chat_id
if isinstance(message, LinkMessage):
# do something
elif isinstance(message, PictureMessage):
# do something
elif isinstance(message, VideoMessage):
# do something
elif isinstance(message, StartChattingMessage):
# do something
elif isinstance(message, ScanDataMessage):
# do something
elif isinstance(message, StickerMessage):
# do something
elif isinstance(message, TextMessage):
query = message.body
query_words = query.split()
chat_type = message.chat_type
participants = message.participants
if query.lower() in ['placeholder1', 'placeholder2']:
# do something
elif query_words[0] in ['placeholder3', 'placeholder4']:
# do something
elif query_words[0] in ['placeholder5'] and user in ['mamun']:
# do something
# a large number of more elif statements present in actual app
else:
# do something
return Response(status=200)
if __name__ == '__main__':
app.run(port=8000, debug=True)
What I have done so far is create separate modules for custom functionality that I created, but in the end they are consumed by the large number of elif statements which I don't like. Is there any way I can avoid the elif statement hell?
My actual bot is 100% complete, production ready and approved by kik, but the way I had to program it still bothers me when I look at it.
elif
s by using just oneif
. I would write an answer, but I am confused by the removed sections of code. Do you want thepass
es? \$\endgroup\$ – EugeneProut Sep 25 '17 at 13:22