You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python编写Discord Ghostpinger机器人!ghostping指令无响应求助

Discord Ghostpinger 机器人问题排查及修复方案

存在的问题

你的代码共有5处可导致功能失效的问题:

  • 命令匹配逻辑错误:message.content.lower是方法对象,未加()调用执行,无法得到转小写后的消息内容,导致!ghostping命令永远匹配失败
  • 变量未定义:on_message事件的入参只有message,不存在ctx变量,调用ctx.message.delete()会直接抛出异常中断执行
  • 异步逻辑错误:异步函数中使用同步阻塞的time.sleep(1),会卡住整个机器人的事件循环,无法正常处理后续请求
  • 参数提取逻辑错误:split('!ghostping')[0]拿到的是命令前的空内容,你要@的目标用户在命令后面,应该取拆分后的索引1的内容
  • TOKEN语法错误:单引号包裹的字符串内部直接使用了单引号don't,会触发Python语法报错

修复后的完整代码

import time
import discord
import asyncio

# 注意TOKEN字符串要用双引号包裹,或者转义内部的单引号
TOKEN = "don't token log my bot pls the token is here btw"

client = discord.Client(intents=discord.Intents.all())

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

@client.event
async def on_message(message):
    full_message = str(message.content)
    channel = str(message.channel.name)
    username = str(message.author).split('#')[0]
    print(f'{username}: {str(message.content)} ({channel})')

    if message.author == client.user:
        return

    if message.channel.name == 'teszt':
        # 修复:lower方法加括号调用,正确转小写
        if message.content.lower().startswith('!ghostping'):
            # 修复:提取命令后面的用户参数,去掉前后空格
            user_message = message.content.split('!ghostping')[1].strip()
            if not user_message:
                await message.channel.send("请指定要ping的用户")
                return
            await message.channel.send(f'@{user_message}')
            # 修复:用异步休眠替代同步sleep
            await asyncio.sleep(1)
            # 修复:直接用入参message删除指令消息
            await message.delete()
            return

client.run(TOKEN)

补充注意事项

如果修复后还是无法运行,需要确认你的机器人已经被授予了对应频道的发送消息、删除消息的权限,同时已经在Discord开发者后台的Bot设置页开启了Message Content Intent开关,否则无法正常读取消息内容。

内容的提问来源于stack exchange,提问作者Petee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:36:02