forked from FeatureBaseDB/slothbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
235 lines (182 loc) · 6.83 KB
/
bot.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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import os
import json
import sys
import time
import random
import string
import discord, openai
from discord.ext import commands
from discord.ext.commands import Bot, Context
import config
from ai import ai
from database import featurebase_tables_schema, featurebase_tables_string, featurebase_query
from database import weaviate_update, weaviate_query
import weaviate
from prettytable import PrettyTable
# random words
from random_word import RandomWords
r = RandomWords()
def random_string(size=6, chars=string.ascii_letters + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
# discord intents
intents = discord.Intents.default()
# intents.message_content = True
client = discord.Client(intents=intents)
# discord log
def log_discord(message):
print("message-->", message)
# print("message content-->", message.content)
# print("message attachments-->", message.attachments)
# print("message id", message.author.id)
# print("name", message.author.name)
# print("discriminator", message.author.discriminator)
# ON READY
@client.event
async def on_ready():
# show reboot of bot
channel = client.get_channel(1067446497253265410)
# test FeatureBase connection
_tables = featurebase_tables_string()
await channel.send("-")
if not _tables:
await channel.send("Couldn't query FeatureBase for tables.")
else:
await channel.send("%s tables availabe via FeatureBase: %s" % (len(_tables.split(",")), _tables))
# connect to weaviate and ensure schema exists
try:
weaviate_client = weaviate.Client("http://localhost:8080")
# Need to reset Weaviate?
# weaviate_client.schema.delete_all()
# make schemas if none found
if not weaviate_client.schema.contains():
dir_path = os.path.dirname(os.path.realpath(__file__))
schema_file = os.path.join(dir_path, "weaviate_schema.json")
weaviate_client.schema.create(schema_file)
await channel.send("Connected to Weaviate instance.")
except Exception as ex:
# show vector database connection error
await channel.send("Can't connect to a Weaviate instance.")
print(ex)
return
# received a reaction
# we use this to move the document to the next step in the pipeline
@client.event
async def on_reaction_add(reaction, user):
channel = client.get_channel(reaction.message.channel.id)
if reaction.message.channel.id == 1067446497253265410:
await channel.send("Standby...running query.")
document = {"concepts": [reaction.message.content]}
result = weaviate_query(document, "History", 0.2)
print(result)
# refactor
# run until we get SQL, or an explaination/answer
if document.get('is_sql', False) != False:
document = featurebase_query(document)
if document.get('data', []) != []:
table_name = document.get('table')
table = featurebase_tables(table_name)[0]
_field_names = []
for field in table.get('fields'):
_field_names.append(field.get('name'))
pretty_table = PrettyTable()
pretty_table.field_names = _field_names
for entry in document.get('data'):
pretty_table.add_row(entry)
table_string = "```\n%s\n```" % pretty_table
await message.channel.send(document.get('explain'))
await message.channel.send(document.get('sql'))
await message.channel.send(table_string)
else:
await message.channel.send("It goes without saying, we have to be here.")
await message.channel.send(document.get('explain'))
return
# received a plain query from the user
@client.event
async def on_message(message):
# log discord message
# log_discord(message)
# if author is the bot, we ignore it
if message.author == client.user:
return
# stop bot from interactions in most channels
# use #offtopic and #bot-dev only
# allows op to interact everywhere
if message.channel.id not in [1067446497253265410, 1038459042345001061]:
if "slothbot" in message.content.lower():
if message.author.name != "Kord" and message.author != client.user:
await message.channel.send("Sorry %s, I can't work in here. See the #bot-dev channel!" % message.author.name)
return
# who wants dallE?
# creates images from a prompt
if message.content.lower().startswith("dream "):
# create document
document = {
"plain": message.content,
"author": message.author.name
}
url = ai("dream", document)
await message.channel.send(url)
return
# graph bot prototype
if "graphbot" in message.content.lower():
import plotly.express as px
import plotly.figure_factory as ff
import numpy as np
x1,y1 = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2))
u1 = np.cos(x1)*y1
v1 = np.sin(x1)*y1
fig = ff.create_quiver(x1, y1, u1, v1)
filename = "static/%s.png" % random_string(6)
fig.write_image(filename)
picture = discord.File(filename)
await message.channel.send(file=picture)
return
# graph bot prototype
if message.content.lower().startswith("help "):
# create document
document = {
"plain": message.content,
"author": message.author.name
}
result = ai("help", document)
await message.channel.send(result.get("explain"))
return
# someone is addressing slothbot, so respond
if "slothbot" in message.content.lower():
# create document
document = {
"plain": message.content,
"author": message.author.name,
# replace this with a weaviate query
# "history": history_thing
"tables": featurebase_tables_string(),
}
# retreive document results from AI
document = ai("query", document)
if document.get('template_file', "eject_document") == "eject_document":
if document.get('use_sql') and document.get('table_to_use'):
await message.channel.send("Ejecting document from the query pipeline. Use the :thumbsup: emoji to continue, or reply in a thread below to inject SQL.")
if document.get('chart_type'):
await message.channel.send("Would use the *%s* database projected to a %s." % (document.get('table_to_use'), document.get('chart_type')))
else:
await message.channel.send("Would use the *%s* database to run a query." % (document.get('table_to_use')))
else:
await message.channel.send("Ejecting document from the query pipeline.")
await message.channel.send(document.get("explain"))
print(document)
history_document = {
"author": document.get('author'),
"plain": document.get('plain'),
"explain": document.get('explain'),
"use_sql": document.get('use_sql'),
"use_chart": document.get('use_chart'),
"table_to_use": document.get('table_to_use'),
"type_of_chart": document.get('type_of_chart')
}
data_uuid = weaviate_update(history_document, "History")
print(data_uuid)
else:
await message.channel.send(document.get("explain"))
return
# entry point
client.run(config.discord_token)