You need to enable JavaScript to run this app. discord.py创建步骤指令与发送私信 摩斯密码机器人问题排查
优惠活动
大模型
产品
解决方案
定价
更多

discord.py创建步骤指令与发送私信 摩斯密码机器人问题排查

Discord 摩斯密码机器人故障修复

问题根因

  • /decryptkey触发逻辑错误:你将/decryptkey的处理逻辑嵌套在了/encryptkey的分支内部,只有命中加密逻辑时才会临时定义内层事件处理函数,且该函数不会被Discord事件系统注册生效,自然无法响应独立的解密命令。
  • 私信发送失败:一是discord.py v1.0+已废弃client.send_message写法,需改用user.send()方法;二是你定义的last_crypt是分支内局部变量,解密逻辑触发时无法读取该值;另外需确认机器人未被限制私信权限、用户未关闭对应服务器的私信接收开关。

修复后完整代码

import discord

MORSE_CODE_DICT = { 'A':'.-', 'B':'-...',
                    'C':'-.-.', 'D':'-..', 'E':'.',
                    'F':'..-.', 'G':'--.', 'H':'....',
                    'I':'..', 'J':'.---', 'K':'-.-',
                    'L':'.-..', 'M':'--', 'N':'-.',
                    'O':'---', 'P':'.--.', 'Q':'--.-',
                    'R':'.-.', 'S':'...', 'T':'-',
                    'U':'..-', 'V':'...-', 'W':'.--',
                    'X':'-..-', 'Y':'-.--', 'Z':'--..',
                    '1':'.----', '2':'..---', '3':'...--',
                    '4':'....-', '5':'.....', '6':'-....',
                    '7':'--...', '8':'---..', '9':'----.',
                    '0':'-----', ', ':'--..--', '.':'.-.-.-',
                    '?':'..--..', '/':'-..-.', '-':'-....-',
                    '(':'-.--.', ')':'-.--.-'}

def encrypt(message):
    cipher = ''
    for letter in message:
        if letter != ' ':  
            cipher += MORSE_CODE_DICT[letter.upper()] + ' '
        else:
            cipher += ' '
    return cipher
  
def decrypt(message):
    message += ' '
    decipher = ''
    citext = ''
    i = 0
    for letter in message:
        if (letter != ' '):
            i = 0
            citext += letter
        else:
            i += 1
            if i == 2 :
                decipher += ' '
            else:
                try:
                    decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT.values()).index(citext)]
                    citext = ''
                except:
                    # 遇到无法识别的摩斯字符跳过
                    citext = ''
    return decipher


class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.last_crypt = "" # 全局存储上一次加密的明文结果

    async def on_ready(self):
        print('Logged on as', self.user)

    async def on_message(self, message): 
        if message.author == self.user:
            return
        message_content = message.content.strip()
        if not message_content:
            return
        
        # 处理加密命令
        if message_content.startswith('/encryptkey '):
            # 提取命令后的内容
            raw_content = message_content[len('/encryptkey '):].strip()
            if not raw_content:
                await message.channel.send("请输入要加密的内容,格式为:/encryptkey 内容", delete_after=5)
                await message.delete()
                return
            # 加密发送
            morse_result = encrypt(raw_content)
            await message.delete()
            await message.channel.send(morse_result)
            # 存储明文到实例属性
            self.last_crypt = decrypt(morse_result)
            return
        
        # 处理解密命令
        if message_content == '/decryptkey':
            if not self.last_crypt:
                await message.channel.send("暂无上一次加密的内容,请先使用/encryptkey加密内容", delete_after=5)
                return
            # 发送私信
            try:
                await message.author.send(f"上一次加密的明文内容为:{self.last_crypt}")
                await message.channel.send("解密结果已私信发送给你", delete_after=3)
            except discord.Forbidden:
                await message.channel.send("无法向你发送私信,请检查你是否开启了本服务器的私信权限", delete_after=5)
            return

intents = discord.Intents.default()
intents.message_content = True # 必须开启消息内容权限,Discord开发者后台也要对应开启
client = MyClient(intents=intents)
client.run('#token_here')

额外注意事项

  • 需要在Discord开发者后台的Bot设置页开启Message Content Intent权限,否则机器人无法读取消息内容
  • 代码中新增了异常捕获,用户关闭私信权限时会给出公屏提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 00:15:01