-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
302 lines (240 loc) · 11.7 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import asyncio
import logging
from pathlib import Path
import uuid
import validators
import discord
from discord.interactions import Interaction
from discord.ext import commands, tasks
from discord.ui import Button, View
from dotenv import load_dotenv
import os
import yt_dlp as youtube_dl
import datetime
from subclasses import filebin, glyph_tools
make_ephemeral = False
# Load the environment variables from .env file
load_dotenv()
# Create a new bot instance
intents = discord.Intents()
intents.members = True
intents.message_content = True
bot = commands.AutoShardedBot(intents=intents, sync_commands=False, help_command=None)
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
# Create a logger with timestamp in the file name
def setup_logger():
"""
Setup the logger.
"""
log_file = f"bot_{timestamp}.log"
logger = logging.getLogger('bot.py')
logger.setLevel(logging.INFO)
# Create a file handler and set the log level
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.INFO)
# Create a formatter and add it to the file handler
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
# Add the file handler to the logger
logger.addHandler(file_handler)
return logger
logger = setup_logger()
# load all cogs within the cogs directory
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
try:
bot.load_extension(f'cogs.{filename[:-3]}')
logger.info(f"Loaded extension: {filename}")
except Exception as e:
logger.error(f"Failed to load extension: {filename}")
logger.error(f"Error: {str(e)}")
print(f"Error loading extension: {filename}")
print(f"Error: {str(e)}")
activity: str = "/help"
@bot.event
async def on_command_error(ctx, error):
"""
Event triggered when a command fails.
"""
logger.error(f"Command {ctx.command} failed with error: {str(error)}")
@bot.event
async def on_ready():
"""
Event triggered when the bot is ready.
"""
logger.info(f'Logged in as {bot.user.name}')
logger.info(f'ID: {bot.user.id}')
activity = "/help"
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name=activity))
# delete all commands and recreate them
await bot.sync_commands()
@tasks.loop(minutes=1)
async def change_activity():
"""
Change the bot's activity every 60 seconds.
"""
# Set the activity
global activity # make 'activity' a global variable so it can be accessed by the function
# Cycle through a list of activities
activities = ["/help", "Having fun", "Nya"]
activity = activities[(activities.index(activity) + 1) % len(activities)]
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name=activity))
change_activity.start()
@bot.slash_command(integration_types={discord.IntegrationType.guild_install, discord.IntegrationType.user_install}, name="dl_trim", description="Plays audio from a URL at a specific time")
async def dl_trim(ctx: discord.ApplicationContext,
url: str = discord.Option(name="audio_url", description="The audio file URL", required=True),
begin: float = discord.Option(name="start_time", description="The time to start playing the audio in seconds", default=0.0),
end: float = discord.Option(name="end_time", description="The time to stop playing the audio in seconds", default=None)):
"""
Command to play audio from a URL at a specific time.
"""
logger.info(f"{ctx.author} used /dl_trim command in {ctx.channel} on {ctx.guild}.")
# acknowledge the command without sending a response
await ctx.defer()
try:
if not validators.url(url):
await ctx.respond(content="Invalid URL provided.")
return
except Exception as e:
await ctx.respond(content=f"Error validating URL: {str(e)}", ephemeral=True)
return
ydl = youtube_dl.YoutubeDL()
try:
info = ydl.extract_info(url, download=False)
except youtube_dl.DownloadError:
await ctx.respond(content="Error extracting info from the URL.", ephemeral=True)
return
if end is None:
end = info['duration']
title = info['title']
title += f"_{uuid.uuid4()}"
# Validate begin and end times
try:
begin = float(begin)
end = float(end)
except ValueError:
await ctx.respond(content="Invalid begin or end time.", ephemeral=True)
return
if begin < 0.0 or end < 0.0 or begin > end or end > info['duration']:
await ctx.respond(content="Invalid begin or end time.", ephemeral=True)
return
# use youtube-dl to download the audio file from the url and trim it to the specified time range
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': f'{title}.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'quiet': True,
'no_warnings': True,
'nooverwrites': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'opus',
'preferredquality': '192',
}],
}
loop = asyncio.get_event_loop()
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
try:
await loop.run_in_executor(None, lambda: ydl.download([url]))
except youtube_dl.DownloadError as e:
await ctx.respond(content=f"Error downloading the audio file: {e}", ephemeral=True)
return
# Run ffmpeg using asyncio.create_subprocess_exec
ffmpeg_cmd = ['ffmpeg', '-i', f'{title}.opus', '-ab', '189k', '-ss', str(begin), '-t', str(end - begin), '-acodec', 'libopus', f'{title}.ogg']
process = await asyncio.create_subprocess_exec(*ffmpeg_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
stdout, stderr = await process.communicate()
if process.returncode != 0:
# Handle the error if ffmpeg failed
await ctx.respond(content=f"Error trimming the audio file: {stderr.decode()}", ephemeral=True)
return
# Send the audio file
try:
await ctx.respond(content="Here's your audio! Enjoy! 🎵", file=discord.File(f'{title}.ogg'))
finally:
# Clean up files
for extension in ['.opus', '.ogg']:
audio_file = Path(f'{title}{extension}')
if audio_file.is_file():
audio_file.unlink()
# when a button interaction times out remove the buttons
@bot.event
async def on_button_timeout(interaction: discord.Interaction):
await interaction.message.edit(view=None)
class FileBinButtons(discord.ui.View):
def __init__(self, url: str, bin: str, title: str, yt_url: str, begin: float, end: float, watermark: str, user: str):
super().__init__()
self.url = url
self.bin = bin
self.title = title
self.yt_url = yt_url
self.begin = begin
self.end = end
self.watermark = watermark
self.user = user
user_name_parts = user.rsplit('#', 1)[0].rsplit('#', 1)[0].split('#')
self.user_name = ''.join(user_name_parts[:-1])
self.user_id = int(user.split('#')[-1])
self.disable_on_timeout = True
self.timeout = 60
self.button_pressed = False
# Dynamically adding a button with a fixed URL
self.add_item(discord.ui.Button(label="Upload here", style=discord.ButtonStyle.link, url=self.url))
# Static custom_id for demonstration
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green, custom_id="confirm_bin", row=0)
async def delete_button(self, button: discord.ui.Button, interaction: discord.Interaction):
if self.button_pressed:
await interaction.response.send_message("Already confirmed.", ephemeral=True, delete_after=10)
return
self.button_pressed = True
if await filebin.check_for_nglyph_file_in_bin(self.bin):
await interaction.response.send_message(content=f"<:glyphSuccess:1223680541614801007> <@{self.user_id}> your filebin ({self.bin}) upload has been confirmed.", ephemeral=True, delete_after=15)
await filebin.lock_filebin(self.bin)
button.disabled = True
files = await filebin.get_files_in_bin(self.bin)
for file in files:
if file.endswith('.nglyph'):
filename = await filebin.download_file_from_bin(self.bin, file)
# copy file to new
else:
await interaction.response.send_message(content=f"<:glyphError:1223680333820596294> <@{self.user_id}> your filebin ({self.bin}) upload was not confirmed. Please try again.", ephemeral=True, delete_after=15)
self.button_pressed = False
await filebin.delete_filebin(self.bin)
@bot.slash_command(integration_types={discord.IntegrationType.guild_install, discord.IntegrationType.user_install}, name="create", description="Create a custom glyph without adding it to the database")
async def create(ctx: discord.ApplicationContext,
title: str = discord.Option(name="title", description="The title of the custom glyph", required=True),
url: str = discord.Option(name="url", description="The youtube URL of the audio", required=True),
begin: float = discord.Option(name="start_time", description="The time to start playing the audio in seconds", default=0.0),
end: float = discord.Option(name="end_time", description="The time to stop playing the audio in seconds", default=None),
watermark: str = discord.Option(name="watermark", description="The watermark to add to the audio", default="")):
"""
Command to create a custom glyph
"""
logger.info(f"{ctx.author.name} used /create command in {ctx.channel} on {ctx.guild}.")
# acknowledge the command without sending a response
await ctx.defer(ephemeral=True)
new_bin = await filebin.create_filebin(title=title)
filebin_url = f'https://filebin.net/{new_bin}'
if new_bin is None:
await ctx.respond(content="Error creating filebin link. Please try again later.", ephemeral=True)
return
view = FileBinButtons(url=filebin_url, bin=new_bin, title=title, yt_url=url, begin=begin, end=end, watermark=watermark, user=f'{ctx.author.name}#{ctx.author.id}')
await ctx.respond(content=f"Created custom filebin: {filebin_url}", view=view, ephemeral=True)
@bot.slash_command(integration_types={discord.IntegrationType.guild_install, discord.IntegrationType.user_install}, name="upload", description="Create and upload a custom glyph to the database")
async def upload(ctx: discord.ApplicationContext, name: str = discord.Option(name="name", description="The name of the custom glyph", required=True)):
"""
Command to create and upload a custom glyph
"""
logger.info(f"{ctx.author} used /upload command in {ctx.channel} on {ctx.guild}.")
# acknowledge the command without sending a response
await ctx.respond(content="Not done yet...")
@bot.slash_command(integration_types={discord.IntegrationType.guild_install, discord.IntegrationType.user_install}, name="search", description="Search our database for a custom glyph")
async def search(ctx: discord.ApplicationContext, name: str = discord.Option(name="name", description="The name of the custom glyph", required=True)):
"""
Command to search our database for a custom glyph
"""
logger.info(f"{ctx.author} used /search command in {ctx.channel} on {ctx.guild}.")
# acknowledge the command without sending a response
await ctx.respond(content="Not done yet...")
# Run the bot
bot.run(os.getenv('BOT_TOKEN'))