Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simsimi and other extra features #41

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Binary file added audio.mp3
Binary file not shown.
Binary file added document.pdf
Binary file not shown.
Binary file added image.jpg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions lib/__init__.py
@@ -0,0 +1 @@
__author__ = 'Matteo'
46 changes: 46 additions & 0 deletions lib/language_codes.py
@@ -0,0 +1,46 @@
__author__ = 'Matteo'
LC_AFRIKAANS = "af"
LC_ARABIC = "ar"
LC_BULGARIAN = "bg"
LC_CATALAN = "ca"
LC_CHINESE_SIMPLIFIED = "ch"
LC_CZECH = "cs"
LC_CYMRAEG = "cy"
LC_DANSK = "da"
LC_DEUTSCH = "de"
LC_GREEK = "el"
LC_ENGLISH = "en"
LC_SPANISH = "es"
LC_EUSKARA = "eu"
LC_SUOMI = "fi"
LC_FRENCH = "fr"
LC_HEBREW = "he"
LC_HINDI = "hi"
LC_CROATIAN = "hr"
LC_HUNGARIAN = "hu"
LC_INDONESIAN = "id"
LC_ITALIANO = "it"
LC_JAPANESE = "ja"
LC_KHMER = "kh"
LC_KOREAN = "ko"
LC_LITHUANIAN = "lt"
LC_MALAYALAM = "ml"
LC_BAHASA_MELAYU = "ms"
LC_NORSK = "nb"
LC_NEDERLANDS = "nl"
LC_PUNJABI = "pa"
LC_FILIPINO = "ph"
LC_POLSKI = "pl"
LC_PORTUGUESE = "pt"
LC_ROMANIAN = "ro"
LC_SERBIAN = "rs"
LC_RUSSIAN = "ru"
LC_SLOVAK = "sk"
LC_SVENSKA = "sv"
LC_TAMIL = "ta"
LC_TELUGU = "te"
LC_THAI = "th"
LC_TURKISH = "tr"
LC_UKRAINIAN = "uk"
LC_TIENG_VIET = "vn"
LC_CHINESE_TRADITIONAL = "zh"
6 changes: 6 additions & 0 deletions lib/response_codes.py
@@ -0,0 +1,6 @@
__author__ = 'Matteo'
RESPONSE_OK = 100
RESPONSE_BAD_REQUEST = 400
RESPONSE_UNAUTHORIZED = 401
RESPONSE_NOT_FOUND = 404
RESPONSE_500 = 500
38 changes: 38 additions & 0 deletions lib/simsimi.py
@@ -0,0 +1,38 @@
__author__ = 'Matteo'
from language_codes import LC_ITALIANO
import urllib2, urllib, json
from response_codes import RESPONSE_OK


class SimSimiException(Exception):
pass


class SimSimi(object):
def __init__(self, *args, **kwargs):
self.conversation_request_url = kwargs.get('conversation_request_url',
'http://sandbox.api.simsimi.com/request.p')
self.conversation_key = kwargs.get('conversation_key', '')
self.conversation_language = kwargs.get('conversation_language', LC_ITALIANO)
self.conversation_filter = kwargs.get('conversation_filter', '0.0')

def getConversation(self, text):
requestParam = {
'key': self.conversation_key,
'lc': self.conversation_language,
'ft': self.conversation_filter,
'text': text
}

requestUrl = "%s?%s" % (self.conversation_request_url, urllib.urlencode(requestParam))
try:
response = urllib2.urlopen(requestUrl)
except urllib2.URLError as e:
print e
return
responseDict = json.loads(str(response.read()))

if responseDict['result'] != RESPONSE_OK:
raise SimSimiException("SimSimiException occured: %s" % responseDict['msg'])

return responseDict
100 changes: 86 additions & 14 deletions main.py
Expand Up @@ -59,7 +59,8 @@ def get(self):
urlfetch.set_default_fetch_deadline(60)
url = self.request.get('url')
if url:
self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'setWebhook', urllib.urlencode({'url': url})))))
self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'setWebhook',
urllib.urlencode({'url': url})))))


