My code for the prefix command:
import discord
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
message = await ctx.send("Pong!")
latency = self.bot.latency * 1000
await message.edit(content=f'Pong! **{latency:.2f} ms**')
async def setup(bot):
await bot.add_cog(Ping(bot))
For the slash command:
import discord
from discord import app_commands
from discord.ext import commands
class sPing(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command()
async def ping(self, interaction: discord.Interaction):
latency = self.bot.latency * 1000
await interaction.response.send_message(content='Pong!')
msg = await interaction.original_response()
await msg.edit(content=f'Pong! **{latency:.2f} ms**')
async def setup(bot):
await bot.add_cog(sPing(bot))
Is there a way for me to like stop repeating this and can make the prefix command and slash command together in the same chunk of code?
You can use Hybrid Commands, which include both prefix commands and slash commands:
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(name="ping", description="Check the bot's latency")
async def ping(self, ctx):
msg = await ctx.send("Pong!")
latency = self.bot.latency * 1000
await msg.edit(content = f"Pong! **{latency:.2f} ms**")
async def setup(bot):
await bot.add_cog(Ping(bot))
The name = "ping"
and description = "Check the bot's latency"
provides a name and description for the command. So in case some one doesn't know how to use the command, they can read it's usage here.
I hope this helps!