Python开发Discord机器人多命令无法同时生效问题求助
问题根因
你为on_message事件重复注册了两次回调函数,discord.py的事件装饰器默认会覆盖同事件的已注册回调,因此只有位置靠后的那部分逻辑可以正常运行,是功能互斥的核心原因。
另外你当前的悲伤词汇列表中包含单字a,会导致几乎所有带字母a的消息都误触发鼓励逻辑,建议删除该无效配置。
你导入了python-dotenv但没有调用load_dotenv()方法,会导致无法读取.env文件中的令牌配置,也需要同步修正。
discord.py v2.x及以上版本需要手动开启消息内容意图,除了代码中配置intents外,还需要在Discord开发者后台对应应用的Bot页面打开Message Content Intent开关。
修复后完整代码
import os import random import json import discord from dotenv import load_dotenv import requests # 加载.env配置 load_dotenv() client = discord.Client(intents=discord.Intents.all()) @client.event async def on_ready(): print(f'{client.user.name} has connected to Discord!') sad_words = ["sad", "owo cry", "unhappy", "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) 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' ] @client.event async def on_message(message): if message.author == client.user: return msg = message.content # $inspire 命令处理 if msg.startswith('$inspire'): quote = get_quote() await message.channel.send(quote) # $hero cry 命令处理 if message.content == '$hero cry': response = random.choice(cry_gif) await message.channel.send(response) # 悲伤词汇检测处理 if any(word in msg for word in sad_words): await message.channel.send(random.choice(starter_encouragements)) client.run(os.getenv("abc"))
内容的提问来源于stack exchange,提问作者HeroBaskan
相关产品推荐
相关产品推荐

