如何在discord.py中放置多个导致相同响应的命令?

时间:2020-10-15 01:59:49

标签: python discord.py

@client.event
async def on_message(message):
    if message.content == "fase":
        channel = (mychannel)
        await message.channel.send("Fase 1")

我正在尝试使message.content检测多个单词并发送相同的message.channel.send 我尝试过

if message.content.lower() == "fase", "estagio", "missao", "sala":
if message.content.lower() == ("fase", "estagio", "missao", "sala"):
if message.content.lower() == "fase" or  "estagio" or "missao" or "sala":
if message.content.lower() == ("fase" or  "estagio" or "missao" or "sala"):

我读了这篇文章:How do I allow for multiple possible responses in a discord.py command?

这是完全相同的问题,但是在他的情况下,这是我已经在代码中解决的CaseSensitiveProblem

第二个包含多个单词的代码是:

bot = commands.Bot(command_prefix='!', case_insensitive=True)
@bot.command(aliases=['info', 'stats', 'status'])
    async def about(self):
        # your code here

我做到了,并且遇到了很多错误,甚至使该机器人甚至无法运行(即在Discord.py 1.4.1和python 3.6中使用PyCharm):

#import and token things up here
bot = commands.Bot(command_prefix='i.')
@bot.command(aliases=['fase', 'estagio', 'missao', 'sala']) #'@' or 'def' expected
    async def flame(self): #Unexpected indent // Unresolved reference 'self'
        if message.content(self): #Unresolved reference 'message'
            await message.send("Fase 1") #Unresolved reference 'message' // Statement expected, found Py:DEDENT


我该如何解决?

1 个答案:

答案 0 :(得分:2)

以下是使用Commands扩展名的方法:

from discord.ext import commands

bot = commands.Bot(command_prefix='!', case_insensitive=True)
@bot.command(aliases=['info', 'stats', 'status'])
async def about(ctx):
    #Your code here

每个命令都有以下共同点:

  • 它们是使用bot.command()装饰器创建的。
  • 默认情况下,命令名称是函数名称。
  • 装饰器和函数定义必须具有相同的缩进级别。
  • ctx(第一个参数)将是一个discord.Context对象,其中包含许多信息(消息作者,频道和内容,不和谐服务器,使用的命令,命令的别名)调用,...)

然后,ctx允许您使用一些快捷方式:

  • message.channel.send()成为ctx.send()
  • message.author成为ctx.author
  • message.channel成为ctx.channel

命令参数也更易于使用:

from discord import Member
from discord.ext import commands

bot = commands.Bot(command_prefix='!', case_insensitive=True)

#Command call example: !hello @Mr_Spaar
#Discord.py will transform the mention to a discord.Member object
@bot.command()
async def hello(ctx, member: Member):
    await ctx.send(f'{ctx.author.mention} says hello to {member.mention}')

#Command call example: !announce A new version of my bot is available!
#"content" will contain everything after !announce (as a single string)
@bot.command()
async def announce(ctx, *, content):
    await ctx.send(f'Announce from {ctx.author.mention}: \n{content}')

#Command call example: !sum 1 2 3 4 5 6
#"numbers" will contain everything after !sum (as a list of strings)
@bot.command()
async def sum(ctx, *numbers):
    numbers = [int(x) for x in numbers]
    await ctx.send(f'Result: {sum(numbers)}')