From e70e21381dfa0bca442513b01ecc83fc33cfdeaa Mon Sep 17 00:00:00 2001 From: Filipe Pina Date: Thu, 21 Jan 2016 10:51:58 +0000 Subject: [PATCH] simsimi plugin updated --- plugins/simsimi.py | 16 +++++++++++++--- tests/test_simsimi.py | 25 +++++++++++++++++++++---- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/plugins/simsimi.py b/plugins/simsimi.py index 48dc519..7a92bdb 100644 --- a/plugins/simsimi.py +++ b/plugins/simsimi.py @@ -4,16 +4,26 @@ class SimsimiPlugin(tgbot.TGPluginBase): + def __init__(self, key, trial_key=True): + super(SimsimiPlugin, self).__init__() + self._key = key + self._trial_key = trial_key + self._url = 'http://sandbox.api.simsimi.com/request.p' if trial_key else 'http://api.simsimi.com/request.p' + def simsimi(self, message, text): self.bot.send_chat_action(message.chat.id, ChatAction.TEXT) - res = requests.get('http://www.simsimi.com/requestChat', params={ + res = requests.get(self._url, params={ + 'key': self._key, 'lc': 'en', 'ft': '1.0', - 'req': text, + 'text': text, }).json() - self.bot.send_message(message.chat.id, res['res']['msg']) + if res['result'] == 100: + self.bot.send_message(message.chat.id, res['response']) + else: + self.bot.send_message(message.chat.id, 'Sorry, sleeping at the moment...') def chat(self, message, text): if not text: diff --git a/tests/test_simsimi.py b/tests/test_simsimi.py index bc2ac08..674c200 100644 --- a/tests/test_simsimi.py +++ b/tests/test_simsimi.py @@ -2,11 +2,16 @@ from tgbot import plugintest from tgbot.botapi import Update from plugins.simsimi import SimsimiPlugin +import os + +from requests.packages import urllib3 +urllib3.disable_warnings() class SimsimiPluginTest(plugintest.PluginTestCase): def setUp(self): - self.bot = self.fake_bot('', plugins=[], no_command=SimsimiPlugin()) + self._key = os.environ.get('SIMSIMI_KEY', '') + self.bot = self.fake_bot('', plugins=[], no_command=SimsimiPlugin(self._key)) self.received_id = 1 def receive_message(self, text, sender=None, chat=None): @@ -35,10 +40,22 @@ def receive_message(self, text, sender=None, chat=None): self.received_id += 1 def test_reply(self): - self.receive_message('hello') + # if no key configured, use mock + if not self._key: + import mock - # any reply will do... - self.last_reply(self.bot) + def fget(*args, **kwargs): + r = type('Test', (object,), {})() + r.json = lambda: {'result': 100, 'response': 'hello'} + return r + + with mock.patch('requests.get', fget): + self.receive_message('hello') + else: + self.receive_message('hello') + + # any reply will do except the error reply + self.assertNotEqual(self.last_reply(self.bot), 'Sorry, sleeping at the moment...') def test_no_reply(self): self.receive_message('')