properly handle private responses

This commit is contained in:
Jonas Leder 2026-03-25 20:39:35 +01:00
commit 2b02039e98
6 changed files with 113 additions and 70 deletions

View file

@ -4,7 +4,7 @@ import logging
import nextcord
import runtime
from utils import interaction_log_context, send_response
from utils import interaction_log_context
startuptime = runtime.time()
@ -21,4 +21,4 @@ async def about(interaction: nextcord.Interaction):
embed.add_field(name="Uptime", value=uptime, inline=True)
embed.add_field(name="Servers", value=str(len(runtime.bot.guilds)), inline=True)
embed.add_field(name="Invite", value=runtime.inviteURL, inline=True)
await send_response(interaction, embed=embed)
await interaction.response.send_message(embed=embed)

View file

@ -8,7 +8,7 @@ import radioCommands # noqa: F401
from checkVideos import checkVideos
from heartBeatTask import hearBeat
from radioTask import checkForNextTrack
from utils import interaction_log_context, log_exception, send_response
from utils import interaction_log_context, log_exception
runtime.logger.info("Welcome to DJ Bot, initializing files")
@ -46,14 +46,23 @@ async def on_application_command(interaction):
async def on_application_command_error(interaction, error):
if isinstance(error, PermissionError):
runtime.logger.warning("Permission denied: %s error=%s", interaction_log_context(interaction), error)
await send_response(interaction, str(error), ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send(str(error), ephemeral=True)
else:
await interaction.response.send_message(str(error), ephemeral=True)
return
if isinstance(error, ValueError):
runtime.logger.warning("Invalid slash command usage: %s error=%s", interaction_log_context(interaction), error)
await send_response(interaction, str(error), ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send(str(error), ephemeral=True)
else:
await interaction.response.send_message(str(error), ephemeral=True)
return
log_exception("Unhandled application command error: %s error=%s", interaction_log_context(interaction), error)
await send_response(interaction, "An unexpected error occurred while running this command.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("An unexpected error occurred while running this command.", ephemeral=True)
else:
await interaction.response.send_message("An unexpected error occurred while running this command.", ephemeral=True)
async def checkVideosTask():

View file

@ -5,7 +5,7 @@ import nextcord
import runtime
from command_guards import require_guild, require_role_access
from utils import interaction_log_context, log_exception, send_response
from utils import interaction_log_context, log_exception
command_logger = logging.getLogger("discordyoutubemonitor.commands.general")
@ -23,22 +23,24 @@ async def register(interaction: nextcord.Interaction, registration_key: str, ser
[target_server, registration_key],
)
if dbcursor.fetchone() is None:
await send_response(interaction, "wrong key", ephemeral=True)
await interaction.response.send_message("wrong key", ephemeral=True)
command_logger.warning("Register failed: invalid key for server %s", target_server)
else:
dbcursor.execute(
"UPDATE registeredServer SET registered=1 WHERE Server=%s AND registerKey=%s",
[target_server, registration_key],
)
await send_response(
interaction,
await interaction.response.send_message(
"The Server has been registered and the bot can now be used.",
ephemeral=True,
)
command_logger.info("Register succeeded for server %s", target_server)
except Exception:
log_exception("Register command failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Registration failed.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Registration failed.", ephemeral=True)
else:
await interaction.response.send_message("Registration failed.", ephemeral=True)
finally:
dbcursor.close()
@ -54,7 +56,7 @@ async def ping(interaction: nextcord.Interaction):
title=":ping_pong: | Pong!",
description="```prolog\nLatency :: " + str(round(runtime.bot.latency * 1000)) + "ms\nResponse :: " + str(delta) + "ms```",
)
await send_response(interaction, embed=embed)
await interaction.response.send_message(embed=embed, ephemeral=True)
@runtime.bot.slash_command(description="Allow a role to use the bot")
@ -63,11 +65,14 @@ async def addadmin(interaction: nextcord.Interaction, server_role: nextcord.Role
try:
await require_role_access(interaction)
dbcursor.execute("INSERT INTO adminRoles (Server, roleID) VALUES (%s, %s)", [interaction.guild.id, server_role.id])
await send_response(interaction, "Added " + server_role.name + " to the list of Roles with bot access")
await interaction.response.send_message("Added " + server_role.name + " to the list of Roles with bot access")
command_logger.info("Added admin role %s on guild %s", server_role.id, interaction.guild.id)
except Exception:
log_exception("Addadmin failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to add the role.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to add the role.", ephemeral=True)
else:
await interaction.response.send_message("Failed to add the role.", ephemeral=True)
finally:
dbcursor.close()
@ -78,11 +83,14 @@ async def removeadmin(interaction: nextcord.Interaction, role: nextcord.Role):
try:
await require_role_access(interaction)
dbcursor.execute("DELETE FROM adminRoles WHERE Server=%s AND roleID=%s", [interaction.guild.id, role.id])
await send_response(interaction, "Removed " + role.name + " from the list of Roles with bot access")
await interaction.response.send_message("Removed " + role.name + " from the list of Roles with bot access")
command_logger.info("Removed admin role %s on guild %s", role.id, interaction.guild.id)
except Exception:
log_exception("Removeadmin failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to remove the role.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to remove the role.", ephemeral=True)
else:
await interaction.response.send_message("Failed to remove the role.", ephemeral=True)
finally:
dbcursor.close()
@ -91,4 +99,4 @@ async def removeadmin(interaction: nextcord.Interaction, role: nextcord.Role):
async def changeprefix(interaction: nextcord.Interaction):
await require_role_access(interaction)
command_logger.info("Changeprefix requested after slash migration: %s", interaction_log_context(interaction))
await send_response(interaction, "This bot now uses slash commands, so custom prefixes are no longer required.")
await interaction.response.send_message("This bot now uses slash commands, so custom prefixes are no longer required.")

View file

@ -5,7 +5,7 @@ import nextcord
import runtime
from checkVideo import checkVideo
from command_guards import require_monitor_access
from utils import defer_response, interaction_log_context, log_exception, send_response
from utils import defer_response, interaction_log_context, log_exception
command_logger = logging.getLogger("discordyoutubemonitor.commands.monitor")
@ -22,7 +22,7 @@ async def monitor(interaction: nextcord.Interaction, youtube_video_url: str):
dbcursor = runtime.get_db_cursor()
try:
await require_monitor_access(interaction)
await defer_response(interaction)
await defer_response(interaction, ephemeral=True)
command_logger.info("Monitor requested: %s url=%s", interaction_log_context(interaction), youtube_video_url)
response = await fetch_youtube_video_metadata(youtube_video_url)
videoID = response["thumbnail_url"].split("/vi/")[1].split("/hqdefault.jpg")[0]
@ -42,11 +42,14 @@ async def monitor(interaction: nextcord.Interaction, youtube_video_url: str):
dbcursor.execute("UPDATE VIDEOS SET messageID=%s, channelID=%s WHERE id=%s", [message.id, interaction.channel.id, monitor_id])
dbcursor.execute("SELECT * FROM VIDEOS WHERE id=%s", [monitor_id])
await checkVideo(dbcursor.fetchone())
await send_response(interaction, "Monitoring created for `" + videoID + "`.", ephemeral=True)
await interaction.followup.send("Monitoring created for `" + videoID + "`.", ephemeral=True)
command_logger.info("Monitor created: guild=%s video=%s message=%s", interaction.guild.id, videoID, message.id)
except Exception:
log_exception("Monitor command failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to create the monitor.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to create the monitor.", ephemeral=True)
else:
await interaction.response.send_message("Failed to create the monitor.", ephemeral=True)
finally:
dbcursor.close()
@ -66,13 +69,16 @@ async def updatemonitor(interaction: nextcord.Interaction, youtube_video_url: st
)
result = dbcursor.fetchone()
if result is None:
await send_response(interaction, "No monitor job for this video was found in this channel.", ephemeral=True)
await interaction.followup.send("No monitor job for this video was found in this channel.", ephemeral=True)
return
await checkVideo(result)
await send_response(interaction, "Monitor updated for `" + videoID + "`.", ephemeral=True)
await interaction.followup.send("Monitor updated for `" + videoID + "`.", ephemeral=True)
except Exception:
log_exception("Updatemonitor failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to update the monitor.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to update the monitor.", ephemeral=True)
else:
await interaction.response.send_message("Failed to update the monitor.", ephemeral=True)
finally:
dbcursor.close()
@ -93,8 +99,7 @@ async def monitorsettings(interaction: nextcord.Interaction, setting_name: str =
dbcursor.execute("INSERT INTO monitorConfig (Server) VALUES (%s)", [interaction.guild.id])
if setting_name is None:
await send_response(
interaction,
await interaction.response.send_message(
"Use `/monitorsettings setting_name:<name> value:<value>`.\nAvailable settings: `viewCounter`, `likeCounter`, `style`, `showLastUpdate`, `pingMessage`.",
)
return
@ -103,22 +108,22 @@ async def monitorsettings(interaction: nextcord.Interaction, setting_name: str =
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=%s", [interaction.guild.id])
result = dbcursor.fetchone()
if setting_name == "viewCounter":
await send_response(interaction, setting_name + ": " + ("on" if result["showViewCounter"] else "off"))
await interaction.response.send_message(setting_name + ": " + ("on" if result["showViewCounter"] else "off"))
elif setting_name == "likeCounter":
await send_response(interaction, setting_name + ": " + ("on" if result["showLikeCounter"] else "off"))
await interaction.response.send_message(setting_name + ": " + ("on" if result["showLikeCounter"] else "off"))
elif setting_name == "showLastUpdate":
await send_response(interaction, setting_name + ": " + ("on" if result["showLastUpdate"] else "off"))
await interaction.response.send_message(setting_name + ": " + ("on" if result["showLastUpdate"] else "off"))
elif setting_name == "style":
await send_response(interaction, setting_name + ": " + ("footer" if result["likeAndViewsAsField"] else "field"))
await interaction.response.send_message(setting_name + ": " + ("footer" if result["likeAndViewsAsField"] else "field"))
elif setting_name == "pingMessage":
await send_response(interaction, setting_name + ": " + result["pingMessage"])
await interaction.response.send_message(setting_name + ": " + result["pingMessage"])
else:
await send_response(interaction, "Unknown setting.", ephemeral=True)
await interaction.response.send_message("Unknown setting.", ephemeral=True)
return
if setting_name == "pingMessage":
dbcursor.execute("UPDATE monitorConfig SET pingMessage=%s WHERE Server=%s", [value, interaction.guild.id])
await send_response(interaction, "New message on block change is: " + value)
await interaction.response.send_message("New message on block change is: " + value)
return
state = "1" if value == "1" else "0"
@ -133,13 +138,16 @@ async def monitorsettings(interaction: nextcord.Interaction, setting_name: str =
tableName = "likeAndViewsAsField"
if tableName == "":
await send_response(interaction, "Unknown setting.", ephemeral=True)
await interaction.response.send_message("Unknown setting.", ephemeral=True)
return
dbcursor.execute("UPDATE monitorConfig SET " + tableName + "=%s WHERE Server=%s", [state, interaction.guild.id])
await send_response(interaction, "Updated " + setting_name + ", new state is " + value)
await interaction.response.send_message("Updated " + setting_name + ", new state is " + value)
except Exception:
log_exception("Monitorsettings failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to update monitor settings.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to update monitor settings.", ephemeral=True)
else:
await interaction.response.send_message("Failed to update monitor settings.", ephemeral=True)
finally:
dbcursor.close()

View file

@ -8,7 +8,7 @@ import runtime
from command_guards import require_music_disabled, require_music_enabled
from permissionCheck import checkIfPremiumAsync
from radioTask import ensure_player_connected, load_next_track
from utils import interaction_log_context, log_exception, send_response
from utils import interaction_log_context, log_exception
command_logger = logging.getLogger("discordyoutubemonitor.commands.radio")
@ -32,10 +32,13 @@ async def stop(interaction: nextcord.Interaction):
if player is not None:
await player.stop()
await player.disconnect()
await send_response(interaction, "The bot was stopped by <@" + str(interaction.user.id) + ">")
await interaction.response.send_message("The bot was stopped by <@" + str(interaction.user.id) + ">")
except Exception:
log_exception("Stop command failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to stop the bot.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to stop the bot.", ephemeral=True)
else:
await interaction.response.send_message("Failed to stop the bot.", ephemeral=True)
finally:
dbcursor.close()
@ -53,10 +56,13 @@ async def start(interaction: nextcord.Interaction):
player = await ensure_player_connected(interaction.guild.id, result["PlayChannel"])
if player is not None and getattr(player, "current", None) is None:
await load_next_track(player, result["youtubeChannelID"], interaction.guild.id)
await send_response(interaction, "The bot was started by <@" + str(interaction.user.id) + ">")
await interaction.response.send_message("The bot was started by <@" + str(interaction.user.id) + ">")
except Exception:
log_exception("Start command failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to start the bot.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to start the bot.", ephemeral=True)
else:
await interaction.response.send_message("Failed to start the bot.", ephemeral=True)
finally:
dbcursor.close()
@ -71,8 +77,7 @@ async def changechannel(interaction: nextcord.Interaction):
try:
channel = interaction.user.voice.channel
except Exception:
await send_response(
interaction,
await interaction.response.send_message(
"To change the MusicBot Channel you have to connect to a voice channel and then run this command",
ephemeral=True,
)
@ -84,10 +89,13 @@ async def changechannel(interaction: nextcord.Interaction):
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=%s", [interaction.guild.id])
result = dbcursor.fetchone()
await load_next_track(player, result["youtubeChannelID"], interaction.guild.id)
await send_response(interaction, "Playback channel updated to <#" + str(channel.id) + ">")
await interaction.response.send_message("Playback channel updated to <#" + str(channel.id) + ">")
except Exception:
log_exception("Changechannel failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to change the channel.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to change the channel.", ephemeral=True)
else:
await interaction.response.send_message("Failed to change the channel.", ephemeral=True)
finally:
dbcursor.close()
@ -98,17 +106,20 @@ async def volume(interaction: nextcord.Interaction, volume: int):
await require_music_enabled(interaction)
command_logger.info("Volume requested: %s volume=%s", interaction_log_context(interaction), volume)
if volume < 0 or volume > 100:
await send_response(interaction, "Volume has to be between 0 and 100", ephemeral=True)
await interaction.response.send_message("Volume has to be between 0 and 100", ephemeral=True)
return
player = get_guild_player(interaction)
if player is None:
await send_response(interaction, "Nothing is currently playing.", ephemeral=True)
await interaction.response.send_message("Nothing is currently playing.", ephemeral=True)
return
await player.set_volume(volume)
await send_response(interaction, "Volume set to " + str(volume) + "%")
await interaction.response.send_message("Volume set to " + str(volume) + "%")
except Exception:
log_exception("Volume command failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to change the volume.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to change the volume.", ephemeral=True)
else:
await interaction.response.send_message("Failed to change the volume.", ephemeral=True)
@runtime.bot.slash_command(description="Skip the current mix")
@ -119,17 +130,20 @@ async def skip(interaction: nextcord.Interaction):
command_logger.info("Skip requested: %s", interaction_log_context(interaction))
player = get_guild_player(interaction)
if player is None:
await send_response(interaction, "Nothing is currently playing.", ephemeral=True)
await interaction.response.send_message("Nothing is currently playing.", ephemeral=True)
return
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=%s", [interaction.guild.id])
result = dbcursor.fetchone()
await player.stop()
await load_next_track(player, result["youtubeChannelID"], interaction.guild.id)
await send_response(interaction, "Skipped the current track.")
await interaction.response.send_message("Skipped the current track.")
except Exception:
log_exception("Skip command failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to skip the current track.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to skip the current track.", ephemeral=True)
else:
await interaction.response.send_message("Failed to skip the current track.", ephemeral=True)
finally:
dbcursor.close()
@ -142,7 +156,7 @@ async def current(interaction: nextcord.Interaction):
player = get_guild_player(interaction)
current_track = getattr(player, "current", None) if player is not None else None
if current_track is None:
await send_response(interaction, "Nothing is currently playing.", ephemeral=True)
await interaction.response.send_message("Nothing is currently playing.", ephemeral=True)
return
embed = nextcord.Embed(
@ -157,10 +171,13 @@ async def current(interaction: nextcord.Interaction):
name="time",
value=str(timedelta(seconds=round(runtime.time() - runtime.starttime.get(str(interaction.guild.id), runtime.time())))),
)
await send_response(interaction, embed=embed)
await interaction.response.send_message(embed=embed)
except Exception:
log_exception("Current command failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to load the current track.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to load the current track.", ephemeral=True)
else:
await interaction.response.send_message("Failed to load the current track.", ephemeral=True)
@runtime.bot.slash_command(description="Set the music player channel")
@ -171,8 +188,7 @@ async def setupmusic(interaction: nextcord.Interaction, channel: nextcord.VoiceC
command_logger.info("Setupmusic requested: %s play_channel=%s", interaction_log_context(interaction), channel.id)
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=%s", [interaction.guild.id])
if dbcursor.fetchone() is not None:
await send_response(
interaction,
await interaction.response.send_message(
"Bot is already configured on this Server, please try to start it with `/start` or contact me if you need future assistance (<@"
+ str(runtime.adminUserID)
+ ">)",
@ -182,13 +198,15 @@ async def setupmusic(interaction: nextcord.Interaction, channel: nextcord.VoiceC
"INSERT INTO PLAYER (PlayChannel, Server, youtubeChannelID) VALUES (%s, %s, %s)",
(channel.id, interaction.guild.id, runtime.defaultPlaylistURL),
)
await send_response(
interaction,
await interaction.response.send_message(
"Setup complete, " + runtime.bot.user.name + " should now connect to <#" + str(channel.id) + "> and start playing Music soon.",
)
except Exception:
log_exception("Setupmusic failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to configure music playback.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to configure music playback.", ephemeral=True)
else:
await interaction.response.send_message("Failed to configure music playback.", ephemeral=True)
finally:
dbcursor.close()
@ -200,7 +218,7 @@ async def restart(interaction: nextcord.Interaction):
await require_music_enabled(interaction)
await runtime.connect_lavalink()
command_logger.info("Restart requested: %s", interaction_log_context(interaction))
await send_response(interaction, "restarting music bot, please wait one moment")
await interaction.response.send_message("restarting music bot, please wait one moment")
dbcursor.execute("UPDATE PLAYER SET enabled=0 WHERE Server=%s", [interaction.guild.id])
player = get_guild_player(interaction)
if player is not None:
@ -215,7 +233,10 @@ async def restart(interaction: nextcord.Interaction):
await load_next_track(player, result["youtubeChannelID"], interaction.guild.id)
except Exception:
log_exception("Restart command failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to restart the player.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to restart the player.", ephemeral=True)
else:
await interaction.response.send_message("Failed to restart the player.", ephemeral=True)
finally:
dbcursor.close()
@ -233,9 +254,12 @@ async def changeplaylist(interaction: nextcord.Interaction, new_playlist_url: st
if player is not None:
await player.stop()
await load_next_track(player, new_playlist_url, interaction.guild.id)
await send_response(interaction, "changed Playlist to `" + new_playlist_url + "`")
await interaction.response.send_message("changed Playlist to `" + new_playlist_url + "`")
except Exception:
log_exception("Changeplaylist failed: %s", interaction_log_context(interaction))
await send_response(interaction, "Failed to change the playlist.", ephemeral=True)
if interaction.response.is_done():
await interaction.followup.send("Failed to change the playlist.", ephemeral=True)
else:
await interaction.response.send_message("Failed to change the playlist.", ephemeral=True)
finally:
dbcursor.close()

View file

@ -11,12 +11,6 @@ def interaction_author(interaction):
return getattr(interaction, "user", None) or getattr(interaction, "author", None)
async def send_response(interaction, *args, **kwargs):
if interaction.response.is_done():
return await interaction.followup.send(*args, **kwargs)
return await interaction.response.send_message(*args, **kwargs)
async def defer_response(interaction, ephemeral=False):
if not interaction.response.is_done():
await interaction.response.defer(ephemeral=ephemeral)