Created
June 21, 2018 12:12
-
-
Save omarlopesino/698170884d61da88f918cdde3b3c4edf to your computer and use it in GitHub Desktop.
Discord bot using api.ai to process messages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import discord | |
import asyncio | |
import apiai | |
import json | |
client = discord.Client() | |
// Api.ai access token. | |
CLIENT_ACCESS_TOKEN = 'access-token' | |
def query_apiai(query): | |
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN) | |
request = ai.text_request() | |
request.lang = 'es' # optional, default value equal 'en' | |
#request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>" | |
request.query = query | |
response = request.getresponse() | |
json_obj = json.loads(response.read().decode('utf-8')) | |
if 'messages' in json_obj['result']['fulfillment']: | |
return json_obj['result']['fulfillment']['messages'][0]['speech'] | |
else: | |
return False | |
@client.event | |
async def on_ready(): | |
print('Logged in as') | |
print(client.user.name) | |
print(client.user.id) | |
print('------') | |
@client.event | |
async def on_message(message): | |
if message.author == client.user: | |
return | |
apiai_response = query_apiai(message.content) | |
if apiai_response: | |
await client.send_message(message.channel, apiai_response) | |
discordbot_token = 'discord-bot-token' | |
client.run(discordbot_token); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment