· 6 years ago · Dec 09, 2019, 11:36 PM
1# bot.py
2import os
3
4import discord
5from discord.ext import commands
6import sqlite3
7from sqlite3 import Error
8import json
9from discord import Webhook, RequestsWebhookAdapter
10from tabulate import tabulate
11import unicodedata
12import ast, sys
13from collections.abc import Sequence
14from discord.ext.commands import has_permissions, MissingPermissions
15import asyncio
16import random
17
18os.environ["LANG"] = "en_US.UTF-8"
19
20def create_connection(db_file):
21 """ create a database connection to the SQLite database
22 specified by db_file
23 :param db_file: database file
24 :return: Connection object or None
25 """
26 conn = None
27 try:
28 conn = sqlite3.connect(db_file)
29 return conn
30 except Error as e:
31 print(e)
32
33 return conn
34
35def create_table(conn, create_table_sql):
36 """ create a table from the create_table_sql statement
37 :param conn: Connection object
38 :param create_table_sql: a CREATE TABLE statement
39 :return:
40 """
41 try:
42 c = conn.cursor()
43 c.execute(create_table_sql)
44 except Error as e:
45 print(e)
46
47def dbmake():
48 database = "discord.db"
49
50 sql_create_library_table = """ CREATE TABLE IF NOT EXISTS library (
51 name text PRIMARY KEY,
52 link text NOT NULL,
53 description text
54 ); """
55
56 sql_create_catagory_table = """ CREATE TABLE IF NOT EXISTS catagories (
57 name text,
58 catagory text NOT NULL
59 ); """
60 # create a database connection
61 conn = create_connection(database)
62
63 # create tables
64 if conn is not None:
65 # create library table
66 create_table(conn, sql_create_library_table)
67 create_table(conn, sql_create_catagory_table)
68 else:
69 print("Error! cannot create the database connection.")
70
71if __name__ == '__main__':
72 dbmake()
73
74def add_entry(name, link, description, catagory):
75 database = "discord.db"
76 conn = create_connection(database)
77 with conn:
78 library = (name, link, description);
79 cata= (name, catagory);
80 main = ''' INSERT INTO library(name,link,description)
81 VALUES(?,?,?) '''
82 catagories = ''' INSERT INTO catagories(name,catagory)
83 VALUES(?,?) '''
84 cur = conn.cursor()
85 cur.execute(main, library)
86 cur.execute(catagories, cata)
87
88def delete_entry(name):
89 database = "discord.db"
90 conn = create_connection(database)
91 with conn:
92 sqllib = 'DELETE FROM library WHERE name=?'
93 sqlcata = 'DELETE FROM catagories WHERE name=?'
94 cur = conn.cursor()
95 cur.execute(sqllib, (name,))
96 cur.execute(sqlcata, (name,))
97 conn.commit()
98
99def find_entry(name):
100 database = "discord.db"
101 conn = create_connection(database)
102 with conn:
103 cur = conn.cursor()
104 cur.execute("SELECT * FROM library WHERE name=? COLLATE NOCASE", (name,))
105 result = cur.fetchone()
106 name, link, description = result[0], result[1], result[2]
107 return (name, link, description)
108
109def find_catagories():
110 database = "discord.db"
111 conn = create_connection(database)
112 with conn:
113 cur = conn.cursor()
114 cur.execute(" SELECT DISTINCT catagory FROM catagories ORDER BY catagory; ")
115 result = cur.fetchall()
116 return (result)
117
118def find_catagory(catagory):
119 database = "discord.db"
120 conn = create_connection(database)
121 sql = ''' SELECT library.name,library.link,library.description,catagories.catagory
122 FROM library
123 INNER JOIN catagories
124 ON library.name=catagories.name
125 WHERE catagories.catagory=? '''
126 with conn:
127 cur = conn.cursor()
128 cur.execute(sql, [catagory])
129 result = cur.fetchall()
130 #print (result)
131 #name, link, description, catagory = result[0], result[1], result[2], result[3]
132 return (result)
133
134def show_all():
135 database = "discord.db"
136 conn = create_connection(database)
137 conn.text_factory = lambda x: str(x, 'utf-8')
138 conn.row_factory = sqlite3.Row
139 with conn:
140 cur = conn.cursor()
141 cur.execute("SELECT * FROM library")
142 rows = cur.fetchall()
143 #return json.dumps(rows) #CREATE JSON
144
145
146 for row in rows:
147 print(f"{row['name']}, {row['link']}, {row['description']}.")
148
149
150 #for row in rows:
151 # name, link, description = row[0], row[1], row[2]
152 # print('{0} {1} {2}'.format(name, link, description))
153 # arraytest.append('{0} {1} {2}'.format(name, link, description))
154 #print(arraytest)
155 return (rows)
156
157def add_interactive(name, link, description):
158 database = "discord.db"
159 conn = create_connection(database)
160 with conn:
161 library = (name, link, description);
162 main = ''' INSERT INTO library(name,link,description)
163 VALUES(?,?,?) '''
164 cur = conn.cursor()
165 cur.execute(main, library)
166
167def add_interactive_catagories(name, catagory):
168 database = "discord.db"
169 conn = create_connection(database)
170 with conn:
171 cata= (name, catagory);
172 catagories = ''' INSERT INTO catagories(name,catagory)
173 VALUES(?,?) '''
174 cur = conn.cursor()
175 cur.execute(catagories, cata)
176
177def make_sequence(seq):
178 if seq is None:
179 return ()
180 if isinstance(seq, Sequence) and not isinstance(seq, str):
181 return seq
182 else:
183 return (seq,)
184
185def message_check(ctx, channel=None, author=None, content=None, ignore_bot=True, lower=True):
186 channel = make_sequence(channel)
187 author = make_sequence(author)
188 content = make_sequence(content)
189 if lower:
190 content = tuple(c.lower() for c in content)
191 def check(message):
192 if ignore_bot and message.author.bot:
193 return False
194 if channel and message.channel not in channel:
195 return False
196 if author and message.author not in author:
197 return False
198 actual_content = message.content.lower() if lower else message.content
199 if content and actual_content not in content:
200 return False
201 if len(message.content) >= 5:
202 return False
203 return True
204 return check
205
206token = "NjQ5MDQxNDMxMDA4MTE2NzQ4.Xd3Ciw.Ox5qzYVXbcaF38Jnp5KRqByjCpM"
207guild = "KareBox Test Guild"
208
209client = discord.Client()
210
211@client.event
212async def on_ready():
213 for guild in client.guilds:
214 if guild.name == guild:
215 break
216
217 print(
218 f'{client.user} is connected to the following guild:\n'
219 f'{guild.name}(id: {guild.id})'
220 )
221
222def chunks(lst, n):
223 """Yield successive n-sized chunks from lst."""
224 for i in range(0, len(lst), n):
225 yield lst[i:i + n]
226
227bot = commands.Bot(command_prefix='!')
228
229@bot.command(pass_context=True, name='library', help='save/long save/remove/show/showall')
230async def library(ctx, *args):
231 if args[0] == 'save':
232 if (len(args)) == 1:
233 author = ctx.message.author
234 await author.send("```" + "\n" + "Starting to add new entry with hand holding mode\nBot will time out in 2 minutes without response" + "```")
235 await author.send("```" + "\n" + "Please type the name of the entry\nOne word is highly recommend\neg: My-Cool-Name" + "```")
236 try:
237 name = await bot.wait_for("message", timeout=120.0, check=message_check(ctx, channel=ctx.author.dm_channel))
238 except asyncio.TimeoutError:
239 await author.send("```" + "\n" + "You timed out, bitch" + "```")
240 return
241 await author.send("```" + "\n" + "Next insert the linky link you want to add" + "```")
242 try:
243 link = await bot.wait_for("message", timeout=120.0, check=message_check(channel=ctx.author.dm_channel))
244 except asyncio.TimeoutError:
245 await author.send("```" + "\n" + "You timed out, bitch" + "```")
246 return
247 await author.send("```" + "\n" + "Enter a description next please" + "```")
248 try:
249 description = await bot.wait_for("message", timeout=120.0, check=message_check(channel=ctx.author.dm_channel))
250 except asyncio.TimeoutError:
251 await author.send("```" + "\n" + "You timed out, bitch" + "```")
252 return
253 await author.send("```" + "\n" + "Catagories are last \nPlease use a space seperated list\n eg: Catagory1 Catagory2 Catagory3" + "```")
254 caties = find_catagories()
255 output = ("```" + "\n" + "A list of previously used catagories for your viewing pleaseure\n" + tabulate(caties, tablefmt="plain", headers=["Catagory"]) + "```")
256 await author.send(output)
257 try:
258 catagories = await bot.wait_for("message", timeout=120.0, check=message_check(channel=ctx.author.dm_channel))
259 except asyncio.TimeoutError:
260 await author.send("```" + "\n" + "You timed out, bitch" + "```")
261 return
262 catagories = str.split(catagories.content)
263 add_interactive(name.content, link.content, description.content)
264 for index in range(len(catagories)):
265 add_interactive_catagories(name.content, catagories[index])
266 await author.send("```" + "\n" + "Entry saved" + "```")
267 else:
268 add_entry(args[1], args[2], args[3], args[4])
269 await ctx.send(len(args))
270 #elif args[0] == 'update':
271 # update_entry(args[2], args[3], args[1])
272 # response = 'update'
273 # await ctx.send('update')
274 elif args[0] == 'remove':
275 delete_entry(args[1])
276 await ctx.send('removed')
277 elif args[0] == 'show':
278 name, link, description = find_entry(args[1])
279 await ctx.send('{0} \n {1}'.format(name, link))
280 elif args[0] == 'catagory':
281 cata = find_catagory(args[1])
282 output = ("```" + "\n" + tabulate(cata, tablefmt="plain", headers=["Name", "Link", "Description", "Catagory"]) + "```")
283 await ctx.send(output)
284 elif args[0] == 'showall':
285 rows = show_all()
286 for row in rows:
287 print(f"{row['name']}, {row['link']}, {row['description']}.")
288 #for row in rows:
289 # print(row[2])
290 # if len(row[2]) > 10:
291 # c = row[2]
292 # row[2] = c[:10]
293 # print(c)
294
295 #for chunk in [show_all_entrys[i:i+1900] for i in range(0, len(show_all_entrys), 1900)]:
296 #short_table = [[(c if len(c) < 10 else c[:7] + "...") for row{2}] for row in show_all_entrys]
297 #short_table = [[(c if len(c) < 10 else c[:7] + "...") for row[2] in row] for row in lst]
298 #output = ("```" + "\n" + tabulate(short_table, tablefmt="github", headers=["Name", "Link", "Description"]) + "```")
299 short_table = [[(c if len(c) < 20 else c[:17] + "...") for c in row] for row in rows]
300 for row in short_table:
301 print(row)
302 output = (tabulate(short_table, tablefmt="github", headers=["Name", "Link", "Description"]))
303 output = (tabulate(short_table, tablefmt="github", headers=["Name", "Link", "Description"]))
304 for chunk in [output[i:i+1900] for i in range(0, len(output), 1900)]:
305 print(chunk)
306 await ctx.send("```" + "\n" + chunk + "```")
307
308 else:
309 await ctx.send("No command recognized.")
310@library.error
311async def library_error(ctx, error):
312 author = ctx.message.author
313 if isinstance(error, commands.CheckFailure):
314 await author.send("nothing to see here comrade.")
315
316
317@bot.command(pass_context=True, name='karebox', help='save/long save/update/remove/show/showall')
318@has_permissions(administrator=True)
319async def karebox(ctx):
320 await ctx.send("karebox is the bestbox")
321@karebox.error
322async def karebox_error(ctx, error):
323 if isinstance(error, MissingPermissions):
324 await ctx.send("Error")
325bot.run(token)