英文:
How do I create slash commands in discord.py?
问题
以下是您提供的代码中的翻译部分:
import bot
if __name__ == '__main__':
bot.run_discord_bot()
import random
swears = ["crap"] # i will add more later
def get_response(message: str) -> str:
p_message = message.lower()
for x in range(len(swears)): # loop for swears
if p_message.__contains__(swears[x]) or p_message.__contains__("swear"):
return "`请停止咒骂`"
if p_message.__contains__("i will eat you"):
return "不"
return ""
import discord
import responses
async def send_message(message, user_message, is_private,):
try:
response = responses.get_response(user_message)
if response == "`请停止咒骂`":
await message.author.send(f"{message.author.mention} {response}") # 发送到私聊
await message.channel.send(f"{message.author.mention} {response}") # 发送到频道
else:
await message.author.send(response) if is_private else await message.channel.send(response)
print(f"已发送 {response} 给 {message.author}")
except Exception as E:
print(E)
def run_discord_bot():
TOKEN = "XXXX"
bot = interactions.Client(TOKEN)
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f"{client.user} 已启动!")
@client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
if responses.get_response(user_message) == "": # 这使得机器人不会回应不是咒骂的消息
return
elif user_message[0] == "?":
user_message = user_message[1]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
client.run(TOKEN)
import interactions
# 在 run_discord_bot 中的某个地方:
@bot.command(
name="rules",
description="显示服务器规则",
)
async def rules(ctx: interactions.CommandContext):
await ctx.send("{rules}")
如果您有其他问题或需要进一步的帮助,请随时提出。
英文:
I have a discord bot and it can respond to messages. But how do I make it have slash commands? I want to make a simple slash command that says something. How do I do that? Here is my code:
main.py:
import bot
if __name__ == '__main__':
bot.run_discord_bot()
responses.py:
import random
swears = ["crap"] # i will add more later
def get_response(message: str) -> str:
p_message = message.lower()
for x in range(len(swears)): # loop for swears
if p_message.__contains__(swears[x]) or p_message.__contains__("{swear}"):
return "`PLEASE STOP SWEARING`"
if p_message.__contains__("i will eat you"):
return "no"
return ""
bot.py:
import discord
import responses
async def send_message(message, user_message, is_private,):
try:
response = responses.get_response(user_message)
if response == "`PLEASE STOP SWEARING`":
await message.author.send(f"{message.author.mention} {response}") # sends to DM
await message.channel.send(f"{message.author.mention} {response}") # sends to channel
else:
await message.author.send(response) if is_private else await message.channel.send(response)
print(f"sent {response} to {message.author}")
except Exception as E:
print(E)
def run_discord_bot():
TOKEN = "XXXX"
bot = interactions.Client(TOKEN)
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f"{client.user} is up and running!")
@client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
if responses.get_response(user_message) == "": # this makes the bot not respond to messages that are not swears
return
elif user_message[0] == "?":
user_message = user_message[1]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
client.run(TOKEN)
I tried using many ways like chatGPT, but the information was outdated. Ans I also tried this way:
import interactions
# somewhere in run_discord_bot:
@bot.command(
name="rules",
description="shows the server rules",
)
async def rules(ctx: interactions.CommandContext):
await ctx.send("{rules}")
答案1
得分: 0
从discord包中导入`~Interaction`。
*在[这里](https://stackoverflow.com/questions/71165431/how-do-i-make-a-working-slash-command-in-discord-py)中也发现了相同的问题*
```py
from discord import Interaction
# 如果斜杠命令不在一个cog中
@client.tree.command(description="显示服务器规则") # 移除了name参数,因为它与async函数相同会引发错误
async def rules(interaction: discord.Interaction) -> None:
rules = (
"1. 不说脏话",
"2. 尊重他人",
"3. 不能在语音频道大声说话",
)
await interaction.response.send_message(f"{rules}")
在cogs中
from discord import app_commands
from discord.ext import commands
class MyCog(commands.Cog);
@app_commands.command(description="显示服务器规则")
async def rules(self, interaction: discord.Interaction) -> None:
... # 这里可以使用与cog外部的斜杠命令相同的代码
您必须知道~Interaction.response
只能发送一次,然后必须使用~Interaction.followup
。
另外,您必须同步您的命令,但我不建议您在on_ready
事件中同步它们,可以像这样做。
from discord.ext.commands import is_owner, Context
@client.command()
@is_owner()
async def sync(ctx: Context) -> None:
synced = await client.tree.sync()
await ctx.reply("{}个命令已同步".format(len(synced)))
<details>
<summary>英文:</summary>
Import `~Interaction` from discord package.
*Same problem is found in [here](https://stackoverflow.com/questions/71165431/how-do-i-make-a-working-slash-command-in-discord-py)*
```py
from discord import Interaction
# if slash command isn't in a cog
@client.tree.command(description="Shows the server rules") # removed the name param because it will raise an error as it is the same that the async function
async def rules(interaction: discord.Interaction) -> None:
rules = (
"1. Don't say bad words",
"2. Respect other people",
"3. You mustn't speak loud in voice channels",
)
await interaction.response.send_message(f"{rules}")
In cogs
from discord import app_commands
from discord.ext import commands
class MyCog(commands.Cog);
@app_commands.command(description="Shows the server rules")
async def rules(self, interaction: discord.Interaction) -> None:
... # Here can be the same code that the slash command outside cog
You must know that ~Interaction.response
can only be sent once, then you must use ~Interaction.followup
.
Also, you must sync your commands, but I don't recommend you to sync them in the on_ready
event, do something like this.
from discord.ext.commands import is_owner, Context
@client.command()
@is_owner()
async def sync(ctx: Context) -> None:
synced = await client.tree.sync()
await ctx.reply("{} commands synced".format(len(synced)))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论