示例#1
0
import os
import telebot
import time
import random
import threading
from telebot import types
from pymongo import MongoClient
import traceback
import apiai, json
from api.ai import Agent

token = ''
bot = telebot.TeleBot(token)

neiro = apiai.ApiAI('')
parent = ''

agent = Agent(
    'cipraded',
    '',
    '',
)

training = False
teachers = [268486177, 792414733, 441399484]


@bot.message_handler(commands=['train'])
def ctrain(m):
    pass
示例#2
0
文件: app.py 项目: popomilk/superAPI
from MessageForm import *
from Ten_Carousel import *

#AI自然語言分析(DialogFlow)
import apiai

#Google表單
import sys
import datetime
import gspread
from oauth2client.service_account import ServiceAccountCredentials as SAC

app = Flask(__name__)

#LINEAPI認證
ai = apiai.ApiAI('084bce6e157c47d39d5cb23715b47b69')
line_bot_api = LineBotApi(
    'TNwu7tqho7m8MnMSmG8jpAF8tWl+hzBQzb/JKdbDBJv3HkMAUJiz8uo0nS0hG89tbsjQk8IV02p/v5ChZ1txRKjMlvPufgBPak5Y5AEwJt84wc9Mocg+yeZ8oyRQcfwFKnfmNaNRJR27Qc9r6iY38AdB04t89/1O/w1cDnyilFU='
)
handler = WebhookHandler('d184dfc3ec38e22fb7edf6b7275023a8')

static_tmp_path = os.path.join(os.path.dirname(__file__), 'static', 'tmp')


# 監聽所有來自 /callback 的 Post Request
@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']
    # get request body as text
    body = request.get_data(as_text=True)
示例#3
0
import os.path
import sys
import json
import speech_recognition as sr
#import win32com.client

try:
    import apiai
