def text_message_processing(text, lang): request = apiai.ApiAI(df_token).text_request() request.lang = lang request.session_id = 'WeatherBotHelper_ai' request.query = text responseJson = json.loads(request.getresponse().read().decode('utf-8')) try: response = responseJson['result']['parameters'] except: return [], None response_values = list(filter(lambda x: response[x] != '', list(response))) _list, address = [responseJson['result']['contexts'][0]['name']], None for value in response_values: if value == 'date-time': now = datetime.datetime.now() try: then = datetime.datetime(*map(int, response[value].split('-'))) except: then = datetime.datetime(*map(int, (response[value].split('/')[1]).split('-'))) delta = then - now days = delta.days if days == -1: _list.append('today') elif days == 0: _list.append('tommorow') elif days == 1: _list.append('after tommorow') elif days == 6: _list.append('week') else: _list.append('now') elif value == 'langs': _list.append(response[value]) elif value == 'address': address = list(response[value].values())[0] else: _list.append(value) return list(set(_list)), address
def botResponseReciever(queryMessage): ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN) request = ai.text_request() request.query = queryMessage response = request.getresponse() rawData = str(response.read()) rawData = rawData.replace(r"\n", "") #Remove \n rawData = rawData.replace(r"b'", "", 1) #Remove b' rawData = rawData.replace( r"\'", "") #Remove \' which causes prob in the bot message #rawData = r"Sorry I didn\u0027t get that..." rawData = rawData.replace(r"\u0027", r"'") # Replaces the decoded message with ' jsonData = rawData[0:-1] #Remove ' in the end data = json.loads(jsonData) #pprint.pprint(data) #textToSpeech(data['result']['fulfillment']['speech']) send_data = (data['result']['fulfillment']['speech'], data['result']['metadata']['intentName']) return send_data
def main(qry): ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN) request = ai.text_request() request.session_id = session_id request.query = qry response = request.getresponse() return json.loads(response.read().decode("utf-8"))
def get_api_ai(sentence, arg): ai = apiai.ApiAI(apiai_token) request = ai.text_request() request.lang = 'en' # optional, default value equal 'en' request.query = sentence response = json.loads(request.getresponse().read().decode()) intent = response['result']['action'] entities = [i for i in response['result']['parameters'].values()] return intent, entities
def getDialogflowResponse(text): ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN) request = ai.text_request() # if continue_session == False: request.session_id = sessionID #random.randint(0,999999999999) request.query = text response = request.getresponse() return response
def df_answer(token, text): request = apiai.ApiAI(token).text_request() request.lang = 'ru' request.session_id = 'vksmartbot' request.query = text responseJson = json.loads(request.getresponse().read().decode('utf-8')) response = responseJson['result']['fulfillment']['speech'] if response: return response else: return 'Я только проснулся, попробуй еще разок!'
def runRequest(self, method, url, data=None, headers=None): request = http.client.HTTPSConnection('www.googleapis.com') if data and headers: request.request(method, url, data, headers) elif headers: # for inserting a row request.request(method, url, headers=headers) else: request.request(method, url) response = request.getresponse() print(response.status, response.reason) response = response.read() print (response) return response
def start(self): for event in self.long_poll.listen(): print(event.object.text, " ", event.object.from_id) lst = event.object.text if event.object.from_id>0: request = apiai.ApiAI('e495f56e5266410ab8a0ab4f6081f003').text_request() # Токен API к Dialogflow request.lang = 'ru' # На каком языке будет послан запрос request.session_id = 'BatlabAIBot' # ID Сессии диалога (нужно, чтобы потом учить бота) request.query = lst # Посылаем запрос к ИИ с сообщением от юзера responseJson = json.loads(request.getresponse().read().decode('utf-8')) response = responseJson['result']['fulfillment']['speech'] # Разбираем JSON и вытаскиваем ответ # Если есть ответ от бота - присылаем юзеру, если нет - бот его не понял try: self.send_msg(event.object.peer_id, response) except: self.send_msg(event.object.peer_id, 'Я Вас не совсем понял!')
def main(): ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN) request = ai.text_request() request.lang = 'de' request.session_id = "123" txt = "XXX에서 ZZZ까지 경로" request.query = txt response = request.getresponse() rData = response.read() data = rData.decode('utf-8') print(data)
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 if points == "": get_value=wks.update_cell(row,3,2) 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_id = message.author.id # user's id user_row = wks.find(user_id).row # finds user's row msg_value = wks.cell(user_row, 6).value # get user's msg value if msg_value == "": # check if the user has empty value # if user value is empty add value =1 adding_value = wks.update_cell(user_row, 6, 1) else: # updating the user's new message value msg_int = int(msg_value) update_msg = wks.update_cell(user_row, 6, msg_int+1) except: print("Could not add msg value") except: print("Could not connect to google spreadsheet") await bot.process_commands(message)
def whatNews(bot, update): print("whatNews begun") try: userDB = users.find_one({"uid": update.message.from_user.id}) except: update.message.reply_text( "You are not registered. Press /start and then resend command2") return ConversationHandler.END if update.message.text == "What do you think about the government?": update.message.reply_text("yeh government bik gayi hai") return ConversationHandler.END else: print("else statement begun") request = ai.text_request() request.session_id = update.message.chat_id print(request.session_id) request.query = update.message.text print(request.query) response = request.getresponse() print(response.read()) JSON = json.loads(response.read().decode()) print(JSON) if JSON['result']['metadata']['intentName'] != 'smaug.news': update.message.reply_text( "hmmm...did not get that...choose from below please", reply_markup=news_keyboard) return else: code = JSON['result']['parameters']['Newsource'] print('\n') print(code) listID = str(randint(10000, 99999)) while listID in userDB["listIDs"]: listID = str(randint(10000, 99999)) newsList = newsListformat data = newsapi.get_top_headlines( sources=code, language='en', ) ## url = newsapi+code+topnews ## print(url) ## response = urllib.request.urlopen(url) ## data = json.loads(response.read()) newsList['code'] = code newsList['list'] = data['articles'] newsList['index'] = 0 newsList['listID'] = listID newsList['uid'] = update.message.from_user.id print('\n') print('\n') print(newsList) x = newsLists.insert({ "code": code, "list": data['articles'], "index": 0, "listID": listID, "uid": update.message.from_user.id }) print(x) users.update({"uid": update.message.from_user.id}, {'$push': { 'listIDs': listID }}) users.update({"uid": update.message.from_user.id}, {'$push': { 'listIDs': listID }}) newsList2use = newsLists.find_one({"listID": listID}) x = "QUERY" + str(listID) + '\n' + '\n' + newsList2use['list'][ newsList2use['index']]['url'] update.message.reply_text(x, reply_markup=inlineNextKeyboard1, parse_mode='HTML') return