-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
170 lines (145 loc) · 6.6 KB
/
bot.py
File metadata and controls
170 lines (145 loc) · 6.6 KB
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
import datetime
import os
import asyncio
from typing import Literal, Optional
import sqlite3
import json
import discord
from discord.ext import commands
from preset import create_embed
with open('config.json', 'r') as f:
config = json.load(f)
token = config["token"]
logChannelId = config["logChannelId"]
guildId = config["GuildId"]
reportChannelId = config["reportChannelId"]
botName = config["botName"]
MY_GUILD = discord.Object(id=guildId)
async def change_bot_status(guild_count, total_member):
await client.wait_until_ready()
while not client.is_closed():
await client.change_presence(activity=discord.Game(name="docs : projectBot.xyz"))
await asyncio.sleep(4)
await client.change_presence(activity=discord.Game(name="{} members in {} servers".format(total_member, guild_count)))
await asyncio.sleep(4)
class MyBot(commands.Bot):
def __init__(self, *, intents: discord.Intents):
super().__init__(command_prefix='!', intents=intents)
self.logChannelId = logChannelId
self.remove_command("help")
self.reportChannelId = reportChannelId
def create_tables(self, guild_id):
self.cursor.execute(f'''CREATE TABLE IF NOT EXISTS projects_{guild_id}
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
description TEXT,
created_at TEXT,
updated_at TEXT,
priority TEXT,
status TEXT
assigned_to TEXT,
authorized_to_change TEXT
start_date TEXT,
due_date TEXT,
progress_status TEXT,
owner TEXT,
comments TEXT
)
''')
self.cursor.execute(f'''CREATE TABLE IF NOT EXISTS tasks_{guild_id}
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER,
name TEXT,
description TEXT,
created_at TEXT,
updated_at TEXT,
priority TEXT,
status TEXT,
assigned_to TEXT,
authorized_to_change TEXT,
start_date TEXT,
due_date TEXT,
progress_status TEXT,
users_notes TEXT,
comments TEXT
)''')
async def setup_database(self):
self.conn = sqlite3.connect('db/mydatabase.db')
self.cursor = self.conn.cursor()
print(f"[{datetime.datetime.now()}] [\033[1;35mCONSOLE\033[0;0m]: Database [\033[1;35mSQLite\033[0;0m] setup.")
try:
for guild in self.guilds:
self.create_tables(guild.id)
print(f"[{datetime.datetime.now()}] [\033[1;35mCONSOLE\033[0;0m]: tables [\033[1;35mSQLite\033[0;0m] created.")
except Exception as e:
print(f"[{datetime.datetime.now()}] [\033[91mERROR\033[0;0m]: {e}")
self.conn.commit()
async def setup_hook(self):
await load_all_cogs()
try:
self.tree.copy_global_to(guild=MY_GUILD)
self.tree.clear_commands(guild=MY_GUILD)
await self.tree.sync()
print(f"[{datetime.datetime.now()}] [\033[1;36mCONSOLE\033[0;0m]: Slash commands synchronized with guilds")
except Exception as e:
print(f"[{datetime.datetime.now()}] [\033[91mmERROR\033[0;0m]: {e}")
async def close(self):
await super().close()
self.conn.close()
intents = discord.Intents.all()
client = MyBot(intents=intents)
async def load_all_cogs():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await client.load_extension(f"cogs.{filename[:-3]}")
@client.event
async def on_ready():
try:
await client.setup_database()
print(f"[{datetime.datetime.now()}] [\033[1;32mCONSOLE\033[0;0m]: {botName} ready")
log_channel = client.get_channel(int(logChannelId))
now = datetime.datetime.now(datetime.timezone.utc)
embed = create_embed(client, "info", "Info", f"> {botName} ready", fields={"date :" : f"> {now.strftime('%Y-%m-%d %H:%M:%S')}"})
guild_count = len(client.guilds)
total_members = sum(guild.member_count for guild in client.guilds)
client.loop.create_task(change_bot_status(guild_count, total_members))
await log_channel.send(embed=embed)
except BaseException as error:
print('An exception occurred: {}'.format(error))
@client.command()
@commands.is_owner()
async def sync(ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "*":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()
await ctx.send(f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}")
return
ret = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
ret += 1
await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")
@client.event
async def on_guild_join(guild):
try:
guild_id = guild.id
client.create_tables(guild_id)
print(f"[{datetime.datetime.now()}] [\033[1;35mCONSOLE\033[0;0m]: Tables created for guild: [\033[1;35m{guild.name}\033[0;0m] - [\033[1;35m{guild.id}\033[0;0m] .")
except Exception as e:
print(f"[{datetime.datetime.now()}] [\033[91mCONSOLE\033[0;0m]: An error occurred while creating tables for guild: [\033[1;35m{guild.name}\033[0;0m] - [\033[1;35m{guild.id}\033[0;0m] : {e}")
client.run(token, log_handler=None)