Skip to content
Permalink
766c5170eb
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
86 lines (60 sloc) 2.55 KB
import discord
import asyncio
import json
from datetime import datetime
from rasa_nlu.model import Interpreter
from .bot import ChatBot
class DiscordBot(ChatBot):
def start(self):
self.client = discord.Client()
# nested event handlers because self.client
# doesn't exist at class definition scope
@self.client.event
async def on_ready():
await self._ready()
@self.client.event
async def on_message(message):
await self._handle_message(message)
self._interpreter = Interpreter.load("./training/models/current/nlu")
self.client.run(self.config.token)
async def _ready(self):
print("DiscordBot running!")
async def _handle_message(self, message):
client = self.client
if message.author.bot:
return
if client.user in message.mentions:
# remove the first word
message_str = " ".join(message.content.split(" ")[1:])
interpreted = self._interpreter.parse(message_str)
print(json.dumps(interpreted, indent=2))
intent = interpreted["intent"]["name"]
entities = interpreted["entities"]
if intent == "greet":
await self.client.send_message(message.channel, "Hello World!")
elif intent == "get_weather":
await self.client.send_message(message.channel,
self.get_weather_summary(entities))
def get_weather_summary(self, entities: list) -> str:
ws = self.services["weather"]
if not entities:
# if no entities supplied, return minutely summary
w_info = ws.get_weather_at(51.5, 0)
return w_info["minutely"]["summary"]
get_entities = lambda name: [x for x in entities if x["entity"] == name]
periods = get_entities("period")
days = get_entities("day")
locations = get_entities("location")
times = get_entities("time")
summary = ""
# test for time periods
if periods:
# if it's a week, return weekly
p = periods[0]["value"].lower()
if p == "week":
return ws.get_weekly_summary(51.5, 0)
elif days:
d = days[0]["value"]
if d == "today":
return ws.get_hourly_summary(51.5, 0, datetime.today())
return "I don't understand that request"