首页 > 解决方案 > 添加新代码块后,discord.py bot 停止响应

问题描述

我是 python 和 discord.py 的新手,这是一个更新了细节的转发,没有难以理解的代码块。我还没有在网上找到这个问题的答案,所以这可能是我的一个小错误。

问题 我正在尝试为我的服务器编写一个 discord.py 机器人,它可以执行一些基本命令。我想在 shell 中添加一些功能,可以让我通过 python shell 控制机器人。在此之前,我有一些可以按预期工作的基本命令(我执行 c!help 并且它以带有帮助的嵌入消息响应)在我通过控制台添加控制代码后,discord 的命令停止按预期响应。

期望的行为:我在不和谐中键入 c!boop {user},机器人向所述用户发送 dm,并在日志通道中发送日志消息。我在 python shell 中执行 c!console,我的交互式菜单出现

会发生什么:我输入 c!boop {user} 不和谐,我什么也没得到。我在 python shell 中执行 c!console,我的交互式菜单出现了。

正如我所说,在我为 Shell 添加新代码之前,它已经工作了。

的代码 这里的代码已经为 MRE 缩短了很多,但是如果你认为完整的代码是必要的,请问。抱歉,如果它仍然很长,我已经删除了 3/4,只保留与我的问题相关的部分。

import discord
import time

client = discord.Client()
prefix = 'c!'

@client.event
async def on_message(message):
    if message.author == client.user:
        return
#This bit is the command for within discord
    if message.content.startswith(prefix + "boop"):
        
        #Getting the Victim's user id
        victim = str(message.content)
        victim = victim.replace(prefix + 'boop ', '')
        victim = victim.replace('<@', '')
        victim = victim.replace('!', '')
        victim = victim.replace('>','')
        
        #Booping the user
        user = client.get_user(int(victim))
        await message.channel.send("Booped " + user.name)
        await user.send('**Boop!**')
        t = time.localtime()
        current_time = time.strftime("%H:%M:%S", t)
        channel = client.get_channel(int(759798825161326593))
        LogMsg = str('`' + current_time + '` ' + message.author.name + ' used command in ' + str(message.channel) + ' `' + message.content + '`')
        await channel.send(LogMsg)


#After I added this section, the above command stopped working
@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print('USER ID: ' + str(client.user.id))
    print('')
    print('To Open the Console, type ' + prefix + 'console in the shell')
    print('------')

    console = str(prefix + 'console')
    while 1 == 1:
        ConsoleInput = input('')
        if ConsoleInput == console:
            while 1 == 1:
                print('------')
                print('Please Select a Module')
                print('1 - Announce')
                print('99 - Exit Console')
                print('------')
                ConsoleInput = int(input(''))

                if ConsoleInput == 1:
                    print('------')
                    print('Module 1 Selected - Announce')
                    print("What's the id of the channel you want to announce in?")
                    Channel_id = int(input())
                    print("Embed? (1 for yes, 2 for no)")
                    YeNo = int(input())
                    
                    if YeNo == 1:
                        print("What is the Title for the Embed message?")
                        EmbedTitle = str(input())
                        print("What is the Description for the Embed message?")
                        announcement = str(input())
                        print('Announcing')
                        channel = client.get_channel(Channel_id)
                        embed=discord.Embed(title=EmbedTitle, description=announcement, color=0xff40ff)
                        await channel.send(embed=embed)
                        print("Announced")

                        t = time.localtime()
                        current_time = time.strftime("%H:%M:%S", t)
                        channel = client.get_channel(int(759798825161326593))
                        await channel.send('`' + current_time + '` ' + 'Console User used command in Console ' '`' + str(Channel_id) + ' ' + EmbedTitle + ' ' + announcement + ' ' + str(YeNo) + '`')
                        
                    elif YeNo == 2:
                        print("What is the announcement?")
                        announcement = str(input())
                        print("Announcing")
                        channel = client.get_channel(Channel_id)
                        await channel.send(announcement)
                        print("Announced")
                        
                        t = time.localtime()
                        current_time = time.strftime("%H:%M:%S", t)
                        channel = client.get_channel(int(759798825161326593))
                        await channel.send('`' + current_time + '` ' + 'Console User used command in Console ' '`' + str(Channel_id) + ' ' + announcement + ' ' + str(YeNo) + '`')

                elif ConsoleInput == 99:
                    print('------')
                    print('Exiting Console')
                    print('You can restart the console by typing ' + prefix + 'console in the shell')
                    print('------')
                    break

client.run(TOKEN GOES HERE)

提前致谢

标签: pythondiscorddiscord.py

解决方案


阻塞代码

看来on_ready事件中的同步代码是挂起机器人的原因;等待来自控制台的输入会停止运行任何其他代码,包括对命令做出反应。

解决此问题的唯一方法是以不涉及使用控制台的不同方式设计您的公告命令,例如让它成为您的机器人的命令。

旁注关于discord.Client()

由于您使用的是较低级别的 API ( discord.Client),您可能会发现为您的机器人开发新命令更加困难。我建议使用discord.py 随附的机器人命令框架( )。discord.ext.commands音调在链接中,所以这里是一个使用框架和你的 boop 命令的例子:

import time
import discord
from discord.ext import commands

prefix = 'c!'
TOKEN = ''

client = commands.Bot(command_prefix=prefix)

@client.event
async def on_ready():
    print('Logged in as', client.user.name)

@client.command(name='boop')
async def client_boop(ctx, user: discord.User):
    """Boops a user.
Accepted inputs are: ID, mention, name#discrim, or name
Example: c!boop thegamecracks"""
    await user.send('**Boop!**')
    await ctx.channel.send("Booped " + user.name)

    current_time = time.strftime("%H:%M:%S", time.localtime())
    log_channel = client.get_channel(759798825161326593)
    LogMsg = '`{}` {} used command in {} `{}`'.format(
        current_time,
        ctx.author.name,
        ctx.channel.name,
        ctx.message.content
    )
    await log_channel.send(LogMsg)

client.run(TOKEN)

推荐阅读