def create_kik_bot(self): self._kik_bot = KikApi( self.configuration.client_configuration.bot_name, self._bot_api_key) self._kik_bot.set_configuration( Configuration( webhook=self.configuration.client_configuration.webhook))
def setUp(self): super(KikBotApiTest, self).setUp() self.requests_mock = mock.patch('requests.api.request', wraps=requests_raise_func) self.requests_mock.start() self.api = KikApi('mybotusername', 'mybotapikey')
class Kik_Helper: def __init__(self, username, api_key): self.engine = Engine() self.username = username self.api_key = api_key self.kik = KikApi(username, api_key) def set_config(self, end_point, manually_send_read_receipts, receive_read_receipts, receive_delivery_receipts, receive_is_typing): requests.post('https://api.kik.com/v1/config', auth=(self.username, self.api_key), headers={'Content-Type': 'application/json'}, data=json.dumps({ "webhook": end_point, "features": { "manuallySendReadReceipts": manually_send_read_receipts, "receiveReadReceipts": receive_read_receipts, "receiveDeliveryReceipts": receive_delivery_receipts, "receiveIsTyping": receive_is_typing } })) return Response(status=200) def check_config(self): config = self.kik.get_configuration() return config.webhook def send_messages(self, request): if not self.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): self.kik.send_messages(self.__choose_response(message)) return Response(status=200) def __choose_response(self, message): messages = [] response = self.engine.computeResponse(message.body) message = TextMessage(to=message.from_user, chat_id=message.chat_id, body=response) message.keyboards.append( SuggestedResponseKeyboard(hidden=False, responses=[TextResponse('OK')])) messages.append(message) return messages
def setup(): """Sets up the bot.""" with open('data.json') as d: config = json.load(d) print(config) app = Flask(__name__) kik = KikApi(config["bot_name"], config["api_key"]) kik.set_configuration(Configuration(webhook=config["hostname"])) blobber = Blobber(analyzer=NaiveBayesAnalyzer()) # , classifier = cl) raven_client = Client(config['sentry_hook']) return app, blobber, config, kik
def init(): """ Main program """ kik = KikApi(BOT_USERNAME, BOT_API_KEY) # 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. logging.debug('setting webhook to %s', WEBHOOK) kik.set_configuration(Configuration(webhook=WEBHOOK)) app = KikBot(kik, __name__) if PORT: app.run(port=PORT, host='127.0.0.1', debug=True) # from command line else: return app
def create_kik_bot(self): if self._bot_api_key is not None: kik_bot = KikApi(self.configuration.client_configuration.bot_name, self._bot_api_key) kik_bot.set_configuration( Configuration( webhook=self.configuration.client_configuration.webhook)) return kik_bot else: YLogger.error(self, "Kik bot api key missing, unable to create kik bot") return None
def init_app(path): """ Ensure that the configuration file is loaded by the web server before it is given the Flask app. :param path: Location of the json configuration file for the application to be run. :return: The flask app object, to be used as the WSGI application. """ global config, kik, queue, parser with open(path) as config_file: config = json.load(config_file) Database.init_database(config) kik = KikApi(config['bot_username'], config['bot_api_key']) kik.set_configuration(Configuration(webhook=config['webhook'])) queue = MessageQueue(config, kik) parser = MessageParser(config, queue) return app
def __init__(self, username, api_key, webhook, case_sensitive=False, command_list="Commands"): self.functions = {} self.help = {} self.kik = KikApi(username, api_key) self.kik.set_configuration(Configuration(webhook=webhook)) self.case_sensitive = case_sensitive if not isinstance(command_list, str): command_list = None if not case_sensitive: if command_list != None: command_list = command_list.lower() self.command_list_command = command_list self.keyboard_entries = [ self.command_list_command ] if case_sensitive else [self.command_list_command.title()]
import logging import sendgrid from firebase import firebase import json import re from StringIO import StringIO import nltk from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage, PictureMessage # create a buffer for form-encoded http requests (nltk sentiment) buff = StringIO("") kik = KikApi(os.environ['KIK_BOT_USERNAME'], os.environ['KIK_BOT_API_KEY']) kik.set_configuration(Configuration(webhook='https://damp-castle-40734.herokuapp.com/incoming')) # Firebase is used to track user state and information firebase_db = os.environ['FIREBASE_DB'] firebase = firebase.FirebaseApplication(firebase_db, None) app = Flask(__name__) global bot bot = telegram.Bot(token=os.environ['TELEGRAM_KEY']) # http://www.laurentluce.com/posts/twitter-sentiment-analysis-using-python-and-nltk/ filters = { 'blur': ImageFilter.BLUR,
class KikBotClient(FlaskRestBotClient): def __init__(self, argument_parser=None): FlaskRestBotClient.__init__(self, "kik", argument_parser) self.create_kik_bot() YLogger.debug(self, "Kik Client is running....") def get_description(self): return 'ProgramY AIML2.0 Kik Client' def get_client_configuration(self): return KikConfiguration() def get_license_keys(self): self._bot_api_key = self.license_keys.get_key("KIK_BOT_API_KEY") def create_kik_bot(self): self._kik_bot = KikApi(self.configuration.client_configuration.bot_name, self._bot_api_key) self._kik_bot.set_configuration(Configuration(webhook=self.configuration.client_configuration.webhook)) def handle_text_message(self, message): question = message.body userid = message.from_user answer = self.ask_question(userid, question) self._kik_bot.send_messages([ TextMessage( to=message.from_user, chat_id=message.chat_id, body=answer ) ]) def get_unknown_response(self, userid): if self.configuration.client_configuration.unknown_command_srai is None: unknown_response = self.configuration.client_configuration.unknown_command else: unknown_response = self.ask_question(userid, self.configuration.client_configuration.unknown_command_srai) if unknown_response is None or unknown_response == "": unknown_response = self.configuration.client_configuration.unknown_command return unknown_response def handle_unknown_message(self, message): userid = message.from_user unknown_response = self.get_unknown_response(userid) self._kik_bot.send_messages([ TextMessage( to=message.from_user, chat_id=message.chat_id, body=unknown_response ) ]) def handle_message_request(self, request): messages = messages_from_json(request.json['messages']) for message in messages: if isinstance(message, TextMessage): self.handle_text_message(message) else: self.handle_unknown_message(message) def receive_message(self, request): if self.configuration.client_configuration.debug is True: self.dump_request(request) if not self._kik_bot.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()): return Response(status=403) self.handle_message_request(request) return Response(status=200)
from flask import Flask, request, Response from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage try: from settings import * except ImportError: from settings.example import * app = Flask(__name__) kik = KikApi(BOT_USERNAME, BOT_API_KEY) kik.set_configuration(Configuration(webhook=WEBHOOK)) @app.route('/webhook', 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: if isinstance(message, TextMessage): kik.send_messages([ TextMessage( to=message.from_user, chat_id=message.chat_id, body=message.body ) ])
def __init__(self, username, api_key): self.engine = Engine() self.username = username self.api_key = api_key self.kik = KikApi(username, api_key)
location = geolocator.geocode(street, language=lang) except: pass return location def geoip(): ip = request.headers.get('X-Forwarded-For', request.remote_addr) if ',' in ip: ip = ip.split(',')[0] return geo.get(ip) if config.KIK_BOT_ENABLED: kik_service = KikApi(config.KIK_BOT_USERNAME, config.KIK_BOT_KEY) try: kik_service.set_configuration( Configuration(webhook='https://%s%s' % (config.SERVER_NAME, config.KIK_BOT_WEBHOOK))) except Exception as e: logging.warning(e) else: kik_service = None if config.MICROSOFT_BOT_ENABLED: microsoft_service = BotFrameworkMicrosoft(config.MICROSOFT_BOT_ID, config.MICROSOFT_BOT_KEY) else: microsoft_service = None
class KikBotApiTest(TestCase): def setUp(self): super(KikBotApiTest, self).setUp() self.requests_mock = mock.patch('requests.api.request', wraps=requests_raise_func) self.requests_mock.start() self.api = KikApi('mybotusername', 'mybotapikey') def tearDown(self): super(KikBotApiTest, self).tearDown() self.requests_mock.stop() @mock.patch('requests.post', return_value=_response(200, json.dumps({}).encode('utf-8'))) def test_send_messages(self, post): msgs = [TextMessage(to='aleem', body='Sometext')] response = self.api.send_messages(msgs) post_call = post.call_args self.assertEqual(post_call[0][0], 'https://api.kik.com/v1/message') self.assertEqual(post_call[1]['auth'], ('mybotusername', 'mybotapikey')) self.assertEqual(post_call[1]['timeout'], 60) self.assertEqual(post_call[1]['headers'], {'Content-Type': 'application/json'}) self.assertEqual(json.loads(post_call[1]['data']), { 'messages': [{ 'type': 'text', 'to': 'aleem', 'body': 'Sometext', }] }) self.assertEqual(response, {}) @mock.patch('requests.post', return_value=_response(200, json.dumps({}).encode('utf-8'))) def test_broadcast_messages(self, post): msgs = [TextMessage(to='aleem', body='Sometext')] response = self.api.send_broadcast(msgs) post_call = post.call_args self.assertEqual(post_call[0][0], 'https://api.kik.com/v1/broadcast') self.assertEqual(post_call[1]['auth'], ('mybotusername', 'mybotapikey')) self.assertEqual(post_call[1]['timeout'], 60) self.assertEqual(post_call[1]['headers'], {'Content-Type': 'application/json'}) self.assertEqual(json.loads(post_call[1]['data']), { 'messages': [{ 'type': 'text', 'to': 'aleem', 'body': 'Sometext' }] }) self.assertEqual(response, {}) @mock.patch('requests.post', return_value=_response(400, json.dumps({'error': 'BadRequest'}).encode('utf-8'))) def test_send_messages_failure(self, post): msgs = [TextMessage(to='aleem', body='Sometext')] self.assertRaises(KikError, self.api.send_messages, msgs) @mock.patch('requests.post', return_value=_response(400, json.dumps({'error': 'BadRequest'}).encode('utf-8'))) def test_send_broadcast_failure(self, post): msgs = [TextMessage(to='aleem', body='Sometext')] self.assertRaises(KikError, self.api.send_broadcast, msgs) @mock.patch('requests.get', return_value=_response(200, json.dumps({ 'firstName': 'First', 'lastName': 'Last', 'profilePicUrl': 'http://foo.bar/profile', 'profilePicLastModified': 1458657367 }).encode('utf-8'))) def test_get_user_profile(self, get): user = self.api.get_user('aleem') get.assert_called_once_with( 'https://api.kik.com/v1/user/aleem', auth=('mybotusername', 'mybotapikey'), timeout=60 ) self.assertIsInstance(user, User) self.assertEqual(user.first_name, 'First') self.assertEqual(user.last_name, 'Last') self.assertEqual(user.profile_pic_url, 'http://foo.bar/profile') self.assertEqual(user.profile_pic_last_modified, 1458657367) @mock.patch('requests.get', return_value=_response(400, json.dumps({'error': 'BadRequest'}).encode('utf-8'))) def test_get_user_profile_failure(self, get): self.assertRaises(KikError, self.api.get_user, 'aleem') @mock.patch('requests.post', return_value=_response( 200, json.dumps({'id': 'ba7a319394f912ccad1ac42770529bd5cb0e9783'}).encode('utf-8') )) def test_create_kik_code(self, post): code = self.api.create_code({'akey': 'avalue'}) post.assert_called_once_with( 'https://api.kik.com/v1/code', timeout=60, auth=('mybotusername', 'mybotapikey'), headers={ 'Content-Type': 'application/json' }, data=json.dumps({'data': '{"akey": "avalue"}'}) ) self.assertIsInstance(code, Code) self.assertEqual(code.id, 'ba7a319394f912ccad1ac42770529bd5cb0e9783') @mock.patch('requests.post', return_value=_response( 200, json.dumps({'id': 'ba7a319394f912ccad1ac42770529bd5cb0e9783'}).encode('utf-8') )) def test_create_kik_code_no_data(self, post): code = self.api.create_code() post.assert_called_once_with( 'https://api.kik.com/v1/code', timeout=60, auth=('mybotusername', 'mybotapikey'), headers={ 'Content-Type': 'application/json' }, data='{}' ) self.assertIsInstance(code, Code) self.assertEqual(code.id, 'ba7a319394f912ccad1ac42770529bd5cb0e9783') @mock.patch('requests.post', return_value=_response(400, json.dumps({'error': 'BadRequest'}).encode('utf-8'))) def test_create_kik_code_failure(self, post): self.assertRaises(KikError, self.api.create_code, {'akey': 'avalue'}) @mock.patch('requests.get', return_value=_response(200, json.dumps({ 'webhook': 'https://example.com/incoming', 'features': { 'manuallySendReadReceipts': True } }).encode('utf-8'))) 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.assertEqual(config.webhook, 'https://example.com/incoming') self.assertEqual(config.features, {'manuallySendReadReceipts': True}) @mock.patch('requests.post', return_value=_response(200, json.dumps({ 'webhook': 'https://example.com/incoming', 'features': { 'manuallySendReadReceipts': True } }).encode('utf-8'))) def test_set_configuration(self, post): config = Configuration( webhook='https://example.com/incoming', features={'manuallySendReadReceipts': True} ) response = self.api.set_configuration(config) self.assertEqual(post.call_count, 1) self.assertEqual(post.call_args[0][0], 'https://api.kik.com/v1/config') self.assertEqual(post.call_args[1]['timeout'], 60) self.assertEqual(post.call_args[1]['auth'], ('mybotusername', 'mybotapikey')) self.assertEqual(post.call_args[1]['headers'], {'Content-Type': 'application/json'}) self.assertEqual(json.loads(post.call_args[1]['data']), { 'webhook': 'https://example.com/incoming', 'features': { 'manuallySendReadReceipts': True } }) self.assertIsInstance(response, Configuration) self.assertEqual(response.webhook, 'https://example.com/incoming') self.assertEqual(response.features, {'manuallySendReadReceipts': True}) def test_verify_signature(self): self.assertTrue(self.api.verify_signature('AC18D0105C2C257652859322B0499313342C6EB9', b'body')) self.assertFalse(self.api.verify_signature('fakesig', b'body'))
from flask import Flask, request, Response from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage app = Flask(__name__) kik = KikApi("female_lama", "42cd379e-5f1a-4390-881d-955f028221e2") kik.set_configuration( Configuration(webhook="https://22e81a38.ngrok.io/incoming")) live_dict = {} def user_is_admin(username): return username in [ "ilike3pancakes", "oskarsbanana", "YG_Bands_", "vikiid95", "goditee", "BossJordan_g", "Its_Margo_", "yoitscass28" ] def maybe_do_verify(_text_message): if not user_is_admin(_text_message.from_user): return _text_message.body user = _text_message.body.split("verify with me ") if len(user) < 2 or len(user[1]) < 1: return "Please verify with the admin @%s" % _text_message.from_user return "Hello %s, the group admin @%s is asking for verification. Please send a live photo to them using the kik camera to prove that your kik profile is real." % ( user[1], _text_message.from_user)
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 = "ini dia foto kamuu!" else: profile_picture_response = "ga mirip loh, yaudh lah yaa" 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('botmca', 'fffa79e9-afe9-45e4-b2bd-6ec78732b3de') # 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='https://7c50a1a4.ngrok.io/incoming')) app = KikBot(kik, __name__) app.run(port=8080, host='127.0.0.1', debug=True)
from flask import Flask, request, Response from kik import KikApi, Configuration, KikError from kik.messages import messages_from_json, TextMessage from kik_hangman_session import Hangman import json import logging from kik_sql import KikDB import os logging.basicConfig(filename='hangmanlog.log', level=logging.INFO, format="[%(asctime)s] %(message)s") app = Flask(__name__) kik = KikApi('gameofhangman', os.environ['KIK_API_KEY']) Hangman.kik = kik code = kik.create_code( {os.environ['KIK_CODE_KEY']: os.environ['KIK_CODE_VALUE']}) server_url = 'http://' + os.environ['KIK_HOSTNAME'] + ':8080/incoming' kik.set_configuration(Configuration(webhook=server_url)) def logprint(msg, *args): logging.info(msg) for i in args: logging.info(str(i)) print(msg, args) @app.route('/incoming', methods=['POST'])
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 = "ini dia foto kamuu!" else: profile_picture_response = "ga mirip loh, yaudh lah yaa" 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('dodebot', '50c8dd0b-3eee-4b6d-a75e-22d1ea3abecf') # 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='https://a62f7c5e.ngrok.io/incoming')) app = KikBot(kik, __name__) app.run(port=8080, host='127.0.0.1', debug=True)
from flask import Flask, request, Response import requests, json from champion import * from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage, StartChattingMessage, IsTypingMessage app = Flask(__name__) kik = KikApi("leaguestats", "d7fdd8fa-d642-4517-bda4-2392a5820db4") api_key = "d7fdd8fa-d642-4517-bda4-2392a5820db4" riotKey = 'RGAPI-33ddda68-2769-46cc-8a03-1c8c393551ad' kik.set_configuration(Configuration("https://1556b3a4.ngrok.io/inc")) @app.route('/inc', methods=['POST']) def inc(): if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()): return Response(status=403) #chatID = None chatMessage = None greetingMessage = "Welcome to LeagueStats! Type in your summoner name in order to find out your\ worst 3 champions!" userNotExist = "This user doesn't exist, please try to enter another summoner name." messages = messages_from_json(request.json['messages']) for message in messages: if isinstance(message, StartChattingMessage):
class Bot(object): def __init__(self, username, api_key, webhook, case_sensitive=False, command_list="Commands"): self.functions = {} self.help = {} self.kik = KikApi(username, api_key) self.kik.set_configuration(Configuration(webhook=webhook)) self.case_sensitive = case_sensitive if not isinstance(command_list, str): command_list = None if not case_sensitive: if command_list != None: command_list = command_list.lower() self.command_list_command = command_list self.keyboard_entries = [ self.command_list_command ] if case_sensitive else [self.command_list_command.title()] def start(self, route="/incoming"): @app.route(route, methods=["POST", "GET"]) def main(): if not self.kik.verify_signature( request.headers.get('X-Kik-Signature'), request.get_data()): return Response(status=403) messages = messages_from_json(request.json['messages']) print "--Received Messages", messages to_send = None for message in messages: self.kik.send_messages([ IsTypingMessage(to=message.from_user, chat_id=message.chat_id, is_typing=True) ]) if isinstance(message, TextMessage): split = message.body.split(" ") command = split[0] if not self.case_sensitive: command = command.lower() text_data = " ".join(split[1:]) if command == self.command_list_command: r = [ TextMessage(to=message.from_user, chat_id=message.chat_id, body=self.command_list()) ] elif self.functions.has_key(command): r = self.functions[command](text_data) else: r = [ TextMessage(to=message.from_user, chat_id=message.chat_id, body="Unknown command.") ] for m in r: if m.to == None: m.to = message.from_user if m.chat_id == None: m.chat_id = message.chat_id if m.keyboards == []: keyboard = self.make_keyboard() if len(keyboard.responses) > 0: m.keyboards.append(keyboard) self.kik.send_messages(r) return Response(status=200) def make_keyboard(self): keyboard = SuggestedResponseKeyboard( hidden=False, responses=[TextResponse(x) for x in self.keyboard_entries]) return keyboard def command(self, name, help_entry=None): if not self.case_sensitive: name = name.lower() def decorator(function): def wrapper(): return function self.functions[name] = function if isinstance(help_entry, str): self.help[name] = help_entry return wrapper() return decorator def keyboard(self, entry): def decorator(function): def wrapper(): return function self.keyboard_entries.append(entry) return wrapper() return decorator def execute(self, name, *args, **kwargs): return self.functions[name](*args, **kwargs) def command_list(self): return "\n".join( [key + " : " + val for key, val in self.help.iteritems()])
import sys import mysql.connector from datetime import date class mymenu: def __init__(self, date, menu, menu_id): self.date = date self.menu = menu self.menu_id = menu_id my_date = date.today() app = Flask(__name__) kik = KikApi("chinyeebot", "8ed8ec43-b3c6-45d9-85e4-0e4442d592a4") mydb = mysql.connector.connect(host="us-cdbr-iron-east-01.cleardb.net", user="******", passwd="2c2f1c38", database="heroku_5a951cfac26923b") mycursor = mydb.cursor() #sql = "select menu from menu join lunch_info on lunch_info.menu_id=menu.id where date=?" mycursor.execute( "select * from menu join lunch_info on lunch_info.menu_id = menu.id where date = %(date)s", {'date': my_date}) a = mycursor.fetchall()[0] my_menu = a[1] my_menu_id = a[0] today = mymenu(my_date, my_menu, my_menu_id)
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('BOT_USERNAME_HERE', 'BOT_API_KEY_HERE') # 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='WEBHOOK_HERE')) app = KikBot(kik, __name__) app.run(port=8080, host='127.0.0.1', debug=True)
self.response_messages.append( TextMessage(to=self.message.from_user, chat_id=self.message.chat_id, body=message)) def send_message_with_responses(self, message, responses): text_responses = [] for response in responses: text_responses.append(TextResponse(response)) self.response_messages.append( TextMessage(to=self.message.from_user, chat_id=self.message.chat_id, body=message, keyboards=[ SuggestedResponseKeyboard(responses=text_responses) ])) if __name__ == "__main__": """ Main program """ kik = KikApi('studyhelper', 'be6f061d-69f2-401a-9fad-0a31aa9cac68') # 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=LISTENING_SERVER + '/incoming')) app = KikBot(kik, __name__) app.run(port=8080, host='127.0.0.1', debug=True)
from flask import Flask, request, Response import os from random import randint from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage,VideoMessage,SuggestedResponseKeyboard,TextResponse app = Flask(__name__) # kik = KikApi("TwerkBabes","aa3bc886-2ccc-4382-a754-248cdce3b0c8") # kik = KikApi("TwerkBabes","e3900be8-7cb0-491e-8fa2-95a58719ce3a") kik = KikApi("TwerkBabes","e3900be8-7cb0-491e-8fa2-95a58719ce3a") kik.set_configuration(Configuration(webhook="http://107.170.21.148:9997/incoming",features= {"manuallySendReadReceipts": True,"receiveReadReceipts": True,"receiveDeliveryReceipts": True,"receiveIsTyping": True})) #kik.send_messages([TextMessage(to='adertsc3521',body='Test')]) dir_list = os.listdir('/var/www/html/videos') @app.route('/incoming', methods=['POST']) def incoming(): # print 'kuch to hua2' 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']) msg = TextMessage() for message in messages: if isinstance(message, TextMessage): # print message.body # kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="thank you for messaging TwerkBabes. Your daily source of Twerkers")]) # kik.send_messages([VideoMessage(to=message.from_user,chat_id=message.chat_id,video_url="http://199.217.117.213:9999/static/tt.mp4")]) # kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="We hope you enjoyed this twerk babe! See more by going to url.com")]) # break random_index = randint(0,len(dir_list)-1) file_name = dir_list[random_index]
from flask import Flask, request, Response from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage app = Flask(__name__) kik = KikApi('valescobot', 'b21fceb8-90ab-4599-8004-43b336f33054') kik.set_configuration(Configuration(webhook='https://dry-dawn-97641.herokuapp.com/')) @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: if isinstance(message, TextMessage): kik.send_messages([ TextMessage( to=message.from_user, chat_id=message.chat_id, body=message.body ) ]) return Response(status=200) if __name__ == "__main__":
def init_bot(self): self._bot = KikApi(self.username, self.api_key)
class KikBot(IntegrationBot): """ Kik integration. Permabots sets webhook. Only requires api_key and username from Kik provider. Follow Kik instructons to create a bot and obtain username and api_key `<https://dev.kik.com/>`_. """ api_key = models.CharField(_('Kik Bot API key'), max_length=200, db_index=True) username = models.CharField(_("Kik Bot User name"), max_length=200) class Meta: verbose_name = _('Kik Bot') verbose_name_plural = _('Kik Bots') def __init__(self, *args, **kwargs): super(KikBot, self).__init__(*args, **kwargs) self._bot = None if self.api_key and self.username: self.init_bot() def __str__(self): return "%s" % self.username def __repr__(self): return "(%s, %s)" % (self.username, self.api_key) def init_bot(self): self._bot = KikApi(self.username, self.api_key) def set_webhook(self, url): self._bot.set_configuration(Configuration(webhook=url)) @property def hook_url(self): return 'permabots:kikbot' @property def hook_id(self): return str(self.id) @property def null_url(self): return "https://example.com" @property def identity(self): return 'kik' def message_text(self, message): return message.body def get_chat_state(self, message): try: return KikChatState.objects.select_related('state', 'chat', 'user').get(chat=message.chat, user=message.from_user, state__bot=self.bot) except KikChatState.DoesNotExist: return None def build_keyboard(self, keyboard): def traverse(o, tree_types=(list, tuple)): if isinstance(o, tree_types): for value in o: for subvalue in traverse(value, tree_types): yield subvalue else: yield o built_keyboard = [] if keyboard: built_keyboard = [TextResponse(element) for element in traverse(ast.literal_eval(keyboard))][:20] return built_keyboard def create_chat_state(self, message, target_state, context): KikChatState.objects.create(chat=message.chat, user=message.from_user, state=target_state, ctx=context) def get_chat_id(self, message): return message.chat.id def send_message(self, chat_id, text, keyboard, reply_message=None, user=None): if reply_message: to = reply_message.from_user.username if user: to = user texts = text.strip().split('\\n') msgs = [] for txt in texts: for chunk in textwrap.wrap(txt, 100): msg = TextMessage(to=to, chat_id=chat_id, body=chunk) msgs.append(msg) if keyboard: msgs[-1].keyboards.append(SuggestedResponseKeyboard(to=to, responses=keyboard)) try: logger.debug("Messages to send:(%s)" % str([m.to_json() for m in msgs])) self._bot.send_messages(msgs) logger.debug("Message sent OK:(%s)" % str([m.to_json() for m in msgs])) except: exctype, value = sys.exc_info()[:2] logger.error("Error trying to send message:(%s): %s:%s" % (str([m.to_json() for m in msgs]), exctype, value))
picture_table = 'pic.pdl' AM8 = '8AM' PM8 = '8PM' AM10 = '10AM' PM10 = '10PM' DEFAULT_TIME = 18 SET_BAE_TIME = 'SET BAE TIME' TODAY_BAE = "TODAY'S BAE" DISABLE_BAE_TIME = 'DISABLE BAE TIME' app = Flask(__name__) # kik = KikApi("TwerkBabes","aa3bc886-2ccc-4382-a754-248cdce3b0c8") # kik = KikApi("TwerkBabes","e3900be8-7cb0-491e-8fa2-95a58719ce3a") kik = KikApi(bot_username,bot_secret_key) kik.set_configuration(Configuration(webhook=webhook_address,features= {"manuallySendReadReceipts": True,"receiveReadReceipts": True,"receiveDeliveryReceipts": True,"receiveIsTyping": True})) db = Base(schedule_table_name) if db.exists(): db.open() #kik.send_messages([TextMessage(to='adertsc3521',body='Test')]) def run_every_10_seconds(): print 'run_every_10_seconds' now = datetime.datetime.now() #record = db(user="") #now = now.replace(hour=20, minute=0, second=1, microsecond=0) print now; db = Base(schedule_table_name) if db.exists(): db.open()
class KikBotClient(FlaskRestBotClient): def __init__(self, argument_parser=None): FlaskRestBotClient.__init__(self, "kik", argument_parser) self.create_kik_bot() YLogger.debug(self, "Kik Client is running....") def get_client_configuration(self): return KikConfiguration() def get_license_keys(self): self._bot_api_key = self.license_keys.get_key("KIK_BOT_API_KEY") def create_kik_bot(self): self._kik_bot = KikApi( self.configuration.client_configuration.bot_name, self._bot_api_key) self._kik_bot.set_configuration( Configuration( webhook=self.configuration.client_configuration.webhook)) def handle_text_message(self, message): question = message.body userid = message.from_user answer = self.ask_question(userid, question) self._kik_bot.send_messages([ TextMessage(to=message.from_user, chat_id=message.chat_id, body=answer) ]) def get_unknown_response(self, userid): if self.configuration.client_configuration.unknown_command_srai is None: unknown_response = self.configuration.client_configuration.unknown_command else: unknown_response = self.ask_question( userid, self.configuration.client_configuration.unknown_command_srai) if unknown_response is None or unknown_response == "": unknown_response = self.configuration.client_configuration.unknown_command return unknown_response def handle_unknown_message(self, message): userid = message.from_user unknown_response = self.get_unknown_response(userid) self._kik_bot.send_messages([ TextMessage(to=message.from_user, chat_id=message.chat_id, body=unknown_response) ]) def handle_message_request(self, request): messages = messages_from_json(request.json['messages']) for message in messages: if isinstance(message, TextMessage): self.handle_text_message(message) else: self.handle_unknown_message(message) def receive_message(self, request): if self.configuration.client_configuration.debug is True: self.dump_request(request) if not self._kik_bot.verify_signature( request.headers.get('X-Kik-Signature'), request.get_data()): return Response(status=403) self.handle_message_request(request) return Response(status=200)
import json import sys from importlib import import_module from os import listdir, path sys.path.insert(0, path.join(path.dirname(__file__), '.')) sys.path.insert(0, path.join(path.dirname(__file__), 'xlib')) from config import Config from flask import Flask, request from kik import KikApi, Configuration app = Flask(__name__) kik = KikApi(Config.BOT_USERNAME, Config.BOT_API_KEY) config = Configuration(webhook='https://ea997cf2.ngrok.io/incoming', features={}) kik.set_configuration(config) @app.before_request def parse_data(): if request.method in ('POST', 'PATCH', 'PUT', 'DELETE'): try: request.args = json.loads(request.get_data()) except ValueError: pass for file_name in listdir('{}/api'.format(path.dirname(path.realpath(__file__)))): if not file_name.startswith('.') and file_name.endswith('.py') and file_name != '__init__.py': import_module('api.{}'.format(file_name[:-3]))
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)
class Kik_Helper: def __init__(self, username, api_key): self.engine = Engine() self.username = username self.api_key = api_key self.kik = KikApi(username, api_key) def set_config(self, end_point, manually_send_read_receipts, receive_read_receipts, receive_delivery_receipts, receive_is_typing): requests.post( 'https://api.kik.com/v1/config', auth=(self.username, self.api_key), headers={ 'Content-Type': 'application/json' }, data=json.dumps({ "webhook": end_point, "features": { "manuallySendReadReceipts": manually_send_read_receipts, "receiveReadReceipts": receive_read_receipts, "receiveDeliveryReceipts": receive_delivery_receipts, "receiveIsTyping": receive_is_typing } }) ) return Response(status=200) def check_config(self): config = self.kik.get_configuration() return config.webhook def send_messages(self, request): if not self.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): self.kik.send_messages(self.__choose_response(message)) return Response(status=200) def __choose_response(self, message): messages = [] response = self.engine.computeResponse(message.body) message = TextMessage( to=message.from_user, chat_id=message.chat_id, body=response ) message.keyboards.append( SuggestedResponseKeyboard( hidden = False, responses = [TextResponse('OK')] ) ) messages.append(message) return messages
def create_kik_bot(self): self._kik_bot = KikApi(self.configuration.client_configuration.bot_name, self._bot_api_key) self._kik_bot.set_configuration(Configuration(webhook=self.configuration.client_configuration.webhook))
class KikBot(IntegrationBot): """ Kik integration. Permabots sets webhook. Only requires api_key and username from Kik provider. Follow Kik instructons to create a bot and obtain username and api_key `<https://dev.kik.com/>`_. """ api_key = models.CharField(_('Kik Bot API key'), max_length=200, db_index=True) username = models.CharField(_("Kik Bot User name"), max_length=200) class Meta: verbose_name = _('Kik Bot') verbose_name_plural = _('Kik Bots') def __init__(self, *args, **kwargs): super(KikBot, self).__init__(*args, **kwargs) self._bot = None if self.api_key and self.username: self.init_bot() def __str__(self): return "%s" % self.username def __repr__(self): return "(%s, %s)" % (self.username, self.api_key) def init_bot(self): self._bot = KikApi(self.username, self.api_key) def set_webhook(self, url): self._bot.set_configuration(Configuration(webhook=url)) @property def hook_url(self): return 'permabots:kikbot' @property def hook_id(self): return str(self.id) @property def null_url(self): return "https://example.com" @property def identity(self): return 'kik' def message_text(self, message): return message.body def get_chat_state(self, message): try: return KikChatState.objects.select_related( 'state', 'chat', 'user').get(chat=message.chat, user=message.from_user, state__bot=self.bot) except KikChatState.DoesNotExist: return None def build_keyboard(self, keyboard): def traverse(o, tree_types=(list, tuple)): if isinstance(o, tree_types): for value in o: for subvalue in traverse(value, tree_types): yield subvalue else: yield o built_keyboard = [] if keyboard: built_keyboard = [ TextResponse(element) for element in traverse(ast.literal_eval(keyboard)) ][:20] return built_keyboard def create_chat_state(self, message, target_state, context): KikChatState.objects.create(chat=message.chat, user=message.from_user, state=target_state, ctx=context) def get_chat_id(self, message): return message.chat.id def send_message(self, chat_id, text, keyboard, reply_message=None, user=None): if reply_message: to = reply_message.from_user.username if user: to = user texts = text.strip().split('\\n') msgs = [] for txt in texts: for chunk in textwrap.wrap(txt, 100): msg = TextMessage(to=to, chat_id=chat_id, body=chunk) msgs.append(msg) if keyboard: msgs[-1].keyboards.append( SuggestedResponseKeyboard(to=to, responses=keyboard)) try: logger.debug("Messages to send:(%s)" % str([m.to_json() for m in msgs])) self._bot.send_messages(msgs) logger.debug("Message sent OK:(%s)" % str([m.to_json() for m in msgs])) except: exctype, value = sys.exc_info()[:2] logger.error("Error trying to send message:(%s): %s:%s" % (str([m.to_json() for m in msgs]), exctype, value))
from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage #from tag_speech import SpeechTagger # import responses from responses import UsrgreetingList, messageList, help_str from weather_request import * from wit import Wit bot = Wit(access_token="VOCFYQI6MHUL7CDRMPURE4Z26KJGNL7G") usr_name = 'glooffybot' key = '71981fb3-c57d-43bf-ac84-534120e8857e' weather_key = "396cbf110cc7bd1bd3087f317643a83f" app = Flask(__name__) kik = KikApi(usr_name, key) # this is for the kik server. It sets up the webhook so that kik server can # send messages to the webhook and then incoming function extracts the data # recieved. kik.set_configuration(Configuration(webhook='https://glooffy.herokuapp.com/')) def SendMessage(user, ch_id, msg): # sends a single message kik.send_messages([TextMessage(to=user, chat_id=ch_id, body=msg)]) @app.route('/', methods=['POST']) def incoming(): if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
class KikBotApiTest(TestCase): def setUp(self): super(KikBotApiTest, self).setUp() self.requests_mock = mock.patch('requests.api.request', wraps=requests_raise_func) self.requests_mock.start() self.api = KikApi('mybotusername', 'mybotapikey') def tearDown(self): super(KikBotApiTest, self).tearDown() self.requests_mock.stop() @mock.patch('requests.post', return_value=_response(200, json.dumps({}).encode('utf-8'))) def test_send_messages(self, post): msgs = [TextMessage(to='aleem', body='Sometext')] response = self.api.send_messages(msgs) post_call = post.call_args self.assertEqual(post_call[0][0], 'https://api.kik.com/v1/message') self.assertEqual(post_call[1]['auth'], ('mybotusername', 'mybotapikey')) self.assertEqual(post_call[1]['timeout'], 60) self.assertEqual(post_call[1]['headers'], {'Content-Type': 'application/json'}) self.assertEqual(json.loads(post_call[1]['data']), { 'messages': [{ 'type': 'text', 'to': 'aleem', 'body': 'Sometext', }] }) self.assertEqual(response, {}) @mock.patch('requests.post', return_value=_response(200, json.dumps({}).encode('utf-8'))) def test_broadcast_messages(self, post): msgs = [TextMessage(to='aleem', body='Sometext')] response = self.api.send_broadcast(msgs) post_call = post.call_args self.assertEqual(post_call[0][0], 'https://api.kik.com/v1/broadcast') self.assertEqual(post_call[1]['auth'], ('mybotusername', 'mybotapikey')) self.assertEqual(post_call[1]['timeout'], 60) self.assertEqual(post_call[1]['headers'], {'Content-Type': 'application/json'}) self.assertEqual(json.loads(post_call[1]['data']), { 'messages': [{ 'type': 'text', 'to': 'aleem', 'body': 'Sometext' }] }) self.assertEqual(response, {}) @mock.patch('requests.post', return_value=_response( 400, json.dumps({ 'error': 'BadRequest' }).encode('utf-8'))) def test_send_messages_failure(self, post): msgs = [TextMessage(to='aleem', body='Sometext')] self.assertRaises(KikError, self.api.send_messages, msgs) @mock.patch('requests.post', return_value=_response( 400, json.dumps({ 'error': 'BadRequest' }).encode('utf-8'))) def test_send_broadcast_failure(self, post): msgs = [TextMessage(to='aleem', body='Sometext')] self.assertRaises(KikError, self.api.send_broadcast, msgs) @mock.patch('requests.get', return_value=_response( 200, json.dumps({ 'firstName': 'First', 'lastName': 'Last', 'profilePicUrl': 'http://foo.bar/profile', 'profilePicLastModified': 1458657367 }).encode('utf-8'))) def test_get_user_profile(self, get): user = self.api.get_user('aleem') get.assert_called_once_with('https://api.kik.com/v1/user/aleem', auth=('mybotusername', 'mybotapikey'), timeout=60) self.assertIsInstance(user, User) self.assertEqual(user.first_name, 'First') self.assertEqual(user.last_name, 'Last') self.assertEqual(user.profile_pic_url, 'http://foo.bar/profile') self.assertEqual(user.profile_pic_last_modified, 1458657367) @mock.patch('requests.get', return_value=_response( 400, json.dumps({ 'error': 'BadRequest' }).encode('utf-8'))) def test_get_user_profile_failure(self, get): self.assertRaises(KikError, self.api.get_user, 'aleem') @mock.patch('requests.post', return_value=_response( 200, json.dumps({ 'id': 'ba7a319394f912ccad1ac42770529bd5cb0e9783' }).encode('utf-8'))) def test_create_kik_code(self, post): code = self.api.create_code({'akey': 'avalue'}) post.assert_called_once_with( 'https://api.kik.com/v1/code', timeout=60, auth=('mybotusername', 'mybotapikey'), headers={'Content-Type': 'application/json'}, data=json.dumps({'data': '{"akey": "avalue"}'})) self.assertIsInstance(code, Code) self.assertEqual(code.id, 'ba7a319394f912ccad1ac42770529bd5cb0e9783') @mock.patch('requests.post', return_value=_response( 200, json.dumps({ 'id': 'ba7a319394f912ccad1ac42770529bd5cb0e9783' }).encode('utf-8'))) def test_create_kik_code_no_data(self, post): code = self.api.create_code() post.assert_called_once_with( 'https://api.kik.com/v1/code', timeout=60, auth=('mybotusername', 'mybotapikey'), headers={'Content-Type': 'application/json'}, data='{}') self.assertIsInstance(code, Code) self.assertEqual(code.id, 'ba7a319394f912ccad1ac42770529bd5cb0e9783') @mock.patch('requests.post', return_value=_response( 400, json.dumps({ 'error': 'BadRequest' }).encode('utf-8'))) def test_create_kik_code_failure(self, post): self.assertRaises(KikError, self.api.create_code, {'akey': 'avalue'}) @mock.patch('requests.get', return_value=_response( 200, json.dumps({ 'webhook': 'https://example.com/incoming', 'features': { 'manuallySendReadReceipts': True } }).encode('utf-8'))) 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.assertEqual(config.webhook, 'https://example.com/incoming') self.assertEqual(config.features, {'manuallySendReadReceipts': True}) @mock.patch('requests.post', return_value=_response(200, json.dumps({}).encode('utf-8'))) def test_set_configuration(self, post): config = Configuration(webhook='https://example.com/incoming', features={'manuallySendReadReceipts': True}) response = self.api.set_configuration(config) self.assertEqual(post.call_count, 1) self.assertEqual(post.call_args[0][0], 'https://api.kik.com/v1/config') self.assertEqual(post.call_args[1]['timeout'], 60) self.assertEqual(post.call_args[1]['auth'], ('mybotusername', 'mybotapikey')) self.assertEqual(post.call_args[1]['headers'], {'Content-Type': 'application/json'}) self.assertEqual( json.loads(post.call_args[1]['data']), { 'webhook': 'https://example.com/incoming', 'features': { 'manuallySendReadReceipts': True } }) self.assertEqual(response, {})
from flask import Flask, request, Response from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage, VideoMessage ##### NEW ##### from config import username, api_key, webhook ##### NEW ##### from giphypop import translate app = Flask(__name__) kik = KikApi(username, api_key) kik.set_configuration(Configuration(webhook=webhook)) ###### def giffy(message): img = translate(message, api_key='dc6zaTOxFJmzC') gif = img.fixed_height.url print(gif) return gif ####### @app.route('/incoming', methods=['POST']) def incoming(): print('coming in here') if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
import const from flask import Flask, request, Response from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage import main_work app = Flask(__name__) kik = KikApi(const.bot_name, const.bot_api_key) kik.set_configuration(Configuration(webhook= const.bot_server + 'incoming')) @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: if isinstance(message, TextMessage): main_work.func(message, TextMessage, kik) '''kik.send_messages([ TextMessage( to=message.from_user,
print( "[{bot_username}] Could not load custom module: custom_modules.{custom_module} ... - ignoring" .format(custom_module=custom_module_name, bot_username=bot_username)) # prepare database if custom_module is not None and hasattr(custom_module, "ModuleCharacterPersistentClass"): db_class = custom_module.ModuleCharacterPersistentClass( default_config, bot_username) else: db_class = CharacterPersistentClass(default_config, bot_username) del db_class kik_api = KikApi( bot_username, default_config.get("BotAuthCode", "abcdef01-2345-6789-abcd-ef0123456789")) LazyKikUser.kik_api = kik_api # 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_api.set_configuration( Configuration(webhook="{}:{}/incoming".format( default_config.get("RemoteHostIP", "www.example.com"), default_config.get("RemotePort", "8080")))) print("[{bot_username}] Debug URL: {host}:{port}/debug".format( bot_username=bot_username, host=default_config.get("RemoteHostIP", "www.example.com"), port=default_config.get("RemotePort", "8080"))) print("[{bot_username}] Started: {now:%d.%m.%Y %H:%M:%S}".format(
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('bear.bot1', 'a7343fdc-e454-4b05-83d2-70fc8bb531f7') # 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='https://38cc2287.ngrok.io/')) app = KikBot(kik, __name__) app.run(port=9999, host='localhost', debug=True) #app.run(port=4040, host='127.0.0.1')
from datetime import datetime #****************************************# from kik import KikApi, Configuration from kik.messages import (LinkMessage, SuggestedResponseKeyboard, TextMessage, TextResponse, messages_from_json) #**********************************************************# # // Kik Bot Authentication globals #**********************************************************# BOT_USERNAME = os.environ.get('BOT_USERNAME', 'rant.ai') BOT_API_KEY = os.environ.get('BOT_API_KEY', 'baf16ad1-d654-4a29-9db8-a24a811a8ebb') BOT_WEBHOOK = os.environ.get('BOT_WEBHOOK', 'https://rant-ai-kik-bot.herokuapp.com/incoming') app = Flask(__name__) kik = KikApi(BOT_USERNAME, BOT_API_KEY) kik.set_configuration(Configuration(webhook=BOT_WEBHOOK)) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['app.db'] app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) #**********************************************************# # // DB model to save messages #**********************************************************# class ChatRecord(db.Model): id = db.Column(db.Integer, primary_key=True) original = db.Column(db.Text) created_datetime = db.Column(db.DateTime, default=datetime.utcnow)
from MessageBuilder import MessageBuilder from flask import Flask, request, Response from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage, ReceiptMessage, ReadReceiptMessage, SuggestedResponseKeyboard, TextResponse, StartChattingMessage import os reset = False 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))
from flask import Flask, request, Response from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage, SuggestedResponseKeyboard, TextResponse, VideoMessage, StartChattingMessage, PictureMessage import getGiphy app = Flask(__name__) kik = KikApi('whatabot', '5c42b012-9000-4954-b03b-f62d89447c27') kik.set_configuration(Configuration(webhook='https://a570e0b8.ngrok.io/incoming')) @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: 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(