Discord bot命令不工作(Python)

Discord bot命令不工作(Python),python,discord,Python,Discord,我目前正在使用python编写我的第一个discord机器人。在尝试编写命令时,我发现自己无法做到这一点。此代码: import os import random from discord.ext import commands from dotenv import load_dotenv load_dotenv() TOKEN = 'NzQxMjA2OTQzMDc4ODA5NjEy.Xy0Mwg.Shkr9hHvkn-y4l5ye1yTHYM3rQo' client = discord.Cl

我目前正在使用python编写我的第一个discord机器人。在尝试编写命令时,我发现自己无法做到这一点。此代码:

import os
import random
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()
TOKEN = 'NzQxMjA2OTQzMDc4ODA5NjEy.Xy0Mwg.Shkr9hHvkn-y4l5ye1yTHYM3rQo'
client = discord.Client()
    
@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')

pp = commands.Bot(command_prefix='!')

messages = ["hello", "hi", "how are you?"]
@pp.command(name = "swear")
async def swear(ctx):
    await ctx.send(rand.choice(messages))

client.run(TOKEN)
当我输入时,在discord应用程序中没有输出任何内容!发誓bot处于联机状态,其他代码正常工作,例如:

@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
以下是完整的代码:

导入不一致
导入操作系统
随机输入
从discord.ext导入命令
从dotenv导入加载\u dotenv
加载_dotenv()
令牌=(##我的令牌拼写出来)
client=discord.client()
@客户端事件
_ready()上的异步定义:
打印('im以{0.user}的形式显示)。格式(客户端))
@客户端事件
异步def on_消息(消息):
如果message.author==client.user:
返回
如果message.content.startswith('hello'):
等待message.channel.send('Hi there!')
elif message.content.startswith(“Ethan的妈妈是同性恋吗?”):
等待消息。频道。发送(“是的,100%!”)
elif message.content.startswith(“你在做什么?”):
wait message.channel.send(f“步骤{message.author}”)
message.content.lower()中的elif“生日快乐”:
wait message.channel.send('Happy birth!
Client()
Bot()
是创建Bot的两种方法,同时使用这两种方法是错误的

使用
Client()
Bot()

Bot()
Client()
的扩展版本,因此您只需要
Bot()
并使用

  • @pp.event
    而不是
    @client.event
  • pp.run(令牌)
    而不是
    client.run(令牌)
  • pp.user
    而不是
    client.user

编辑:

你必须在所有函数之前定义
pp
,就像这样

随机导入
从discord.ext导入命令
令牌='TOKEN'
pp=commands.Bot(命令前缀='!')
@pp.事件
_ready()上的异步定义:
打印('im为{}格式(pp.user))
@pp.事件
异步def on_消息(消息):
如果message.author==pp.user:
返回
如果message.content.startswith('hello'):
等待message.channel.send('Hi there!')
elif message.content.startswith(“Ethan的妈妈是同性恋吗?”):
等待消息。频道。发送(“是的,100%!”)
elif message.content.startswith(“你在做什么?”):
wait message.channel.send(f“步骤{message.author}”)
message.content.lower()中的elif“生日快乐”:

wait message.channel.send('生日快乐!通过在此处粘贴您的令牌,您已经为所有人提供了您的机器人的密码。立即刷新它!(Ps令牌应该放在单独的文件中。)你知道如何将它放在一个单独的文件中吗?我不知道你在说什么…很确定dotenv就是为了这个。但是你需要优先重置你的令牌。至于我
Client()
Bot()
是创建bot的两种不同方法-因此您可以同时创建两个bot-您不能同时使用它们,因为您需要
client.run(TOKEN)
pp.run(TOKEN)
同时运行这两种方法。您应该只使用
bot()
@pp.event
而不是
@client.event
当我使用pp.event时,代码的响应是
名称错误:名称“pp”未定义
。你必须在所有
@pp.event之前定义
pp=commands.Bot(command_prefix=!)
-这太明显了,我没有提到它。