-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchat-plus-wolframalpha.py
155 lines (118 loc) · 4.16 KB
/
chat-plus-wolframalpha.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
"""
Demo version of Discord chatbot with Wolfram|Alpha
Sprint 1 of Emporium of Digital Delights, May 2021
Team: Group the Boop
Authors: Andrew
Yousef
Contributions: Ewan Klein <[email protected]>
Rosalyn Pearson
Helen Williams
Last edited: 28 May 2021
"""
import json
from aiohttp import ClientSession
from discord.ext import commands
from munch import munchify
from os import getenv
from random import choice
from urllib.parse import quote_plus
#from loguru import logger
# required for running locally
from dotenv import load_dotenv
load_dotenv()
TOKEN = getenv('TOKEN')
APPID = getenv('APPID')
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.aiohttpsession = None
async def login(self, *args, **kwargs):
self.aiohttpsession = ClientSession()
await super().login(*args, **kwargs)
async def close(self):
await super().close()
if self.aiohttpsession:
await self.aiohttpsession.close()
bot = Bot(command_prefix="$")
with open("exchanges.json", "r") as f:
exchanges = json.load(f)
sessions = []
conversations = {}
async def wolframalpha(appid, msg):
async with msg.channel.typing():
if msg.author.id not in conversations:
conversations[msg.author.id] = munchify(
{"host": "", "id": "", "s": ""})
url = f"https://{conversations[msg.author.id].host or 'api.wolframalpha.com'}/v1/conversation.jsp?" \
f"appid={appid}" \
f"&i={quote_plus(msg.content)}"
if conversations[msg.author.id].id:
url += f"&conversationid={conversations[msg.author.id].id}"
if conversations[msg.author.id].s:
url += f"&s={conversations[msg.author.id].s}"
async with bot.aiohttpsession.request("GET", url) as resp:
response = munchify(await resp.json(content_type="application/json"))
if not hasattr(response, "error"):
conversations[msg.author.id].host = response.host + "/api"
conversations[msg.author.id].id = response.conversationID
conversations[msg.author.id].s = response.s if hasattr(
response, "s") else ""
return response.result
else:
raise ValueError(response.error)
def new_topic():
"""
Start talking about a random topic.
"""
topics = ["wasps", "ice cream", "school", "Fortnite",
"burgers", "hotels", "getting a suntan"]
topic = choice(topics) # choose a topic at random
phrases = [f"So what do you think about {topic}?",
f"Anyway, I really like {topic}!", f"That's really interesing but what about {topic}???"]
phrase = choice(phrases)
return phrase
async def respond(msg):
"""
Generate a response to the user input.
"""
user_input = msg.content.lower()
words = user_input.split()
response = responsecopy = new_topic()
for word in words:
if word in exchanges:
responses = exchanges[word]
response = choice(responses)
break
if response == responsecopy:
try:
response = await wolframalpha(APPID, msg)
except ValueError:
pass
return response
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
@bot.command()
async def hello(ctx):
"""Starts a new chatbot session"""
if ctx.author.id not in sessions:
sessions.append(ctx.author.id)
await ctx.reply("Hello, nice to meet you!")
else:
await ctx.reply("There is already an ongoing bot session!")
@bot.command()
async def bye(ctx):
"""Exits the chatbot session"""
if ctx.author.id in sessions:
sessions.remove(ctx.author.id)
await ctx.reply("It was nice chatting to you!")
else:
await ctx.reply("There is no active bot session!")
@bot.event
async def on_message(msg):
if (await bot.get_context(msg)).valid:
await bot.process_commands(msg)
return # Exit if the message invokes another command
if msg.author.id in sessions:
await msg.reply(await respond(msg))
bot.run(TOKEN)