except ImportError:
    sys.path.append(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

r = sr.Recognizer()
CLIENT_ACCESS_TOKEN = '2c087495015448aabb887b153f6e81fd'
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
#speaker = win32com.client.Dispatch("SAPI.SpVoice")


def say(words):
    print('Robot Say: ' + words)  # Represent robot 'say' function
    #speaker.Speak(words)


class Speech():
    def __init__(self):
        self.interrupt_intents = [
            'GoWashroom'
        ]  # List of interruption events. Now it only contains goWashroom.
        self.guest_bot = 'name'
        self.name_bot = ''
        self.response = ''
示例#4
0
 def __init__(self):
     self.ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
示例#5
0
def handle_command(message):
    print("text2")

    if obj.xs == 1:
        if obj.count == 0:
            des = message.text
            newt.setDes(des)
            obj.count += 1
            bot.send_message(message.from_user.id, "Enter required number of performed tasks")
        elif obj.count == 1:
            fer = int(message.text)
            newt.setReq(fer)
            obj.count += 1
            bot.send_message(message.from_user.id, "Enter priority as digit(1(lowest priority)-10(highest priority))")
        elif obj.count == 2:
            prior = int(message.text)
            newt.setPrior(prior)
            obj.count += 1
            bot.send_message(message.from_user.id, "Is this for special person?(enter answer and id of holder)")
        elif obj.count == 3:
            obj.cur = None
            text = message.text
            if text.lower().find('yes') != -1 or text.lower() == "y":
                textList = text.split(" ")
                zip = int(textList[1])
                newt.setHolderId(zip)
                newt.setNum(0)
                newt.setId(obj.ids())
                Tas.append(Tasks().create(newt))
            else:
                for z in Sta:
                    id = new_id(Sta)
                    if z.depid == obj.cur.depid:
                        newt.setDepId(0)
                        newt.setNum(0)
                        newt.setId(id)
                        newt.setHolderId(0)
                        Tas.append(Tasks().create(newt))
            with open('tasks.dat', "wb") as file:
                pickle.dump(Tas, file)
            task_buttons(message)

    elif obj.xs == 2:
        dele = int(message.text)
        for t in Tas:
            if t.id == dele:
                Tas.remove(t)
        with open('tasks.dat', "wb") as file:
            pickle.dump(Tas, file)
        task_buttons(message)

    else:
        if message.text == "/Client":
            client(message)

        elif message.text == "/Stuff":
            stuff(message)

        elif message.text == "/Admin":
            admin(message)

        elif message.text.lower() == "займи мне место":
            myQueue = bq.take_queue(message.from_user.id)
            t1 = threading.Thread(target=bq.live, args=(myQueue, message.from_user.id))
            t1.start()

        elif message.text.lower() == "покажи водителя":
            driver = get_driver()
            bot.send_message(message.from_user.id, "Driver:")
            bot.send_message(message.from_user.id, "name: {}".format(driver['name']))
            bot.send_message(message.from_user.id, "surname: {}".format(driver['surname']))
            bot.send_message(message.from_user.id, "age: {}".format(driver['age']))
            bot.send_message(message.from_user.id, "Driver class: {}".format(driver['dr_class']))

        elif message.text.lower() == "покажи мои билеты":
            mytickets = get_tickets()
            for t in mytickets:
                bot.send_message(message.from_user.id, "Booked seat:{}".format(t['sid']))
                bot.send_message(message.from_user.id, "source: {}".format(t['source']))
                bot.send_message(message.from_user.id, "destination: {}".format(t['destination']))
                bot.send_message(message.from_user.id, "leaving time: {}".format(t['ltime']))
                bot.send_message(message.from_user.id, "arrival time: {}".format(t['atime']))
                bot.send_message(message.from_user.id, "Driver: {}".format(t['driver']))
                bot.send_message(message.from_user.id, "Bus: {}".format(t['bus']))

        elif message.text.lower() == "покажи автобус":
            bus = get_bus()
            bot.send_message(message.from_user.id, "Bus:{}".format(bus['id']))
            bot.send_message(message.from_user.id, "Mark: {}".format(bus['mark']))
            bot.send_message(message.from_user.id, "Year: {}".format(bus['year']))
            bot.send_message(message.from_user.id, "Amount of seats: {}".format(bus['seats']))

        elif message.text.lower() == "покажи расписание":
            schedule = get_schedule()
            myQueue = bq.take_queue(message.from_user.id)
            bot.send_message(message.from_user.id, "Schedule")
            bot.send_message(message.from_user.id, "id:{}".format(schedule['id']))
            bot.send_message(message.from_user.id, "source: {}".format(schedule['source']))
            bot.send_message(message.from_user.id, "destination: {}".format(schedule['destination']))
            bot.send_message(message.from_user.id, "Bus: {}".format(schedule['bus']))
            bot.send_message(message.from_user.id, "Driver: {}".format(schedule['driver']))

        elif message.text.lower().find("купи билеты") is not -1 or message.text.lower().find("купить билеты") is not -1:
            msg = message.text.lower()
            global busid
            busid = 0
            seats = []
            isFirst = True
            for str in msg.split():
                if str.isdigit():
                    if isFirst:
                        busid = int(str)
                        break
                    else:
                        seats.append(int(str))

            bseats, sid = bus_bus_ticket(busid, seats)
            if bseats is None:
                print("Life is good")
                bot.send_message(chat_id=message.from_user.id, text="Дело сделано!")
            else:
                str = "Unfortunately, these seats are occupied already: "
                for bs in bseats:
                    str += bs + " "
                if len(seats) > len(bseats):
                    str += "But I have booked the rest"
                bot.send_message(chat_id= message.from_user.id, text= str)

            msg = "Here are the seats of bus: {}\n".format(busid)
            ss = get_seats(sid)
            for s in range(0, len(ss)):
                key = False
                if s[0] == 1:
                    key = True
                msg += "id: {} booked: {}\n".format(s[0], key)

            bot.send_message(chat_id=message.from_user.id, text=msg)

        else:
            # bot.send_message(message.from_user.id, message.text)

            request = apiai.ApiAI('b9c84a1d9d2d4626884a0033964085d4').text_request()  # Токен API к Dialogflow
            request.lang = 'ru'  # На каком языке будет послан запрос
            request.session_id = 'AIYAv1'  # ID Сессии диалога (нужно, чтобы потом учить бота)
            request.query = message.text  # Посылаем запрос к ИИ с сообщением от юзера...
            responseJson = json.loads(request.getresponse().read().decode('utf-8'))
            response = responseJson['result']['fulfillment']['speech']  # Разбираем JSON и вытаскиваем ответ
            # Если есть ответ от бота - присылаем юзеру, если нет - бот его не понял
            if response:
                bot.send_message(chat_id= message.from_user.id, text=response)
            else:
                bot.send_message(chat_id=message.from_user.id, text='Я Вас не совсем поняла!')
示例#6
0
 def __init__(self):
     self.token = 'e677f19897554756861dd69150c87d58'  # faq client
     self.ai = apiai.ApiAI(self.token)
     self.session_id = ''
示例#7
0
文件: bot.py 项目: ausaleh/chatbot
 def apiaiCon(self):
     self.CLIENT_ACCESS_TOKEN = ""
     self.ai = apiai.ApiAI(self.CLIENT_ACCESS_TOKEN)
     self.request = self.ai.text_request()
     self.request.lang = 'de'  #Default : English
     self.request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"
    def handle_message(event):
        # 連ALTAS
        userId = event.source.user_id
        client = pymongo.MongoClient("mongodb+srv://edison:[email protected]/test?retryWrites=true&w=majority") 
        db = client.data
        collection = db.user
        condition = {'userId': userId}
        user = collection.find_one(condition)

        text = event.message.text
        language = 'zh-TW'
        country = translate_text(text,"auto","en")# 防止系統以為簡體轉繁體產生error,先轉成en
        if (country.get('SourceLanguageCode') == "zh"):  
            zh_text = country.get('TranslatedText')
            text = translate_text(zh_text,"en","zh-TW").get('TranslatedText')
        else:
            result = translate_text(text,"auto","zh-TW")  # 轉成中文
            language = result.get('SourceLanguageCode') #偵測使用者語言
            text = result.get('TranslatedText')
            print('SourceLanguageCode: ' + language)
        print('TranslatedText: ' + text)
        
        if text == "餐廳":
            print(event.message.text)
            # user沒資料
            if user == None or user['lat'] == None:
                language = "zh-TW"
                if user:
                    language = user['lan']

                relocation = {
                    'zh-TW' : 'https://i.imgur.com/Mu3OmsY.jpg',
                    'en' : 'https://imgur.com/QPeSsju.jpg',
                    'ja' : 'https://imgur.com/MjuLXTe.jpg',
                    'ko' : 'https://imgur.com/2uu74Xs.jpg'
                }.get(user['lan'], None)

                # 給予定位
                bubble1 = BubbleContainer(
                    direction='ltr',
                    hero=ImageComponent(
                        url=relocation,
                        size='full',
                        aspect_ratio='5:1',
                        aspect_mode='fit',
                        action=URIAction(uri='line://nv/location', label='label')
                    ),
                )
                message1 = FlexSendMessage(alt_text="hello", contents=bubble1)
                line_bot_api.reply_message(
                    event.reply_token, [TextSendMessage(text=trans_txt("資料庫沒有你的位置資料,請重新定位位置喔!",language).get('TranslatedText')), message1])

            else:  # user有資料
                # 拿user經緯度
                lat = user['lat']
                lng = user['lng']
                print(lat)
                print(lng)
                # 離user最近的五筆推薦
                res = getRestuarantsByPref(user['preference'],[lng,lat])
                
                #print(res)
                #######這裡要改,沒有網址跟地址
                def getphoto(name,lat,lng):###拿照片METHOD
                    restaurantSearch ="https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=AIzaSyCkzX3dPU0ny5Y7iyxIvoY6uDGS77Qelj0&location={},{}&rankby=distance&type=restaurant&language=zh-TW".format(lat,lng)
                    restaurantReq = requests.get(restaurantSearch)
                    restaurant_dict = restaurantReq.json()
                    newname=name.split(' - ')
                    
                    photoReference=''
                    photoWidth=''
                    address='無地址'
                    for i in range(len(restaurant_dict)):
                        if newname[0] in str(restaurant_dict['results'][i]['name']) :
                            try:
                                photoReference= restaurant_dict['results'][i]['photos'][0]['photo_reference']
                            except:
                                photoReference=''
                            try:
                                photoWidth=restaurant_dict['results'][i]['photos'][0]['width']
                            except:
                                photoWidth=''
                            try:  
                                address=restaurant_dict['results'][i]['vicinity']
                            except:
                                address='無地址'
                    if photoReference=='':
                        thumbnailImageUrl ="https://imgur.com/XWtpbnt.jpg"
                    else:
                        thumbnailImageUrl = "https://maps.googleapis.com/maps/api/place/photo?key=AIzaSyCkzX3dPU0ny5Y7iyxIvoY6uDGS77Qelj0&photoreference={}&maxwidth={}".format(photoReference,photoWidth)                
                    return thumbnailImageUrl,address,newname[0]

                bubble_list = list(map(lambda i: RestuarantBubble(
                    name=trans_txt((getphoto(i['title'],i['location']['lat'],i['location']['lng'])[2]),user['lan']).get('TranslatedText'), 
                    address=trans_txt((getphoto(i['title'],i['location']['lat'],i['location']['lng'])[1]),user['lan']).get('TranslatedText'), 
                    time="10:00 - 23:00", 
                    ##image="https://i.imgur.com/TwKsV8T.jpg",
                    image=getphoto(i['title'],i['location']['lat'],i['location']['lng'])[0],  
                    website="https://example.com",
                    lat=i['location']['lat'],
                    lng=i['location']['lng'], 
                    lan = user['lan'],
                    rating=i['rating']), res))
                
            

                #print(bubble_list)
                carousel = CarouselContainer(contents=bubble_list)

                #######這裡要改
                newBubble = BubbleContainer(
                    body=BoxComponent(
                        layout='vertical',
                        contents=[
                            TextComponent(text=trans_txt('需要更詳細的推薦嗎?',user['lan']).get('TranslatedText')),
                            ButtonComponent(action=URIAction(uri='line://nv/location',text=trans_txt('重新定位',user['lan']).get('TranslatedText'), label=trans_txt('重新定位',user['lan']).get('TranslatedText'))),
                            ButtonComponent(action=URIAction(uri='https://access.line.me/oauth2/v2.1/authorize?response_type=code&client_id=1606988072&redirect_uri=https://lineloginscu.herokuapp.com/&state=abcde&scope=openid%20profile',text=trans_txt('重新設定喜好',user['lan']).get('TranslatedText'), label=trans_txt('重新設定喜好',user['lan']).get('TranslatedText')))
                        ]
                    )
                )

                # 轉成使用者輸入的語言回覆

                line_bot_api.reply_message(event.reply_token, [
                    TextSendMessage(text=trans_txt('讓我來推薦你附近餐廳~',user['lan']).get('TranslatedText')),
                    FlexSendMessage(alt_text=trans_txt("推薦餐廳",user['lan']).get('TranslatedText'), contents=carousel),
                    FlexSendMessage(alt_text=trans_txt("額外設定",user['lan']).get('TranslatedText'), contents=newBubble)
                ])

        elif text == '住宿' or event.message.text == '宿泊施設':
            print(event.message.text)
            def getphoto(name,lat,lng):###拿照片METHOD
                    restaurantSearch ="https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=AIzaSyCkzX3dPU0ny5Y7iyxIvoY6uDGS77Qelj0&location={},{}&rankby=distance&language=zh-TW".format(lat,lng)
                    restaurantReq = requests.get(restaurantSearch)
                    restaurant_dict = restaurantReq.json()
                    newname=name.split(' - ')
                    
                    photoReference=''
                    photoWidth=''
                    address='無地址'
                    for i in range(len(restaurant_dict)):
                        if newname[0] in str(restaurant_dict['results'][i]['name']) or newname[0] == str(restaurant_dict['results'][i]['name']) or str(restaurant_dict['results'][i]['name'])  in newname[0]  :
                            try:
                                photoReference= restaurant_dict['results'][i]['photos'][0]['photo_reference']
                            except:
                                photoReference=''
                            try:
                                photoWidth=restaurant_dict['results'][i]['photos'][0]['width']
                            except:
                                photoWidth=''
                            try:  
                                address=restaurant_dict['results'][i]['vicinity']
                            except:
                                address='無地址'
                    if photoReference=='':
                        thumbnailImageUrl ="https://imgur.com/I9zmjwp.jpg"
                    else:
                        thumbnailImageUrl = "https://maps.googleapis.com/maps/api/place/photo?key=AIzaSyCkzX3dPU0ny5Y7iyxIvoY6uDGS77Qelj0&photoreference={}&maxwidth={}".format(photoReference,photoWidth)                
                    return thumbnailImageUrl,address,newname[0]
            # user沒資料
            if(user == None or user['lat'] == None):
                language = "zh-TW"
                if user:
                    language = user['lan']

                relocation = {
                    'zh-TW' : 'https://i.imgur.com/Mu3OmsY.jpg',
                    'en' : 'https://imgur.com/QPeSsju.jpg',
                    'ja' : 'https://imgur.com/MjuLXTe.jpg',
                    'ko' : 'https://imgur.com/2uu74Xs.jpg'
                }.get(user['lan'], None)

                # 給予定位
                bubble1 = BubbleContainer(
                    direction='ltr',
                    hero=ImageComponent(
                        url=relocation,
                        size='full',
                        aspect_ratio='5:1',
                        aspect_mode='fit',
                        action=URIAction(uri='line://nv/location', label='label')
                    ),
                )
                message1 = FlexSendMessage(alt_text=trans_txt("資料庫沒有你的位置資料,請重新定位位置喔!",language).get('TranslatedText'), contents=bubble1)
                line_bot_api.reply_message(
                    event.reply_token, [TextSendMessage(text=trans_txt("資料庫沒有你的位置資料,請重新定位位置喔!",language).get('TranslatedText')), message1])

            else:  # user有資料
                # 拿user經緯度
                lat = user['lat']
                lng = user['lng']
                print(lat)
                print(lng)
                # 離user最近的五筆推薦
                lodging = client.data.lodging_tag
                lodging.ensure_index([('location', '2d')])
                res = lodging.find({"location": {"$near": [lat, lng]}}).limit(5)

                # build bubble list
                bubble_list = list(map(lambda i: LodgingBubble(
                    name=trans_txt((getphoto(i['title'],i['location']['lat'],i['location']['lng'])[2]),user['lan']).get('TranslatedText'), 
                    address=trans_txt((getphoto(i['title'],i['location']['lat'],i['location']['lng'])[1]),user['lan']).get('TranslatedText'), 
                    lat=i['location']['lat'],
                    lng=i['location']['lng'],
                    lan=user['lan'],
                    picture=getphoto(i['title'],i['location']['lat'],i['location']['lng'])[0], 
                ), res))
                
                
                
                carousel = CarouselContainer(contents=bubble_list)

                line_bot_api.reply_message(event.reply_token, [TextSendMessage(text=trans_txt("讓我來推薦你附近住宿~",user['lan']).get('TranslatedText')),
                                                            FlexSendMessage(alt_text=trans_txt("讓我來推薦你附近住宿~",user['lan']).get('TranslatedText'), contents=carousel)])

        elif text == '活動' or event.message.text == '활동에 참여할 수 있습니다' :
            print(event.message.text)
            # user沒資料
            if user == None or user['lat'] == None:
                language = "zh-TW"
                if user:
                    language = user['lan']

                relocation = {
                    'zh-TW' : 'https://i.imgur.com/Mu3OmsY.jpg',
                    'en' : 'https://imgur.com/QPeSsju.jpg',
                    'ja' : 'https://imgur.com/MjuLXTe.jpg',
                    'ko' : 'https://imgur.com/2uu74Xs.jpg'
                }.get(user['lan'], None)
                # 給予定位
                bubble1 = BubbleContainer(
                    direction='ltr',
                    hero=ImageComponent(
                        url='https://i.imgur.com/Mu3OmsY.jpg',
                        size='full',
                        aspect_ratio='5:1',
                        aspect_mode='fit',
                        action=URIAction(uri='line://nv/location', label='label')
                    ),
                )
                message1 = FlexSendMessage(alt_text=trans_txt("資料庫沒有你的位置資料,請重新定位位置喔!",language).get('TranslatedText'), contents=bubble1)
                line_bot_api.reply_message(
                    event.reply_token, [TextSendMessage(text=trans_txt("資料庫沒有你的位置資料,請重新定位位置喔!",language).get('TranslatedText')), message1])

            else:  # user有資料
                # 拿user經緯度
                lat = user['lat']
                lng = user['lng']
                print(lat)
                print(lng)
                # 離user最近的五筆推薦
                activity = client.data.activity_data
                activity.ensure_index([('location', '2d')])
                res = activity.find({"location": {"$near": [lat, lng]}}).limit(5)

                # build bubble list
                bubble_list = list(map(lambda i: ActivityBubble(
                    name=trans_txt(i['name'],user['lan']).get('TranslatedText'), 
                    address=trans_txt((i['Add']or "無地址"),user['lan']).get('TranslatedText'), 
                    lat=i['location']['lat'],
                    lng=i['location']['lng'], 
                    lan=user['lan'],
                    picture=checkUrl(i['Picture']), 
                    website=i['Website']or "https://www.google.com/search?q={searchname}".format(searchname=i['name'])
                    ), res))
                
                carousel = CarouselContainer(contents=bubble_list)

                line_bot_api.reply_message(event.reply_token, [TextSendMessage(text=trans_txt("讓我來推薦你附近活動~",user['lan']).get('TranslatedText')),
                                                            FlexSendMessage(alt_text=trans_txt("讓我來推薦你附近活動~",user['lan']).get('TranslatedText'), contents=carousel)])

        elif text == '景點' or event.message.text == '観光名所':
            print(event.message.text)
            # user沒資料
            if user == None or user['lat'] == None:
                language = "zh-TW"
                if user:
                    language = user['lan']

                relocation = {
                    'zh-TW' : 'https://i.imgur.com/Mu3OmsY.jpg',
                    'en' : 'https://imgur.com/QPeSsju.jpg',
                    'ja' : 'https://imgur.com/MjuLXTe.jpg',
                    'ko' : 'https://imgur.com/2uu74Xs.jpg'
                }.get(user['lan'], None)
                bubble1 = BubbleContainer(
                    direction='ltr',
                    hero=ImageComponent(
                        url='https://i.imgur.com/Mu3OmsY.jpg',
                        size='full',
                        aspect_ratio='5:1',
                        aspect_mode='fit',
                        action=URIAction(uri='line://nv/location', label='label')
                    ),
                )
                message1 = FlexSendMessage(alt_text=trans_txt("資料庫沒有你的位置資料,請重新定位位置喔!",language).get('TranslatedText'), contents=bubble1)
                line_bot_api.reply_message(
                    event.reply_token, [TextSendMessage(text=trans_txt("資料庫沒有你的位置資料,請重新定位位置喔!",language).get('TranslatedText')), message1])
            else:
                lat = user['lat']
                lng = user['lng']
                print(lat)
                print(lng)

                scenic_spot = client.data.scenic_spot
                scenic_spot.ensure_index([('location', '2d')])
                res = scenic_spot.find(
                    {"location": {"$near": [lng, lat]}}).limit(5)
                
                def getphoto(name,lat,lng,add):
                    restaurantSearch ="https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=AIzaSyCkzX3dPU0ny5Y7iyxIvoY6uDGS77Qelj0&location={},{}&rankby=distance&locationbias=circle:20000&language=zh-TW".format(lat,lng)
                    restaurantReq = requests.get(restaurantSearch)
                    restaurant_dict = restaurantReq.json()
                
                
                    photoReference=''
                    photoWidth=''
                    for i in range(len(restaurant_dict)):
                        if str(restaurant_dict['results'][i]['name']) in name or name in str(restaurant_dict['results'][i]['name']) :
                            try: 
                                photoReference= restaurant_dict['results'][i]['photos'][0]['photo_reference']
                                photoWidth=restaurant_dict['results'][i]['photos'][0]['width']
                            except:
                                photoReference=''

                        elif add in str(restaurant_dict['results'][i]['vicinity']) or str(restaurant_dict['results'][i]['vicinity']) in add:
                            try: 
                                photoReference= restaurant_dict['results'][i]['photos'][0]['photo_reference']
                                photoWidth=restaurant_dict['results'][i]['photos'][0]['width']
                            except:
                                photoReference=''  
                            break
                            
                    if photoReference=='':
                        thumbnailImageUrl ="https://imgur.com/PzggTWr.jpg"
                    else:
                        thumbnailImageUrl = "https://maps.googleapis.com/maps/api/place/photo?key=AIzaSyCkzX3dPU0ny5Y7iyxIvoY6uDGS77Qelj0&photoreference={}&maxwidth={}".format(photoReference,photoWidth)                
                    return thumbnailImageUrl
                
                
                bubble_list = list(map(lambda i: ScenicSpotBubble(
                    name=trans_txt(i['name'],user['lan']).get('TranslatedText'),
                    address=trans_txt(i['Add'],user['lan']).get('TranslatedText'),
                    description=trans_txt((i['Description']or "無敘述"),user['lan']).get('TranslatedText') ,
                    lat=i['location']['lat'],
                    lng=i['location']['lng'],
                    lan=user['lan'],
                    mapurl='https://www.google.com/maps/search/?api=1&query=TASTY西堤牛排中和板南店',
                    image=getphoto(i['name'],i['location']['lat'],i['location']['lng'],i['Add']),
                ), res))

                carousel = CarouselContainer(contents=bubble_list)
                #print(carousel)
                line_bot_api.reply_message(event.reply_token, [TextSendMessage(text=trans_txt("讓我來推薦你附近景點~",user['lan']).get('TranslatedText')),
                                                            FlexSendMessage(alt_text=trans_txt("讓我來推薦你附近景點~",user['lan']).get('TranslatedText'), contents=carousel)])

        elif text == '登入':
            line_bot_api.reply_message(event.reply_token, TextSendMessage(
                text=f"https://access.line.me/oauth2/v2.1/authorize?response_type=code&client_id={os.environ.get('LOGIN_ID')}&redirect_uri={os.environ.get('LOGIN_REDIRECT')}&state=abcde&scope=openid%20profile"))

        elif text == "定位":
            message = TemplateSendMessage(
                alt_text='Confirm template',
                template=ConfirmTemplate(
                    text=trans_txt('是否要修改定位?',user['lan']).get('TranslatedText'),
                    actions=[
                        PostbackTemplateAction(
                            label='postback',
                            text='postback text',
                            data='action=buy&itemid=1'
                        ),
                        URITemplateAction(
                            label='location',
                            uri='line://nv/location'
                        )
                    ]
                )
            )
            line_bot_api.reply_message(event.reply_token, message)

        elif text == "選單" or text == "功能表" or text == "從選單中選取" or text == "選擇菜單":
            # user沒資料
            if user == None:
                bubble = BubbleContainer(
                    direction='ltr',
                    body=BoxComponent(
                        layout='vertical',
                        contents=[
                            # title
                            TextComponent(text='功能推薦 / Recommendations', weight='bold', size='lg'),
                        ],
                    ),
                    footer=BoxComponent(
                        layout='vertical',
                        spacing='xs',
                        contents=[
                        # first row
                        BoxComponent(
                            layout='horizontal',
                            spacing='xs',
                            contents=[
                                # callAction, separator, websiteAction
                                SpacerComponent(size='sm'),
                                # callAction
                                ImageComponent(
                                    url='https://i.imgur.com/3lDSAzf.jpg',
                                    size='full',
                                    aspect_ratio='20:13',
                                    aspect_mode='cover',
                                    action=MessageAction(label='餐廳', text='餐廳')
                                ),

                                # separator
                                SeparatorComponent(),
                                # websiteAction
                                ImageComponent(
                                    url='https://i.imgur.com/Du2ZFZW.jpg',
                                    size='full',
                                    aspect_ratio='20:13',
                                    aspect_mode='cover',
                                    action=MessageAction(label='住宿', text='住宿')
                                )
                            ]
                        ),
                        # second row
                        BoxComponent(
                            layout='horizontal',
                            spacing='xs',
                            contents=[
                                # callAction, separator, websiteAction
                                SpacerComponent(size='sm'),
                                # callAction
                                ImageComponent(
                                    url='https://i.imgur.com/3QOwxjC.jpg',
                                    size='full',
                                    aspect_ratio='20:13',
                                    aspect_mode='cover',
                                    action=MessageAction(label='景點', text='景點')
                                ),
                                # separator
                                SeparatorComponent(),
                                # websiteAction
                                ImageComponent(
                                    url='https://i.imgur.com/N0u3MbN.jpg',
                                    size='full',
                                    aspect_ratio='20:13',
                                    aspect_mode='cover',
                                    action=MessageAction(label='活動', text='活動')
                                )
                            ]
                        ),
                        ]
                    ),
                )
                message = FlexSendMessage(alt_text="hello", contents=bubble)

                #重新定位
                bubble1 = BubbleContainer(
                    direction='ltr',
                    hero=ImageComponent(
                        url='https://i.imgur.com/Mu3OmsY.jpg',
                        size='full',
                        aspect_ratio='5:1',
                        aspect_mode='fit',
                        action=URIAction(uri='line://nv/location', label='label')
                    ),
                )
                message1 = FlexSendMessage(alt_text="hello", contents=bubble1)
                line_bot_api.reply_message(event.reply_token, [message, message1])
            else:
                fuctiontxt = { 
                    'zh-TW' : '功能推薦 / Recommendations',
                    'en' : 'Recommendations',
                    'ja' : '機能に関する推奨事項',
                    'ko' : '기능 권장 사항'
                }.get(user['lan'], None)

                #圖片更改
                pic_res = {
                    'zh-TW' : 'https://i.imgur.com/3lDSAzf.jpg',
                    'en' : 'https://imgur.com/XWtpbnt.jpg',
                    'ja' : 'https://imgur.com/MBLOIcK.jpg',
                    'ko' : 'https://imgur.com/504X61v.jpg'
                }.get(user['lan'], None)
                pic_hotel = {
                    'zh-TW' : 'https://i.imgur.com/Du2ZFZW.jpg',
                    'en' : 'https://imgur.com/I9zmjwp.jpg',
                    'ja' : 'https://imgur.com/xdTwSAc.jpg',
                    'ko' : 'https://imgur.com/dgRSNO8.jpg'
                }.get(user['lan'], None)
                pic_act = {
                    'zh-TW' : 'https://i.imgur.com/N0u3MbN.jpg',
                    'en' : 'https://imgur.com/FfiIWot.jpg',
                    'ja' : 'https://imgur.com/JErghGx.jpg',
                    'ko' : 'https://imgur.com/ZXHNLFp.jpg'
                }.get(user['lan'], None)
                pic_spot = {
                    'zh-TW' : 'https://i.imgur.com/3QOwxjC.jpg',
                    'en' : 'https://imgur.com/PzggTWr.jpg',
                    'ja' : 'https://imgur.com/5y1Ba1P.jpg',
                    'ko' : 'https://imgur.com/uoDvVLR.jpg'
                }.get(user['lan'], None)
                #功能推薦
                bubble = BubbleContainer(
                    direction='ltr',
                    body=BoxComponent(
                        layout='vertical',
                        contents=[
                        # title
                            TextComponent(text=fuctiontxt, weight='bold', size='lg'),
                        ],
                    ),
                    footer=BoxComponent(
                        layout='vertical',
                        spacing='xs',
                        contents=[
                        # first row

                        BoxComponent(
                            layout='horizontal',
                            spacing='xs',
                            contents=[
                                # callAction, separator, websiteAction
                                SpacerComponent(size='sm'),
                                # callAction
                                ImageComponent(
                                    url=pic_res,
                                    size='full',
                                    aspect_ratio='20:13',
                                    aspect_mode='cover',
                                    action=MessageAction(label=trans_txt('餐廳',user['lan']).get('TranslatedText'), text=trans_txt('餐廳',user['lan']).get('TranslatedText'))
                                ),

                                # separator
                                SeparatorComponent(),
                                # websiteAction
                                ImageComponent(
                                    url=pic_hotel,
                                    size='full',
                                    aspect_ratio='20:13',
                                    aspect_mode='cover',
                                    action=MessageAction(label=trans_txt('住宿',user['lan']).get('TranslatedText'), text=trans_txt('住宿',user['lan']).get('TranslatedText'))
                                )
                            ]
                        ),
                        # second row
                        BoxComponent(
                            layout='horizontal',
                            spacing='xs',
                            contents=[
                                # callAction, separator, websiteAction
                                SpacerComponent(size='sm'),
                                # callAction
                                ImageComponent(
                                    url=pic_spot,
                                    size='full',
                                    aspect_ratio='20:13',
                                    aspect_mode='cover',
                                    action=MessageAction(label=trans_txt('景點',user['lan']).get('TranslatedText'), text=trans_txt('景點',user['lan']).get('TranslatedText'))
                                ),
                                # separator
                                SeparatorComponent(),
                                # websiteAction
                                ImageComponent(
                                    url=pic_act,
                                    size='full',
                                    aspect_ratio='20:13',
                                    aspect_mode='cover',
                                    action=MessageAction(label=trans_txt('活動',user['lan']).get('TranslatedText'), text=trans_txt('活動',user['lan']).get('TranslatedText'))
                                )
                            ]
                        ),
                        ]
                    ),
                )
                message = FlexSendMessage(alt_text="hello", contents=bubble)

                relocation = {
                    'zh-TW' : 'https://i.imgur.com/Mu3OmsY.jpg',
                    'en' : 'https://imgur.com/QPeSsju.jpg',
                    'ja' : 'https://imgur.com/MjuLXTe.jpg',
                    'ko' : 'https://imgur.com/2uu74Xs.jpg'
                }.get(user['lan'], None)
                #重新定位
                bubble1 = BubbleContainer(
                    direction='ltr',
                    hero=ImageComponent(
                        url=relocation,
                        size='full',
                        aspect_ratio='5:1',
                        aspect_mode='fit',
                        action=URIAction(uri='line://nv/location', label='label')
                    ),
                )
                message1 = FlexSendMessage(alt_text="hello", contents=bubble1)
                line_bot_api.reply_message(event.reply_token, [message, message1])

        elif text == "語言":
            newbubble = BubbleContainer(
                body=BoxComponent(layout='vertical', contents=[
                    TextComponent(text='語言 / Language / 言語 / 언어 / язык'),
                    ButtonComponent(action=MessageAction(
                        label='中文', text='中文')),
                    ButtonComponent(action=MessageAction(
                        label='English', text='English')),
                    ButtonComponent(action=MessageAction(
                        label='日本語', text='日本語')),
                    ButtonComponent(action=MessageAction(
                        label='한국어', text='한국어')),
                ]))

            line_bot_api.reply_message(event.reply_token, FlexSendMessage(
                alt_text="語言設定", contents=newbubble))

        elif text == "中文" or text == "英語" or text == "日本語" or text == "韓國人":
            lan = { 
            '中文' : 'zh-TW',
            '英語' : 'en',
            '日本語' : 'ja',
            '韓國人' : 'ko',
            }.get(text, None)

            if (user != None):  # user有資料,更新
                print("NOT EMPTY")
                print("language = "+lan)
                user['lan'] = lan
                # print("user_lan="+str(user['lan']))
                collection.update_one(condition, {'$set': user})
            else:  # user沒有資料,新增
                print("EMPTY")
                userdict = {"userId": userId, "lat": None, "lng": None, "lan": lan, "preference": {"like": [], "ok": [], "dislike": []}}
                collection.insert_one(userdict)

            bubble1 = BubbleContainer(
                direction='ltr',
                hero=ImageComponent(
                    url='https://imgur.com/6u5XWJX.jpg',
                    size='full',
                    aspect_ratio='5:1',
                    aspect_mode='fit',
                    action=MessageAction(label=trans_txt('選單',lan).get('TranslatedText'), text=trans_txt('選單',lan).get('TranslatedText'))
                ),
            )
            print("選單:"+trans_txt('選單',lan).get('TranslatedText'))
            # 轉成使用者輸入的語言回覆
            trans_text = translate_text("已變更你的語言囉~開始使用推薦功能吧!","zh-TW",lan).get('TranslatedText')

            line_bot_api.reply_message(event.reply_token, [TextSendMessage(
                text=trans_text), FlexSendMessage(alt_text="已變更你的語言囉~開始使用推薦功能吧!", contents=bubble1)])

        elif text == "天氣":
            if (user['lat'] != None):  # user有資料,拿經緯度
                print("NOT EMPTY")
                lat = user['lat']
                lng = user['lng']
                # 去天氣API拿天氣資料 並回傳JSON 處理JSON拿天氣資料
                complete_url = 'https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid=0056a083378c9466f69a017d5c17c4f4&lang=zh_tw'.format(
                lat, lng)
                print(complete_url)
                response = requests.get(complete_url)
                #print(response)
                x = response.json()
                # 拿天氣資料
                city_name = x['name']
                icon = x['weather'][0]['icon']  # 天氣狀況
                icon_url = 'https://openweathermap.org/img/wn/{}@2x.png'.format(icon)
                print(icon_url)
                description = x['weather'][0]['description']
                temp_min = repr(x['main']['temp_min'])  # 最低溫度
                temp_min = repr(round((float(temp_min)-273.15), 2))
                temp_max = repr(x['main']['temp_max'])  # 最最高溫度
                temp_max = repr(round((float(temp_max)-273.15), 2))
                print(description)
                # 以上皆對

                # 天氣資訊欄
                bubble_1 = BubbleContainer(
                    direction='ltr',
                    hero=ImageComponent(
                        url=icon_url,  # 貌似出錯 解法: 一定要+S在HTTP後面
                        size='lg',
                        aspect_ratio='20:13',
                        aspect_mode='cover'
                    ),
                    body=BoxComponent(
                        layout='vertical',
                        contents=[
                            # title
                            TextComponent(text=city_name, weight='bold', size='xl'),
                            # review
                            # info
                            BoxComponent(
                                layout='vertical',
                                margin='lg',
                                spacing='sm',
                                contents=[
                                    BoxComponent(
                                        layout='baseline',
                                        spacing='sm',
                                        contents=[
                                            TextComponent(
                                                text=trans_txt('天氣狀況',user['lan']).get('TranslatedText'),
                                                color='#aaaaaa',
                                                size='sm',
                                                flex=5
                                            ),
                                            TextComponent(
                                                text=trans_txt(description,user['lan']).get('TranslatedText'),
                                                wrap=True,
                                                color='#666666',
                                                size='sm',
                                                flex=5
                                            )
                                        ],
                                    ),
                                    BoxComponent(
                                        layout='baseline',
                                        spacing='sm',
                                        contents=[
                                            TextComponent(
                                                text=trans_txt('最高溫度',user['lan']).get('TranslatedText'),
                                                color='#aaaaaa',
                                                size='sm',
                                                flex=7
                                            ),
                                            TextComponent(
                                                text=temp_max,
                                                wrap=True,
                                                color='#666666',
                                                size='sm',
                                                flex=5,
                                            ),
                                        ],
                                    ),
                                    BoxComponent(
                                        layout='baseline',
                                        spacing='sm',
                                        contents=[
                                            TextComponent(
                                                text=trans_txt('最低溫度',user['lan']).get('TranslatedText'),
                                                color='#aaaaaa',
                                                size='sm',
                                                flex=7
                                            ),
                                            TextComponent(
                                                text=temp_min,
                                                wrap=True,
                                                color='#666666',
                                                size='sm',
                                                flex=5,
                                            ),
                                        ],
                                    ),
                                ],
                            )
                        ],
                    ),
                    footer=BoxComponent(
                        layout='vertical',
                        spacing='sm',
                        contents=[
                            TextComponent(
                                text=' ',
                                color='#aaaaaa',
                                size='sm',
                                flex=1
                            )
                        ]
                    )
                )
                message1 = FlexSendMessage(alt_text="天氣狀況", contents=bubble_1)
                
                relocation = {
                    'zh-TW' : 'https://i.imgur.com/Mu3OmsY.jpg',
                    'en' : 'https://imgur.com/QPeSsju.jpg',
                    'ja' : 'https://imgur.com/MjuLXTe.jpg',
                    'ko' : 'https://imgur.com/2uu74Xs.jpg'
                }.get(user['lan'], None)
                bubble_2 = BubbleContainer(
                    direction='ltr',
                    hero=ImageComponent(
                        url=relocation,
                        size='full',
                        aspect_ratio='5:1',
                        aspect_mode='fit',
                        action=URIAction(uri='line://nv/location', label='label')
                    )
                )
                message2 = FlexSendMessage(alt_text="定位", contents=bubble_2)
                line_bot_api.reply_message(event.reply_token, [message1, message2])
            

            else:  # user沒有資料,要定位
                print("EMPTY")
                bubble1 = BubbleContainer(
                    direction='ltr',
                    hero=ImageComponent(
                        url='https://i.imgur.com/Mu3OmsY.jpg',
                        size='full',
                        aspect_ratio='5:1',
                        aspect_mode='fit',
                        action=URIAction(uri='line://nv/location', label='label')
                    ),
                )
                line_bot_api.reply_message(
                    event.reply_token,
                    FlexSendMessage(alt_text="定位", contents=bubble1))
            
        else:
            ai = apiai.ApiAI(os.environ.get('CLIENT_ACCESS_TOKEN'))
            request = ai.text_request()

            request.lang = 'tw'  # optional, default value equal 'en'

            request.query = event.message.text
            response = request.getresponse().read().decode()
            result = json.loads(response)
            # 轉成使用者輸入的語言回覆
            trans_text = translate_text(result['result']['fulfillment']['speech'],"zh-TW",language).get('TranslatedText')

            line_bot_api.reply_message(event.reply_token, TextSendMessage(
                text=trans_text))
示例#9
0
from flask import Flask, request, abort

from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import *
import os.path
import sys
import json
import apiai
import star2
import random
from chatBot import cafeChatbot
import read_jokes
app = Flask(__name__)
# YOUR GOOGLE DIALOGFLOW API KEY
ai = apiai.ApiAI('YOUR GOOGLE DIALOGFLOW API KEY')
# Channel Access Token
line_bot_api = LineBotApi('LINE CHANNEL ACCESS TOKEN')
# Channel Secret
handler = WebhookHandler('LINE CHANNEL SECRET')
#man
men = [
    "https://imgur.com/UQINa8n.jpg", "https://imgur.com/3FFrELS.jpg",
    "https://imgur.com/rzpidOW.jpg", "https://imgur.com/2NPW9v3.jpg",
    "https://imgur.com/8lyrjKk.jpg", "https://imgur.com/6Pzsgii.jpg",
    "https://imgur.com/K5dmaWW.jpg", "https://imgur.com/uXJX3oi.jpg",
    "https://imgur.com/AQ3nNIl.jpg", "https://imgur.com/PKlVYab.jpg",
    "https://i.imgur.com/FH4XQVp.jpg"
]
#WEMEN
wemen = [
示例#10
0
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.mail import send_mail

from user.models import Client

# Create your views here.
import requests
import json

MAIL_SERVER = ''

import apiai
ai = apiai.ApiAI("5024b204fe004def95ee70793929c0f0")


def message_to_bot(message, client):

    request = ai.text_request()
    request.query = message

    response = request.getresponse().read().decode('utf-8')
    return json.loads(response)


@csrf_exempt
def recieve_mail(request):

    mails = process_request(request)['mail']
    for mail in mails:
        user = mail['to']
示例#11
0
import urllib.request
import urllib.parse
import codecs
import json,re
from config import *
import apiai
import retreiveData as retreive

client=apiai.ApiAI(APIAIKey)

need_list = ["food","shelter","water","medicine","cloth","hygene"]

def apiai_query(message):
    req=client.text_request()
    req.lang="de"
    req.session_id="<SESSION ID, UNIQUE FOR EACH USER>"
    req.query=message

    response=json.loads(req.getresponse().read().decode('utf-8'))
    responseStatus = response['status']['code']

    print(response)

    if responseStatus == 200 :
        text = response['result']['fulfillment']['speech']
    else:
        text="No Match Found"

    result=response["result"]
    param=result["parameters"]
    if len(param.keys())==0:
示例#12
0
def get_text_messages(message):
    #bot.forward_message(127924504, message.chat_id, message_id)
    GODmsg = "Сообщение " + message.text + " от " + str(message.from_user)
    bot.send_message(127924504, GODmsg)
    if message.text == "Сколько ещё ждать?" or message.text == "/wait":

        # Пишем приветствие

        bot.send_message(message.from_user.id, "Скажи, куда ты собрался?")

        # Готовим кнопки

        keyboard = types.InlineKeyboardMarkup()

        # По очереди готовим текст и обработчик для каждого знака зодиака

        key_chegem = types.InlineKeyboardButton(text='Чегем',
                                                callback_data='chegem')

        # И добавляем кнопку на экран

        keyboard.add(key_chegem)

        key_splav = types.InlineKeyboardButton(text='Сплав с Олегом',
                                               callback_data='splav')

        keyboard.add(key_splav)

        key_chuhloma = types.InlineKeyboardButton(text='Чухлома',
                                                  callback_data='chuhloma')

        keyboard.add(key_chuhloma)

        key_bear = types.InlineKeyboardButton(text='Камчатка',
                                              callback_data='bear')

        keyboard.add(key_bear)

        key_veget = types.InlineKeyboardButton(text='Никуда',
                                               callback_data='veget')

        keyboard.add(key_veget)

        # Показываем все кнопки сразу и пишем сообщение о выборе

        bot.send_message(message.from_user.id,
                         text='Я скажу сколько ещё ждать',
                         reply_markup=keyboard)
    elif message.text == '/ID':
        IDmsg = "Ваш ID в Телеграм: " + str(message.from_user.id)
        bot.send_message(message.from_user.id, IDmsg)
    elif message.text == '/help':
        bot.send_message(
            message.from_user.id,
            "Сколько ещё ждать? или /wait - расчёт дней до ближайшей поездки. /ID - покажет ваш ID в Telegram. На любой другой запрос ответит встроенный искуственный идиот"
        )
    elif message.text == '/start':
        bot.send_message(
            message.from_user.id,
            "Привет! Я умею рассказывать сколько дней до ближайшей поездки (для этого надо спросить 'Сколько ещё ждать?') или можем просто поболтать о жизни с помощью моего искуственного интеллекта."
        )
    else:
        request = apiai.ApiAI(
            dialogflowtoken).text_request()  # Токен API к Dialogflow
        request.lang = 'ru'  # На каком языке будет послан запрос
        request.session_id = 'Bot_Idiot'  # ID Сессии диалога (нужно, чтобы потом учить бота)
        request.query = message.text  # Посылаем запрос к ИИ с сообщением от юзера
        responseJson = json.loads(request.getresponse().read().decode('utf-8'))
        response = responseJson['result']['fulfillment'][
            'speech']  # Разбираем JSON и вытаскиваем ответ
        # Если есть ответ от бота - присылаем юзеру, если нет - бот его не понял
        if response:
            bot.send_message(message.from_user.id, response)
        else:
            bot.send_message(
                message.from_user.id,
                'Я Вас не совсем понял! Попробуйте повторить запрос или введите команду /help для получения справки'
            )
示例#13
0
def message():
    data = json.loads(request.data)
    message_id = data['data']['id']
    session_id = data['data']['personEmail'] + data['data']['roomId']
    room_id = data['data']['roomId']

    if data['data']['personEmail'] == '*****@*****.**':
        return "true"

    if session_id not in session:
        session[session_id] = uuid.uuid1()

    headers = {'Authorization': 'Bearer evenMoreSecret'}

    data = requests.get('https://api.ciscospark.com/v1/messages/' +
                        str(message_id),
                        headers=headers)
    data = json.loads(data.text)
    text = data['text']

    ai = apiai.ApiAI("more secret")
    r = ai.text_request()
    r.lang = 'es'  # optional, default value equal 'en'
    r.session_id = 'asd'
    r.query = text
    response = r.getresponse()
    response = response.read()
    print(response)
    response = json.loads(response)

    if response['result']['actionIncomplete'] is False:
        if 'sw' in response['result']['parameters']:
            swtich = response['result']['parameters']['sw']
            port = response['result']['parameters']['port']

            swtich = swtich.replace("OSCI ", "")
            port = port.replace("OSCI ", "")

            print("sw", swtich)
            print("port", port)
            import paramiko

            ssh = paramiko.SSHClient()
            ssh.load_system_host_keys()
            ssh.set_missing_host_key_policy(paramiko.WarningPolicy())
            ssh.connect(swtich.strip(),
                        port=22,
                        username="******",
                        password="******",
                        look_for_keys=False,
                        allow_agent=False)
            stdin, stdout, stderr = ssh.exec_command("show interfaces " + port)
            stdout = stdout.readlines()
            txt_response = '\n'.join(stdout)
            print("stf", stdout)
            ssh.close()
        else:
            txt_response = response['result']['fulfillment']['speech']
    else:
        txt_response = response['result']['fulfillment']['speech']

    payload = {'roomId': room_id, 'text': txt_response}
    data = requests.post('https://api.ciscospark.com/v1/messages',
                         headers=headers,
                         data=payload)
    data = json.loads(data.text)
    print(data)

    return "true"
示例#14
0
def main():

    parser = argparse.ArgumentParser(description='query Api.Ai web agent.')
    parser.add_argument(
        '--testset',
        dest='testset',
        action='store',
        metavar='TESTSET',
        required=True,
        help=
        'The testset dir to be used, value can be: default or specified. If specified specifyTestSetInfo.txt will be read.'
    )
    parser.add_argument(
        '--token',
        dest='token',
        action='store',
        metavar='TOKEN',
        required=True,
        help=
        'The APIAI client access token which you get when you create the agent.'
    )
    args = parser.parse_args()
    client_access_token = ""
    if args.token is not None:
        client_access_token = args.token
    else:
        raise RuntimeError, 'Usage: python progName --testset default/specified --token clientToken'

    testset = ""
    if args.testset is not None:
        testset = args.testset
    else:
        raise RuntimeError, 'Usage: python progName --testset default/specified --token clientToken'

    testset = testset.lower()
    rootDirTop = "../.."
    infoFile = rootDirTop + '/allGeneFileNames/allGeneFileNames.txt'
    dictkv = getDictInfoFromFile(infoFile)
    serviceName = dictkv["serviceName_APIAI"]
    trainset = dictkv["apiaiActuallyUsedTrainset"]

    resultsIdx = dictkv[
        "apiaiLatestTestResultsIdx"]  # used for label testResults dir to allow multiple tests
    crntIdx = int(resultsIdx) + 1
    srcFiles = []
    trainTimeStamp = dictkv["timeStamp"]
    textTestsetDir = ""
    annoTestsetDir = ""  # for saveInfo, used by evaluator
    if testset == "default":
        annoTestsetDir = dictkv[
            "testSetAnnotated"]  # testSetAnnotated was added when first generating data
        textTestsetDir = dictkv["testSetPureTextDir"]
        srcFiles = getFiles(textTestsetDir)
    else:
        testInfoFile = rootDirTop + '/allGeneFileNames/specifyTestSetInfo.txt'
        testsetkv = getDictInfoFromFile(testInfoFile)
        testTimeStamp = testsetkv["testTimeStamp"]
        testFileStr = testsetkv["testIntentFiles"]
        testDirPref = rootDirTop + "/preprocessResults/autoGeneFromRealAnno/autoGene_"
        testDirSuff = "/DomainIntentNoDupShuffleSubset_Test/text"
        textTestsetDir = testDirPref + testTimeStamp + testDirSuff
        annoTestsetDir = testDirPref + testTimeStamp + "/DomainIntentNoDupShuffleSubset_Test/annotated"
        if testFileStr == "full":
            srcFiles = getFiles(textTestsetDir)
        else:
            srcFiles = getFilesFromStr(testFileStr)

    srcBaseDir = textTestsetDir
    baseDestDir = rootDirTop + "/testResults/" + serviceName
    if (not os.path.exists(baseDestDir)):
        os.mkdir(baseDestDir)

    baseDestDir = baseDestDir + "/" + serviceName + "_TestResults_" + trainset + "_" + trainTimeStamp + "-" + str(
        crntIdx)

    if (not os.path.exists(baseDestDir)):
        os.mkdir(baseDestDir)

    # save saveinfo -- append to file: allGeneFileNames/allGeneFileNames.txt
    crntTimeStamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f')[:-3]
    saveinfo = []
    saveinfo.append("\n# ---- written by queryApiaiAuto2.py:")
    saveinfo.append("crntTimeStamp=" + crntTimeStamp)
    saveinfo.append("apiaiLatestTestResultsIdx=" +
                    str(crntIdx))  #TODO rasa would use serviceName
    saveinfo.append("apiaiLatestTestResultsDir=" +
                    baseDestDir)  # evaluater read this
    saveinfo.append("apiaiTestSetAnnotated=" +
                    annoTestsetDir)  # evaluator read this
    saveinfo.append("apiaiQueriedClientToken=" + client_access_token)
    saveinfo.append("apiaiQueriedTestset=" + testset)

    write2fileAppend(infoFile, saveinfo)

    numUtt = 500  # max num of utt to test
    totalUttProcessed = 0
    ai = apiai.ApiAI(client_access_token)

    # new generated test input text files are contained in one directory
    # not have further subdirectory for each domain as before.
    # srcFiles = getFiles(srcBaseDir)  === got from above.
    start_time = time.time()
    for i in range(len(srcFiles)):
        results = {'results': []}
        domainFile = srcFiles[i]
        print "srcFiles:" + domainFile

        fileUri = os.path.join(srcBaseDir, domainFile)
        print "fileUri:" + fileUri
        utterances = readFile2List(fileUri)
        num = numUtt  # numUtt is the max num of utt to test
        if (num > len(utterances)):
            num = len(utterances)
            print "num of utt to test:" + str(num)

        for j in range(num):
            utt = utterances[j]
            utt = utt.lower()
            print "query:" + str(j) + " = " + utt
            #res = queryApiai(utt)

            request = ai.text_request()
            request.query = utt
            response = request.getresponse()
            jo = response.read()
            res = json.loads(jo)

            results['results'].append(res)
            totalUttProcessed = totalUttProcessed + 1
            print "totalUttProcessed:" + str(totalUttProcessed)

            # wait a bit, then query again for another utt.
            # time.sleep(0.3) # Time in seconds. consider limit of 5 calls per second
            time.sleep(
                0.2
            )  # 0.2 should be enough, as query itself takes time. Apiai is quicker than Luis and Watson.

        domainName = domainFile[0:domainFile.rfind(".")]
        print "domainName:" + domainName
        saveJson2File(baseDestDir, domainName, results)

    elapsed_time = time.time() - start_time
    print "==== APIAI query finished ==== Elapsed Time: " + str(elapsed_time)
示例#15
0
def api_main(Querry):
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

    request = ai.text_request()

    request.lang = 'en'  # optional, default value equal 'en'

    request.session_id = "<SESSION ID>"

    request.query = Querry

    response = request.getresponse()

    # print (response.read())

    JsonData = response.read()

    JsonToPython = json.loads(JsonData)
    print(JsonToPython['result'])

    ActionName = JsonToPython['result']['action']
    ActionIncomplete = JsonToPython['result']['actionIncomplete']

    if ActionName == 'input.Claim_Initiated' and ActionIncomplete == False:
        UserClaimNumber = JsonToPython['result']['contexts'][0]['parameters'][
            'Claim-Number'][0]['number.original']
        print(UserClaimNumber)
        aftr_clm = AfterClaim(UserClaimNumber)
        return (aftr_clm)
    # print (UserClaimNumber)

    elif ActionName == 'input.Coverage_Amount' and ActionIncomplete == False:
        UserPolicyNumber = JsonToPython['result']['contexts'][0]['parameters'][
            'Policy_Number']
        init_stat = (
            "<span style='color: #666766;font-weight: 500;'>Coverage Details</span><span class='list-card-description'>Cool. You're all set. You are covered for </span>"
        )
        CA = PolicyAmount(UserPolicyNumber)
        final_statement = init_stat + str(CA)
        return (final_statement)

    elif ActionName == 'input.PropertyDamage':
        UserPolicyNumber = JsonToPython['result']['contexts'][0]['parameters'][
            'Policy_Number']
        ini_stat = (
            "<span style='color: #666766;font-weight: 500;'>Property Damage</span><span style='display:block;'><img src='static/images/propertyDamage.jpg' style='height: 100%;width: 100%;'></span><span class='list-card-description'>You are covered for damage to </span>"
        )
        prop_dmg = PropertyDamage(UserPolicyNumber)
        close_stat = (
            "<span style='display:block'>Is their any other information I can help you with ?</span>"
        )
        fl_stat = ini_stat + str(prop_dmg) + close_stat
        return (fl_stat)

    elif ActionName == 'input.ClaimAdjuster':
        UserClaimNumber = JsonToPython['result']['contexts'][0]['parameters'][
            'Claim-Number'][0]['number.original']
        print(UserClaimNumber)
        fnl_statement = ClaimAdjuster(UserClaimNumber)
        return (fnl_statement)

    elif ActionName == 'input.Link_Not_Working':
        UserPolicyNumber = JsonToPython['result']['contexts'][0]['parameters'][
            'Policy_Number']

        Cause = JsonToPython['result']['contexts'][0]['parameters'][
            'Accident.original']
        TIME = JsonToPython['result']['contexts'][0]['parameters']['time']
        DATE = JsonToPython['result']['contexts'][0]['parameters']['date'][0]
        print(DATE)
        TimeStamp = str(DATE) + "T" + str(TIME) + "Z"
        UQ.Claim_Number = Random()
        UQ.AdjusterName = Adjuster[random.randint(0, 3)]
        import datetime
        mylist = []
        b = datetime.date.today()
        a = b + timedelta(days=5)
        mylist.append(a)
        UQ.DateOfVisit = mylist[0]
        UQ.ContactNumber = Number[random.randint(0, 3)]
        UQ.Date = DATE
        UQ.Time = TIME
        UQ.Cause = Cause
        UQ.PolicyNumber = UserPolicyNumber
        with open('claim.csv', 'a') as Ques_Ans:
            writer = csv.writer(Ques_Ans)
            writer.writerow([
                UQ.Claim_Number, UQ.AdjusterName, UQ.DateOfVisit,
                UQ.ContactNumber, UQ.Date, UQ.Time, UQ.Cause, UQ.PolicyNumber
            ])

        final = (
            "<span style='color: #666766;font-weight: 500;margin-bottom: 2px;'>Claim Registration</span><span class='list-card-description'>Your Claim has been initiated and your claim registration number is <span style='color: #f9eeaa;font-weight: bold;'>"
            + str(UQ.Claim_Number) +
            ".</span></span><span style='display: block;margin-bottom: 20px;'> You will shortly recieve a call from our Claims Team who will assist you further</span> <span style='display:block;margin-bottom: 2px;'> Is there anything else that I may help you with ?</span><div class='quick-replies-buttons'><button type='button' class='btn pmd-btn-outline pmd-ripple-effect btn-info .pmd-btn-fab apiQuickreplybtnPayload' data-apiquickrepliespayload='Yes, Please'>Yes, Please</button><button type='button' class='btn pmd-btn-outline pmd-ripple-effect btn-info .pmd-btn-fab apiQuickreplybtnPayload' data-apiquickrepliespayload='No, Thanks'>No, Thanks</button></div>"
        )
        print(final)
        return (final)

    elif ActionName == 'input.unknown':

        a = classifier(Querry)
        if a == 'machine':
            flag = 0
            csv_file = csv.reader(open('sanchit.csv'), delimiter=",")
            qstn = Querry
            for row in csv_file:
                print("checking...")
                if qstn == row[0]:
                    return (row[1])
                    flag = flag + 1

            if (flag == 0):
                return (False)
        elif a == 'no machine':
            return ("I am not trained for this scope..")

    else:
        return (JsonToPython)
示例#16
0
    sha256.update(text)
    return sha256.hexdigest()


if __name__ == '__main__':

    # with open("./movr.ini") as f:
    # 	movr_config = f.read()
    # config = ConfigParser.RawConfigParser(allow_no_value=True)
    # config.readfp(io.BytesIO(movr_config))

    # ai 		= apiai.ApiAI(config.get('api_ai', 'client_access_token'))
    # request = ai.text_request()
    # request.session_id = config.get('api_ai', 'session_id')

    ai = apiai.ApiAI('17dac27f07a24b47b39aece331efc3ad')
    request = ai.text_request()
    request.session_id = 'api_ai', '<SESSION ID, UNIQUE FOR EACH USER>'

    # main()

    r = sr.Recognizer()
    m = sr.Microphone()

    with m as source:
        r.adjust_for_ambient_noise(source)

    # r.pause_threshold = 1
    r.operation_timeout = 8
    stop_listening = r.listen_in_background(m, speech_recog_cb)
示例#17
0
import json
from flask import Flask, request
import apiai
import twilio.twiml
from twilio.rest import TwilioRestClient
import config

# Configurations for twilio, apiai, and flask.
client = TwilioRestClient(config.account_sid, config.auth_token)
ai = apiai.ApiAI(config.client_access_token)
app = Flask(__name__)


@app.route("/test")
def hello():
    return "Hello World!"


@app.route("/", methods=['GET', 'POST'])
def server():

    # get SMS input via twilio
    resp = twilio.twiml.Response()

    # get SMS metadata
    msg_from = request.values.get("From", None)
    msg = request.values.get("Body", None)

    # prepare API.ai request
    req = ai.text_request()
    req.lang = 'en'  # optional, default value equal 'en'
示例#18
0
 def __init__(self):
     self.serena = apiai.ApiAI(token)
     self.session_id = util.generate_id(20)
     self.response = {}
示例#19
0
 def __init__(self):
     #Connexion api
     self.ai=apiai.ApiAI(CLIENT_ACCESS_TOKEN)
示例#20
0
#get bot id
BOT_ID = os.environ.get('SLACK_BOT_ID')

#get slack bot token
SLACK_BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN')

#get aiapi access token
APIAI_ACCESS_TOKEN = os.environ.get('APIAI_DEVELOPER_ACCESS_TOKEN')
#APIAI_ACCESS_TOKEN = "696bcad329ed4327981a0ba711b4f663"

#set slack client
slack_client = SlackClient(SLACK_BOT_TOKEN)

#set apiai client
apiai_client = apiai.ApiAI(APIAI_ACCESS_TOKEN)

# constants
AT_BOT = "<@" + BOT_ID + ">"
EXAMPLE_COMMAND = "do"


def parse_slack_output(slack_rtm_output):
    output_list = slack_rtm_output

    if output_list and len(output_list) > 0:
        for output in output_list:
            # print "output: ", len(output.keys()), output , "\n\n", BOT_ID, "\n\n"
            if output and 'text' in output and AT_BOT in output['text']:
                # return text after the @ mention, whitespace removed
                return output['text'].split(
示例#21
0
import apiai, json
import photo_proc

txt_request = apiai.ApiAI('733a0aad1eb0479c88c862e1ec1a26e7').text_request(
)  # Токен API к Dialogflow
txt_request.lang = 'ru'  # На каком языке будет послан запрос
txt_request.session_id = 'Comparator3000'  # ID Сессии диалога (нужно, чтобы потом учить бота)
txt_request.query = 'Ты здесь?'  # Посылаем запрос к ИИ с сообщением от юзера
txt_responseJson = json.loads(txt_request.getresponse().read().decode('utf-8'))
txt_response = txt_responseJson['result']['fulfillment'][
    'speech']  # Разбираем JSON и вытаскиваем ответ
# Если есть ответ от бота - присылаем юзеру, если нет - бот его не понял
print('Проверяем работает ли бот; Спросим: Ты здесь?')
if txt_response:
    print('Бот готов; его ответ: ' + txt_response)
else:
    print('Подключение отсутствует, бот не отвечает')

photo_request = '/test_photo.jpg'
try:
    photo_response = photo_proc.class_detector(photo_request)
    print('Обработка фото функционирует нормально')
except:
    print('Что-то пошло не так при обработке фотографии')
示例#22
0
def handle(msg):
   # imprime a mensagem
   print "%s\n" % msg
   
   # pega os dados básicos da mensagem 
   content_type, chat_type, chatid = telepot.glance(msg)
   print 'content_type: %s\n' % content_type
   print 'chat_type: %s\n' % chat_type
   try:
      msg['reply_to_message']
      IsReply = 1
      ReplyPara = msg['reply_to_message']['from']['username']
   except:
      IsReply = 0

   print 'IsReply = %d' % IsReply
   
   # caso seja alguém entrando no grupo, envia mensagem de boas vindas
   if content_type == 'new_chat_member':
      # se o novo participante for um bot já expulsa.
      if msg['new_chat_participant']['is_bot']:
         bot.sendMessage(chatid, mensagem.userbot)
         bot.kickChatMember(chatid, msg['new_chat_participant']['id'])
      # se o novo participante não for um bot tenta ver se ele tem um nome.
      else:
         try:
            NomeNovoMembro = msg['new_chat_participant']['first_name']
         except:
            NomeNovoMembro = u'Sem Nome'
         # verifica se o novo membro é um ser humano fazendo um teste simples, perguntando quanto é 2+2
         bot.sendMessage(chatid, u'Olá, ' + NomeNovoMembro + u'. Antes de te dar boas vindas vou verificar se tu é realmente uma pessoa, ok? Quanto é dois mais dois? Você tem 30 segundos para responder.')
         DadosNovoMembro['memberid'] = msg['new_chat_participant']['id']
         DadosNovoMembro['chatid'] = chatid
		 
   # avisa quando alguém deixa o grupo
   elif content_type == 'left_chat_member':
      # tenta ler o nome de quem saiu
      try:
         NomeMembroSaindo = msg['left_chat_participant']['first_name']
      except:
         NomeMembroSaindo = u'Sem Nome'
		 
      # avisa grupo que membro saiu
      bot.sendMessage(chatid, NomeMembroSaindo + mensagem.tchau)
		 
   ###########################################
   # A PARTIR DESSE PONTO ELE DETECTA TEXTOS #
   ###########################################
   elif content_type == 'text':
      # todas as mensagens são convertida para caracteres minúsculos
      MensagemGrupo = msg['text'].lower()
      
	  # se a flag de novo membro estiver ativa e esse cara respondeu corretamente, zera o timeout para kick
      if (MensagemGrupo.find('4') >= 0 or MensagemGrupo.find('quatro') >= 0) and msg['from']['id'] == DadosNovoMembro['memberid']:
         DadosNovoMembro['memberid'] = 0
         DadosNovoMembro['chatid'] = 0
         bot.sendMessage(chatid, u'Agora sim. ' + mensagem.boasvindas)
      
      #verifica se a menssagem é para o Fauro e envia a menssagem para o DialogFlow
      #elif MensagemGrupo != False and bool(re.search('\\@FauroIA_bot\\b', MensagemGrupo, re.IGNORECASE)):
      elif ((IsReply and ReplyPara == u'faurorex_bot') or bool(re.search('\\@faurorex_bot\\b', MensagemGrupo, re.IGNORECASE))):
         MensagemGrupoModificada = MensagemGrupo.replace('@faurorex_bot','') #remove da menssagem o nome do Bot
         request = apiai.ApiAI(config.token_dialogflow).text_request() # Conecta ao Dialogflow através da API Token
         request.lang = 'pt-BR' # Seta a lingua a ser utilizada no dialogflow
         request.session_id = 'Small-Talk' # ID Sessão de Dialogo (para terinamento do bot)
         request.query = MensagemGrupoModificada# Envia a menssagem para o dialogflow 
         responseJson = json.loads(request.getresponse().read().decode('utf-8'))
         response = responseJson['result']['fulfillment']['speech'] # pega a resposta do JSON
         if response:
            bot.sendMessage(chatid, text=response) #Resposta a ser enviada para o BOT

      # comando para mostrar último episódio do feed do podcast
      elif MensagemGrupo == '/ultimo':
         feed = feedparser.parse(config.url_feed)
         # imprime o status do feed (códigos http, exemplo, 404 é feed não encontrado. 200 é ok e 301 é redirecionado)
         print feed.status
         if feed.status == 200 or feed.status == 301:
            print feed.entries[0].links[1].href
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
               [InlineKeyboardButton(text = u'Ouvir', url = feed.entries[0].links[1].href, callback_data='url')],
            ])
            bot.sendMessage(chatid, feed.entries[0].title, reply_markup=keyboard)
示例#23
0
from django.conf import settings
from .users import userfb, user_save

import apiai
import json


from .actions import send_message
from .messages import typing, send_text


AI = apiai.ApiAI(settings.CLIENT_ACCESS_TOKEN_DIALOG_FLOW)    
MAX_TIME = 5
        

def recived_message(message):

    sender_id = message['sender']['id']
    
    message_text = message['message']['text']

    request = AI.text_request()

    request.query = message_text

    response = json.loads(request.getresponse().read().decode('utf-8'))
    
    print("SENDER_ID ", sender_id)
    speech = response['result']['fulfillment']['speech']

    _user_data = userfb(sender_id)
 def __init__(self, token):
     self.ai = apiai.ApiAI(token)
示例#25
0
def main():

    # ./preprocessResults/out4RasaReal/rasa_json_2018_03_22-13_01_25_169_80Train/
    #   CrossValidation/KFold_1/testset/text
    parser = argparse.ArgumentParser(description='query Apiai web server.')
    parser.add_argument('--timestamp',
                        dest='timestamp',
                        action='store',
                        metavar='TIMESTAMP',
                        required=True,
                        help='The timestamp of generated data.')
    parser.add_argument('--kfold',
                        dest='kfold',
                        action='store',
                        metavar='KFOLD',
                        required=True,
                        help='order number of the kfold, e.g. 1,2,...')

    parser.add_argument(
        '--token',
        dest='token',
        action='store',
        metavar='TOKEN',
        required=True,
        help=
        'The APIAI client access token which you get when you create the agent.'
    )
    args = parser.parse_args()
    client_access_token = ""
    if args.token is not None:
        client_access_token = args.token
    else:
        raise RuntimeError, 'Usage: python progName --testset default/specified --token clientToken'

    timestamp = ""
    if args.timestamp is not None:
        timestamp = args.timestamp
    else:
        raise RuntimeError, 'Usage: python progName --timestamp tm --kfold Num'

    kfold = ""
    if args.kfold is not None:
        kfold = args.kfold
    else:
        raise RuntimeError, 'Usage: python progName --timestamp tm --kfold Num'

    rootDirTop = "../.."

    textTestsetDir = rootDirTop + "/preprocessResults/autoGeneFromRealAnno/autoGene_" + timestamp + "/CrossValidation/KFold_" + kfold + "/testset/text"
    srcFiles = getFiles(textTestsetDir)

    crntIdx = 1
    serviceName = "APIAI"
    trainset = "KFold"
    trainTimeStamp = timestamp

    baseDestDir = rootDirTop + "/testResults/" + serviceName
    if (not os.path.exists(baseDestDir)):
        os.mkdir(baseDestDir)

    baseDestDir = baseDestDir + "/" + serviceName + "_TestResults_" + trainset + "_" + trainTimeStamp + "-" + str(
        crntIdx)
    baseDestDir = baseDestDir + "/KFold_" + kfold
    if (not os.path.exists(baseDestDir)):
        os.mkdir(baseDestDir)

    numUtt = 500  # max num of utt to test
    totalUttProcessed = 0
    ai = apiai.ApiAI(client_access_token)

    # new generated test input text files are contained in one directory
    # not have further subdirectory for each domain as before.
    # srcFiles = getFiles(srcBaseDir)  === got from above.
    srcBaseDir = textTestsetDir
    start_time = time.time()
    for i in range(len(srcFiles)):
        results = {'results': []}
        domainFile = srcFiles[i]
        print "srcFiles:" + domainFile

        fileUri = os.path.join(srcBaseDir, domainFile)
        print "fileUri:" + fileUri
        utterances = readFile2List(fileUri)
        num = numUtt  # numUtt is the max num of utt to test
        if (num > len(utterances)):
            num = len(utterances)
            print "num of utt to test:" + str(num)

        for j in range(num):
            utt = utterances[j]
            utt = utt.lower()
            print "query:" + str(j) + " = " + utt
            #res = queryApiai(utt)

            request = ai.text_request()
            request.query = utt
            response = request.getresponse()
            jo = response.read()
            res = json.loads(jo)

            results['results'].append(res)
            totalUttProcessed = totalUttProcessed + 1
            print "totalUttProcessed:" + str(totalUttProcessed)

            # wait a bit, then query again for another utt.
            # time.sleep(0.3) # Time in seconds. consider limit of 5 calls per second
            time.sleep(
                0.2
            )  # 0.2 should be enough, as query itself takes time. Apiai is quicker than Luis and Watson.

        domainName = domainFile[0:domainFile.rfind(".")]
        print "domainName:" + domainName
        saveJson2File(baseDestDir, domainName, results)

    elapsed_time = time.time() - start_time
    print "==== APIAI query finished ==== Elapsed Time: " + str(elapsed_time)
示例#26
0
 def __init__(self, client_access_token):
     self.ai = apiai.ApiAI(client_access_token)
     self.request = self.ai.text_request()
     self.request.land = 'en'
示例#27
0
    records = news_records.find({"sender_id": user_id})
    return records


def pushRECORD(record):
    """
	function to push news record to collection
	"""
    news_records.insert_one(record)


####################################################################################

# api.ai client
APIAI_ACCESS_TOKEN = "APIAI_ACCESS_TOKEN"
ai = apiai.ApiAI(APIAI_ACCESS_TOKEN)

# endpoint of the news API
GNEWS_API_ENDPOINT = "https://gnewsapi.herokuapp.com"

# available news categories
news_categories = [('sports', 'sports news'), ('political', 'political news'),
                   ('business', 'business news'),
                   ('top stories', 'top stories news'),
                   ('world', 'world news'), ('national', 'national news'),
                   ('technology', 'technology news'),
                   ('entertainment', 'entertainment news')]

# a help message
HELP_MSG = """
Hey! I am NewsBot. 
示例#28
0
def call_api(dict_input):
    global out_dict
    out_dict = {}
    out_dict['messageText'] = []
    out_dict['messageSource'] = 'messageFromBot'
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
    request = ai.text_request()
    request.lang = 'de'
    request.resetContexts = False
    request.session_id = dict_input['user_id']
    user_id = request.session_id
    request.query = dict_input['messageText']
    print(request.query)
    global item
    response = yaml.load(request.getresponse())
    pp = pprint.PrettyPrinter(indent=4)
    json_data = response['result']['parameters']
    pp.pprint(response)
    df = pd.read_csv('harvey.csv')

    if response['result']['metadata'] == {}:
        out_dict['messageText'].append(
            response['result']['fulfillment']['messages'][0]['speech'])
        return out_dict
    elif response['result']['metadata'][
            'intentName'] == 'Default Fallback Intent':
        out_dict['messageText'].append(
            response['result']['fulfillment']['messages'][0]['speech'])
        return out_dict
    elif response['result']['metadata'][
            'intentName'] == 'Default Welcome Intent':
        out_dict['messageText'].append(
            response['result']['fulfillment']['messages'][0]['speech'])
        return out_dict
    elif response['result']['metadata']['intentName'] == 'best_sellers':
        out_dict['messageText'].append('Here is what is trending right now..')
        out_dict["plugin"] = {'name': 'link', 'type': 'products', 'data': data}
        return out_dict
    elif response['result']['metadata']['intentName'] == 'hot_deals':
        out_dict['messageText'].append(
            'Here are some amazing deals that won\'t last long! Please have a look'
        )
        out_dict["plugin"] = {
            'name': 'deals',
            'type': 'products',
            'data': deals,
            'link': 'yes',
            'values': 'https://www.harveynorman.com.au/hot-deals'
        }
        return out_dict
    elif response['result']['metadata']['intentName'] == 'gift_cards':
        out_dict['messageText'].append(
            'Gift cards are always the best option when you stuck for gift ideas. Take a look below: '
        )
        out_dict["plugin"] = {'name': 'link', 'type': 'products', 'data': gift}
        return out_dict
    elif response['result']['metadata'] == {}:
        out_dict['messageText'].append(
            response['result']['fulfillment']['messages'][0]['speech'])
        return out_dict
    elif response['result']['metadata'][
            'intentName'] == 'Default Fallback Intent':
        out_dict['messageText'].append(
            response['result']['fulfillment']['messages'][0]['speech'])
        return out_dict

    elif response['result']['metadata']['intentName'] == 'place_order':
        if json_data['sub_sub_category'] == '':
            if json_data['Product_sub_category'] == '':
                if json_data['product_category'] == '':
                    out_dict['messageText'].append(
                        response['result']['fulfillment']['messages'][0]
                        ['speech'])
                    out_dict['plugin'] = {
                        'name': 'autofill',
                        'type': 'items',
                        'data': category
                    }
                    return out_dict
                else:
                    out_dict['messageText'].append(
                        response['result']['fulfillment']['messages'][0]
                        ['speech'])
                    out_dict['plugin'] = {
                        'name': 'autofill',
                        'type': 'items',
                        'data': sub_items[json_data['product_category']]
                    }
                    return out_dict
            else:
                out_dict['messageText'].append(
                    response['result']['fulfillment']['messages'][0]['speech'])
                out_dict['plugin'] = {
                    'name': 'autofill',
                    'type': 'items',
                    'data': sub_sub_items[json_data['Product_sub_category']]
                }
                return out_dict
        else:
            products = json_data['sub_sub_category']
            lists = product_list(products)
            link = df.loc[df['Items'] == products, 'Link']
            out_dict["plugin"] = {
                'name': 'lists',
                'type': 'products',
                'data': lists,
                'link': 'yess',
                'values': link
            }
            out_dict['messageText'].append(
                'Here are the products according to your preference')
            clear_context(user_id)
            return out_dict
示例#29
0
async def on_message(message):
    mention = bot.user.mention
    if message.content.startswith(mention):
        anime = rq.get('https://kurusaki-webhook.herokuapp.com/').text
        raw_msg = message.content.split("{}".format(mention))
        msg = "".join(raw_msg[1:])
        ai = apiai.ApiAI(apiai_token)
        request = ai.text_request()
        request.lang = 'en'
        request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"
        request.query = msg
        response = request.getresponse()
        rope = str(response.read())
        rope = rope[rope.index("speech") + 10:]
        rope = rope[0:rope.index("\"")]
        if '$anime' in rope:
            anime = rope.replace('$anime', anime)
            await bot.send_message(message.channel, anime)
        elif 'anime' not in rope:
            await bot.send_message(message.channel, rope)
        if "$time" in rope:
            await bot.say(datetime.datetime.now())
        if '$yukinno' in rope:
            author_id = message.author.id
            if author_id == 287369884940238849:
                love = [
                    'I love you Yukinno', 'Yukkino, I love you!',
                    'I love you!', '<3'
                ]
                ran_love = random.choice(love)
                yukinno_love = rope.replace(rope, ran_love)
                await bot.send_message(message.channel, yukinno_love)
            elif message.author.id != 287369884940238849:
                await bot.send_message(message.channel, rope)
    scope = [
        'https://spreadsheets.google.com/feeds',
        'https://www.googleapis.com/auth/drive'
    ]
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'Annie-e432eb58860b.json', scope)
    gc = gspread.authorize(credentials)
    wks = gc.open('Kurusaki_database_discord').sheet1
    try:
        msg = message.content
        user_id = message.author.id
        name = message.author.name
        find_user_id = wks.find(user_id)

        #setting up spreadsheets for updates
        row = wks.find(user_id).row
        points = wks.cell(row, 3).value
        num_points = float(points)
        if len(msg) <= 2 and len(msg) > 0:
            new_value = wks.update_cell(row, 3, num_points + .50)
        if len(msg) <= 10 and len(msg) > 2:
            new_value = wks.update_cell(row, 3, num_points + .60)
        if len(msg) <= 20 and len(msg) > 10:
            new_value = wks.update_cell(row, 3, num_points + 1.20)
        if len(msg) <= 30 and len(msg) > 20:
            new_value = wks.update_cell(row, 3, num_points + 2.75)
        if len(msg) <= 40 and len(msg) > 30:
            new_value = wks.update_cell(row, 3, num_points + 3.00)
        if len(msg) <= 50 and len(msg) > 40:
            new_value = wks.update_cell(row, 3, num_points + 2.00)
        if len(msg) <= 60 and len(msg) > 50:
            new_value = wks.update_cell(row, 3, num_points + 4.50)
        if len(msg) <= 70 and len(msg) > 60:
            new_value = wks.update_cell(row, 3, num_points + 6.00)
        if len(msg) <= 80 and len(msg) > 70:
            new_value = wks.update_cell(row, 3, num_points + 7.50)
        if len(msg) <= 90 and len(msg) > 80:
            new_value = wks.update_cell(row, 3, num_points + 9.20)
        if len(msg) <= 100 and len(msg) > 90:
            new_value = wks.update_cell(row, 3, num_points + 10.55)
        if len(msg) <= 110 and len(msg) > 100:
            new_value = wks.update_cell(row, 3, num_points + 12.20)
    except gspread.exceptions.CellNotFound:
        print(
            "Discord {} is not in Kurusaki's database yet.\nAttempting to add {} to database."
            .format(name, name))
        adding_user = wks.append_row([name, user_id, 2.00])

    #reacting to discord user's message
    try:
        if "gay" in message.content.lower():
            await bot.add_reaction(message, emoji='👌')
        if "yukinno" in message.content.lower():
            await bot.add_reaction(message, emoji='❤')
            await bot.add_reaction(message, emoji='🌸')
            await bot.add_reaction(message, emoji='😇')
        if 'okay' in message.content.lower():
            await bot.add_reaction(message, emoji='👌')
        if 'gj' in message.content.lower():
            await bot.add_reaction(message, emoji='👏')
        if 'good job' in message.content.lower():
            await bot.add_reaction(message, emoji='👏')
        if 'goodjob' in message.content.lower():
            await bot.add_reaction(message, emoji='👏')
        if 'bye' in message.content.lower():
            await bot.add_reaction(message, emoji='👋')
        if 'bai' in message.content.lower():
            await bot.add_reaction(message, emoji='👋')
        if "<@287369884940238849>" in message.content.lower():
            await bot.add_reaction(message, emoji='❤')
            await bot.add_reaction(message, emoji='🌸')
            await bot.add_reaction(message, emoji='😇')

        re = 287369884940238849
        send_id = int(message.author.id)
        if send_id == re:
            await bot.add_reaction(message, emoji='❤')
            await bot.add_reaction(message, emoji='🌸')
            await bot.add_reaction(message, emoji='😇')
        if "michelle" in message.content.lower():
            await bot.add_reaction(message, emoji='❤')
            await bot.add_reaction(message, emoji='😇')
            await bot.add_reaction(message, emoji='🌸')
        if "poop" in message.content.lower():
            await bot.add_reaction(message, emoji='🤔')
            await bot.add_reaction(message, emoji='💩')
        if "shit" in message.content.lower():
            await bot.add_reaction(message, emoji='💩')
    except:
        pass
    try:  #message counter for users
        #connecting to GSPREAD
        scope = [
            'https://spreadsheets.google.com/feeds',
            'https://www.googleapis.com/auth/drive'
        ]
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            'Annie-e432eb58860b.json', scope)
        gc = gspread.authorize(credentials)
        wks = gc.open('Kurusaki_database_discord').sheet1
        try:
            user_msg = 1
            user_id = message.author.id  #user's id
            user_row = wks.find(user_id).row  #finds user's row
            msg_value = wks.cell(user_row, 10).value  #get user's msg value
            if msg_value == "":  #check if the user has empty value
                adding_value = wks.update_cell(
                    user_row, 10, 1)  #if user value is empty add value =1
            else:  #updating the user's new message value
                msg_int = int(msg_value)
                update_msg = wks.update_cell(user_row, 10, msg_int + user_msg)
        except:
            print("Could not add msg value")
    except:
        print("Could not connect to google spreadsheet")
    await bot.process_commands(message)
示例#30
0
def index(request):
	if request.method == 'POST':
		message = request.POST['message']
		sessionID = request.POST['sessionID']


		patientInfo_patientName = None
		patientInfo_patientSurname = None
		patientInfo_patientEhrid = None
		patientInfo_isDoctor = False

		#print("*****SESSION ID*****   ",sessionID)

		#print("\n\n*****USER STATUS*****\nUser: "******"\nIs authenticated: ",request.user.is_authenticated,"\n\n")

		user_status = request.user.is_authenticated

		if user_status:

			if hasattr(request.user,"doctor"):
				patientInfo_isDoctor = True
				patientInfo_patientName = request.user.doctor.name
				patientInfo_patientSurname = request.user.doctor.surname
			else:
				patientInfo_isDoctor = False
				patientInfo_patientName = request.user.patient.name
				patientInfo_patientSurname = request.user.patient.surname
				patientInfo_patientEhrid = request.user.patient.ehrid


		if message[:5] != "getE ":
			#BECAUSE IJS SERVER ISN'T WORKING OTHER API
			translation = translate(message,api_link="http://translation-api.docker-e9.ijs.si/translate?sentence=",yandex=True)

			if translation != "":
				message = translation

		#print("*** message: ",message,"***\n")

		contexts = [{
		  "lifespan": 5,
		  "name": "user_data",
		  "parameters": {
		  "is_authenticated": user_status,
		  "user_ehrid": patientInfo_patientEhrid,
		  "user_patientName": patientInfo_patientName,
		  "user_patientSurname": patientInfo_patientSurname,
		  "user_isDoctor": patientInfo_isDoctor
		  }
		}]

		ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

		request = ai.text_request()
		request.session_id = sessionID
		request.lang = 'en'
		request.contexts = contexts
		request.parameters = {"is_authenticated":user_status}
		request.query = message

		data = request.getresponse().read().decode('utf-8')

		answer_json = json.loads(data)

		print(answer_json)

		text_answer = answer_json['result']['fulfillment']['messages'][0]['speech']

		#print(text_answer)

		data = ""
		response_type = ""
		url = ""

		if 'data' in answer_json['result']['fulfillment']:
		    data = answer_json['result']['fulfillment']['data']['data']
		    response_type = answer_json['result']['fulfillment']['data']['responseType']
		    #print("RESPONSE TYPE: ",response_type)
		    url = answer_json['result']['fulfillment']['data']['url']
		    if url[:5] != "https" and url[0] != "/": 
		    	url = "https:" + url[5:]

		    

		#print("data: ",data)

		return HttpResponse('{{"text_answer":"{0}","response_type":"{1}","data":"{2}","url":"{3}"}}'.format(text_answer,response_type,data,url))
	else:
		return render(request,'dfchatbox/index.html')