-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
220 lines (180 loc) · 7.63 KB
/
main.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
import json
import traceback
import uuid
from typing import Optional
import nextcord
from nextcord.ext import commands
from cogs.admin_commands import AdminCommands
from logger import setup_logging
from screenshot import ScreenshotHandler
from site_navigator import PageNavigator
from view import View
### Logging setup ###
log = setup_logging().log
### Bot setup ###
with open("config.json", "r") as config_file:
config_data = json.load(config_file)
TOKEN = config_data["bot_token"]
CLIENT = commands.Bot(intents=nextcord.Intents().all())
admin_commands = AdminCommands(CLIENT)
CLIENT.add_cog(admin_commands)
@CLIENT.event
async def on_ready():
log.info("Bot Ready.")
CLIENT.start_time = nextcord.utils.utcnow()
await CLIENT.change_presence(
activity=nextcord.Activity(type=nextcord.ActivityType.listening, name="/waifu")
)
admin_commands.validate_admins()
connected_users = []
@CLIENT.slash_command(description="Build-a-waifu!")
async def waifu(
interaction: nextcord.Interaction,
co_operator: nextcord.Mentionable = nextcord.SlashOption(
name="co-op",
description="Allows other users to help you build your waifu.",
default=None,
required=False,
),
privacy: Optional[bool] = nextcord.SlashOption(
name="private",
description="Makes it so only you can see your waifus.",
default=False,
required=False,
),
):
"""Starts the bot."""
if not await check_permissions(interaction):
return
if interaction.user.id in connected_users:
await interaction.response.send_message(
"Whoops! One user cannot start me twice at the same time."
"You can continue making your waifu or press ❌ to exit.",
ephemeral=True,
delete_after=10,
)
return
connected_users.append(interaction.user.id)
session_id = uuid.uuid4()
if co_operator:
collaborator_type = 'Role' if isinstance(co_operator, nextcord.Role) else 'User'
collaborator_info = f'Co-operator: {co_operator}. Co-operator type: ({collaborator_type})'
else:
collaborator_info = ''
original_message = await interaction.response.send_message(
(
"Hi there! I'm WaifuBot!\n"
"I create waifus using <https://www.waifulabs.com>. Let's get started!"
"\n* You'll be presented with 4 grids of waifus, each based on your previous choice. "
"\n* Click the number corresponding to the waifu you like best in each grid or use these buttons:"
"\n❌ to exit, ⬅ to undo, ➡ to skip a stage, 🎲 to choose randomly, or 🔄 to refresh the grid."
"\n_(Progress: 1/4)_"
),
ephemeral=privacy,
)
navi = await PageNavigator.create_navi()
log.info(f"Page started for user '{interaction.user.name}'. {collaborator_info}")
View.stage[session_id] = 0
while View.stage[session_id] < 4 and not navi.page.isClosed():
await ScreenshotHandler(navi, interaction, original_message, co_operator).save_send_screenshot(session_id)
if View.stage[session_id] <= 3:
try: #in case the message was deleted
await original_message.edit(
(
"Okay! lets continue. Here's another grid for you to choose from:\n"
f"(_Progress: {View.stage[session_id] + 1}/4)_"
),
view=None,
)
except nextcord.errors.NotFound:
break
if not navi.page.isClosed():
await ScreenshotHandler(navi, interaction, original_message, co_operator).save_send_screenshot( session_id)
await original_message.edit(
content="Here's your waifu! Thanks for playing :slight_smile:"
)
await navi.page.close()
log.info(
f"Page closed for user '{interaction.user.name}', finished. {collaborator_info}"
)
elif navi.timed_out:
log.info(
f"Page closed for user '{interaction.user.name}', timed out. {collaborator_info}")
try:
await original_message.edit(
"Hey, anybody there? No? Okay, I'll shut down then :slight_frown:",
delete_after=10,
attachments=[],
view=None,
)
except nextcord.errors.HTTPException:
pass
else:
try:
await original_message.edit(
"Exiting...", delete_after=5, attachments=[], view=None
)
except nextcord.errors.HTTPException:
pass
log.info(
f"Page closed for user '{interaction.user.name}'. {collaborator_info}")
View.stage.pop(interaction.user.id, None)
connected_users.remove(interaction.user.id)
@CLIENT.slash_command(description="Submit a bug report.")
async def feedback(interaction: nextcord.Interaction):
"""Link to the issues page."""
await interaction.response.send_message(
("If you've encountered a bug or have a suggestion for Waifu Bot, "
"please head over to the issues page on Github: "
"<https://github.com/ranshaa05/WaifuLabs-Bot/issues>.\n"
"There, you can report bugs, suggest features, or ask for help with "
"any issues you're having.\n"
"Thanks for helping us make Waifu Bot better! :slight_smile:"),
ephemeral=True
)
REQUIRED_PERMISSIONS = ["view_channel", "manage_messages", "add_reactions"]
async def check_permissions(interaction):
"""Checks if the bot has the required permissions and notifies the user if not."""
if isinstance(interaction.channel, nextcord.abc.GuildChannel):
bot_role = interaction.guild.me.top_role
bot_channel_permissions = interaction.channel.permissions_for(interaction.guild.me)
missing_permissions = {
"role": [],
"channel": []
}
for permission in REQUIRED_PERMISSIONS:
if not getattr(bot_role.permissions, permission):
missing_permissions["role"].append(permission.replace("_", " ").title())
if not getattr(bot_channel_permissions, permission):
missing_permissions["channel"].append(permission.replace("_", " ").title())
if missing_permissions["role"] or missing_permissions["channel"]:
embed = nextcord.Embed(
title="⚠️ __Missing Permissions__",
description="Hey! I'm missing these permissions:",
color=0xFF0000,
)
for permission_type, permissions in missing_permissions.items():
if permissions:
embed.add_field(
name=f"❌ Missing in {permission_type}:",
value="\n".join(permissions),
inline=True,
)
embed.set_footer(
text="Please grant me these permissions so i can work properly!🙏"
)
await interaction.response.send_message(embed=embed)
return False
return True
@CLIENT.event
async def on_application_command_error(interaction: nextcord.Interaction, error: nextcord.DiscordException):
"""Handles errors that occur in application commands."""
log.error(f"####### an error occured #######\n{error}")
traceback.print_exception(type(error), error, error.__traceback__)
error_message = str(error).split(":")[1]
if error_message not in admin_commands.application_errors:
admin_commands.application_errors[error_message] = 1
else:
admin_commands.application_errors[error_message] += 1
if __name__ == "__main__":
CLIENT.run(TOKEN)