首页 > 解决方案 > 用 Python 制作 Discord Bot 但它不起作用

问题描述

我正在尝试为我和我的朋友们做一个不和谐的机器人来使用它。我正在使用 python 来做这件事。我的问题是机器人应该执行 3 个命令。但是只有 1 个有效,或者当我更改代码的位置时,只有 2 个有效。请帮忙

编码:

import os
import random
import json
import discord
from dotenv import load_dotenv
import requests




client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user.name} has connected to Discord!')

sad_words = ["sad", "owo cry", "unhappy", "a", "miserable"]

starter_encouragements = [
  "Cheer up!",
  "Hang in there.",
  "You are a great person / bot!",
  "i love you",
  "what happend",
  "dont be sad",
  "if you are sad i´m sad"
]

def get_quote():
  response = requests.get("https://zenquotes.io/api/random")
  json_data = json.loads(response.text)
  quote = json_data[0]['q'] + " -" + json_data[0]['a']
  return(quote)

  

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  msg = message.content

  if msg.startswith('$inspire'):
    quote = get_quote()
    await message.channel.send(quote)

   
  if any(word in msg for word in sad_words):
    await message.channel.send(random.choice(starter_encouragements))
    

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    cry_gif = [
        'https://tenor.com/view/crying-anime-cry-gif-13668435',
        'https://c.tenor.com/OhuSWqAsQH4AAAAM/anime-girl-sad-sad.gif',
        
            'https://c.tenor.com/bMSZQ4j3CQkAAAAM/anime-cry.gif ',
            'https://c.tenor.com/zfmbNj3IpAgAAAAC/sorry-crying.gif'
        
    ]

    if message.content == '$hero cry':
        response = random.choice(cry_gif)
        await message.channel.send(response)







client.run(os.getenv("abc"))

当 $inspire 和 "sad words" 起作用时,其他命令 $hero cry 将不起作用。当 $cry 工作时,其他人将无法工作。

标签: pythondiscorddiscord.pybots

解决方案


您可以拥有多个 on_message 但这确实很愚蠢,因此最好将整个内容与 Łukasz Kwieciński 所说的 if/elif/else 语句结合在一起。Free Code Camp 的 discord.py 教程也不是很好。没有好的discord.py教程,所以开始阅读吧。

你也可以去官方 discord.py 服务器寻求帮助

还有一件事,discord.py 正式结束了,没有人维护库了,原来的维护者已经下台了,没有人想维护库


推荐阅读