· 2 years ago · Aug 14, 2023, 03:05 AM
1async def get_prefix(bot, ctx: commands.Context):
2 db = await aiosqlite.connect('prefixes.db')
3 await db.execute("""
4 CREATE TABLE IF NOT EXISTS prefixes (
5 guild_id INTEGER,
6 prefix STRING
7 )""")
8 cursor = await db.execute(f"SELECT * FROM prefixes WHERE guild_id = {ctx.guild.id}")
9 row = await cursor.fetchone()
10 if row is None:
11 prefix = "."
12 else:
13 prefix = str(row[1])
14
15 await db.commit()
16 await db.close()
17
18 return prefix
19
20class MyBot(commands.Bot):
21 def __init__(self):
22 intents = discord.Intents.default()
23 intents.message_content = True
24 super().__init__(intents=intents, command_prefix=get_prefix)
25
26 async def on_ready(self):
27 print(f"Logged in as {self.user} (ID: {self.user.id})")
28 print("------")
29
30 async def on_message(self, message: discord.Message):
31 if message.author == self.user:
32 return
33 try:
34 if message.mentions[0] == self.user:
35 await message.channel.send(f"My prefix for this server is {get_prefix}")
36
37 except Exception as e:
38 await message.reply(e)
39
40 await bot.process_commands(message)
41
42 async def on_command_error(self, ctx: commands.Context, error: commands.CommandError):
43 await ctx.reply(error, ephemeral=True)
44
45bot = MyBot()
46
47@bot.event
48async def on_guild_join(guild):
49 db = await aiosqlite.connect('prefixes.db')
50 cursor = await db.cursor()
51 await cursor.execute(f"SELECT * FROM prefixes WHERE guild_id = {guild.id}")
52 row = await cursor.fetchone()
53
54 if not row:
55 await cursor.execute("INSERT INTO prefixes (guild_id, prefix) VALUES(?, ?)", (guild.id, "."))
56 if row:
57 await cursor.execute("UPDATE prefixes SET prefix = ? WHERE guild_id = ?", (".", guild.id))
58
59 await db.commit()
60 await db.close()
61
62@bot.event
63async def on_guild_remove(guild):
64 db = await aiosqlite.connect('prefixes.db')
65 cursor = await db.cursor()
66 await cursor.execute(f"SELECT * FROM prefixes WHERE guild_id = {guild.id}")
67 row = await cursor.fetchone()
68 if row:
69 await cursor.execute(f"DELETE FROM prefixes WHERE guild_id = {guild.id}")
70
71 await db.commit()
72 await db.close()
73
74@bot.command(aliases=["setprefix"])
75@commands.has_permissions(manage_guild=True)
76async def change_prefix(ctx: commands.Context, prefix: str):
77
78 if len(prefix) > 10:
79 await ctx.send(f"{ctx.author.mention}, Prefix cannot be longer than 10 characters.")
80
81 db = await aiosqlite.connect('prefixes.db')
82 cursor = await db.cursor()
83 await cursor.execute(f"SELECT * FROM prefixes WHERE guild_id = {ctx.guild.id}")
84 row = await cursor.fetchone()
85
86 if not row:
87 await cursor.execute(f"INSERT INTO prefixes(guild_id, prefix) VALUES(?, ?)", (ctx.guild.id, prefix))
88 if row:
89 await cursor.execute("UPDATE prefixes SET prefix = ? WHERE guild_id = ?", (prefix, ctx.guild.id))
90
91 await db.commit()
92 await db.close()
93
94 await ctx.send(f"Changed the prefix to {prefix}")