class WebhookHandler(webapp2.RequestHandler):
Expand All @@ -78,40 +79,68 @@ def post(self):
fr = message.get('from')
chat = message['chat']
chat_id = chat['id']

who = ['who are you', 'Who are you']
if not text:
logging.info('no text')
return

def reply(msg=None, img=None):
def reply(msg=None, img=None, audio=None, document=None, location=None):
if msg:
resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
'chat_id': str(chat_id),
'text': msg.encode('utf-8'),
'disable_web_page_preview': 'true',
'reply_to_message_id': str(message_id),
})).read()

elif img:
resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
('chat_id', str(chat_id)),
('reply_to_message_id', str(message_id)),
], [
('photo', 'image.jpg', img),
])

elif audio:
resp = multipart.post_multipart(BASE_URL + 'sendAudio', [
('chat_id', str(chat_id)),
('reply_to_message_id', str(message_id)),
], [
('audio', 'audio.mp3', audio),
])

elif document:
resp = multipart.post_multipart(BASE_URL + 'sendDocument', [
('chat_id', str(chat_id)),
('reply_to_message_id', str(message_id)),
], [
('document', 'document.pdf', document),
])

elif location:
resp = urllib2.urlopen(BASE_URL + 'sendLocation', urllib.urlencode({
'chat_id': str(chat_id),
'latitude': location[0],
'longitude': location[1],
'reply_to_message_id': str(message_id),
})).read()

else:
logging.error('no msg or img specified')
logging.error('no msg or action specified')
resp = None

logging.info('send response:')
logging.info(resp)

if text.startswith('/'):
if text == '/start':
reply('Bot enabled')
reply('Bot enabled ' + u'\U0001F60E' + ', digit /help to list all available commands')
setEnabled(chat_id, True)

elif text == '/stop':
reply('Bot disabled')
setEnabled(chat_id, False)

elif text == '/image':
img = Image.new('RGB', (512, 512))
base = random.randint(0, 16777216)
Expand All @@ -120,20 +149,63 @@ def reply(msg=None, img=None):
output = StringIO.StringIO()
img.save(output, 'JPEG')
reply(img=output.getvalue())
else:
reply('What command?')

# CUSTOMIZE FROM HERE
elif text == '/my_image':
img = Image.open('image.jpg')
output = StringIO.StringIO()
img.save(output, 'JPEG')
reply(img=output.getvalue())

elif text == '/audio':
audio_file = open('audio.mp3')
audio = audio_file.read()
reply(audio=audio)

elif text == '/pdf':
document_file = open('document.pdf')
document = document_file.read()
reply(document=document)

elif text == '/location':
location = [40.748817, -73.985428]
reply(location=location)

elif text == '/help':
reply('Hello '+fr['first_name']+' here you can control me by sending these commands:\n\n'
'/image: generate sample image\n/my_image: get custom image\n'
'/audio: get house sample\n/pdf: get sample document\n/location: get default location\n')
else:
reply('What command? Try /help')

elif 'who are you' in text:
reply('telebot starter kit, created by yukuku: https://github.com/yukuku/telebot')
elif any(s in text for s in who):
reply('My name is telegram_engine bot! nice to meet you '+fr['first_name']+'!')
elif 'what time' in text:
reply('look at the corner of your screen!')
reply('look at the top of your screen! ' + u'\U0001F51D')
else:
if getEnabled(chat_id):
reply('I got your message! (but I do not know how to answer)')
# coding: utf-8
from lib.simsimi import SimSimi
from lib.language_codes import LC_ENGLISH
from lib.simsimi import SimSimiException

back = ""
simSimi = SimSimi(conversation_language=LC_ENGLISH,
conversation_key='YOUR_SIMSIMI_TOKEN')

try:
from unicodedata import normalize
text = normalize('NFKD', text).encode('ASCII', 'ignore')
response = simSimi.getConversation(text)
if not response['response']:
reply('You exceeded simsimi api daily limit!')
back = response['response']
except SimSimiException as e:
print e
if not back:
reply('Something went wrong..')
elif 'I HAVE NO RESPONSE' in back:
reply('you said something with no meaning')
else:
logging.info('not enabled for chat_id {}'.format(chat_id))
reply(back)


app = webapp2.WSGIApplication([
Expand Down