discord.py执行.balance/.work命令无响应且无控制台日志问题
Discord.py机器人执行.balance/.work命令无响应且无错误日志
问题描述
使用discord.py开发的机器人,执行.balance或.work命令时无任何消息回复,控制台也没有输出错误日志。已尝试移除open_account和get_bank_data的async/await,以及查阅相关问题的解决方案,均无效。
相关代码
main.py
import discord from discord.ext import commands from webserver import keep_alive import json import os os.chdir("/home/runner/exidexi") intents = discord.Intents.all() client = commands.Bot(command_prefix=".", intents=intents, case_insensitive=True) client.remove_command('help') @client.event async def on_ready(): await client.change_presence(activity=discord.Game('.pomoc')) print("Bot is currently online!") @client.event async def setup_hook(): for filename in os.listdir('./cogs'): if filename.endswith('.py'): await client.load_extension(f'cogs.{filename[:-3]}') print(f"Loaded Cog: {filename[:-3]}") else: print("Unable to load pycache folder.") keep_alive() token = os.environ.get("discord_bot_secret") client.run(token)
economy.py
import discord from discord.ext import commands import datetime import random import json import os class balance(commands.Cog): def __init__(self, client): self.client = client @commands.Cog.listener() async def on_ready(self): print("economy.py is ready!") @commands.command() async def balance(self, ctx): await open_account(ctx.author) users = await get_bank_data() user = ctx.author wallet_amt = users[str(user.id)]["wallet"] bank_amt = users[str(user.id)]["bank"] embed = discord.Embed(title = f"{ctx.author.name}'s balance",color = discord.Color.red()) embed.add_field(name = "Wallet balance",value = wallet_amt) embed.add_field(name = "Bank balance",value = bank_amt) await ctx.reply(embed = embed) @commands.command() async def work(self, ctx): await open_account(ctx.author) users = await get_bank_data() user = ctx.author earnings = random.randrange(101) await ctx.reply(f"Someone gave you {earnings} coins!!") users[str(user.id)]["wallet"] += earnings with open("mainbank.json","w") as f: json.dump(users,f) async def open_account(user): users = await get_bank_data() user = ctx.author if str(user.id) in users: return False else: users[str(user.id)] = {} users[str(user.id)]["wallet"] = 0 users[str(user.id)]["bank"] = 0 with open("mainbank.json","w") as f: json.dump(users,f) return True async def get_bank_data(): with open("mainbank.json","r") as f: users = json.load(f) return users async def setup(client): await client.add_cog(economy(client))
mainbank.json
{ }
问题根源及解决方案
1. Cog注册错误
economy.py的setup函数中,错误实例化了不存在的economy类,实际Cog类名为balance。这会导致Cog无法加载,命令根本未注册,自然不会响应。
修正:
async def setup(client): await client.add_cog(balance(client))
2. Cog内部方法缺少self参数
open_account和get_bank_data作为Cog类内的方法,未添加self参数,无法通过Cog实例调用;同时open_account错误使用ctx.author而非传入的user参数。
修正:
- 为两个方法添加
self参数 - 调用时使用
self.前缀 - 移除
open_account内错误的user = ctx.author赋值,直接使用传入的user参数
3. 可选:添加命令未找到监听
为方便排查此类问题,可添加事件捕获未注册命令:
@client.event async def on_command_error(ctx, error): if isinstance(error, commands.CommandNotFound): print(f"Unknown command: {ctx.message.content}")
修正后的完整economy.py代码
import discord from discord.ext import commands import datetime import random import json import os class balance(commands.Cog): def __init__(self, client): self.client = client @commands.Cog.listener() async def on_ready(self): print("economy.py is ready!") @commands.command() async def balance(self, ctx): await self.open_account(ctx.author) users = await self.get_bank_data() user = ctx.author wallet_amt = users[str(user.id)]["wallet"] bank_amt = users[str(user.id)]["bank"] embed = discord.Embed(title=f"{ctx.author.name}'s balance", color=discord.Color.red()) embed.add_field(name="Wallet balance", value=wallet_amt) embed.add_field(name="Bank balance", value=bank_amt) await ctx.reply(embed=embed) @commands.command() async def work(self, ctx): await self.open_account(ctx.author) users = await self.get_bank_data() user = ctx.author earnings = random.randrange(101) await ctx.reply(f"Someone gave you {earnings} coins!!") users[str(user.id)]["wallet"] += earnings with open("mainbank.json", "w") as f: json.dump(users, f) async def open_account(self, user): users = await self.get_bank_data() if str(user.id) in users: return False else: users[str(user.id)] = { "wallet": 0, "bank": 0 } with open("mainbank.json", "w") as f: json.dump(users, f) return True async def get_bank_data(self): try: with open("mainbank.json", "r") as f: users = json.load(f) except FileNotFoundError: users = {} return users async def setup(client): await client.add_cog(balance(client))
验证步骤
- 替换修正后的
economy.py代码 - 重启机器人,确认控制台输出
Loaded Cog: economy和economy.py is ready! - 执行
.balance或.work命令,检查是否正常响应
内容的提问来源于stack exchange,提问作者user20907688
相关产品推荐
相关产品推荐

