登录
首页 >  文章 >  python教程

可开关Discord回声机器人搭建教程

时间:2025-07-22 11:15:27 160浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《打造可开关的Discord回声机器人教程》,很明显是关于文章的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

创建一个可开关的回声Discord机器人(discord.py)

本文将指导你如何使用discord.py库创建一个简单的回声机器人。该机器人会在接收到特定指令后开始重复用户的消息,并在接收到停止指令或超时后停止。我们将使用全局变量控制机器人的回声状态,并利用bot.wait_for()函数监听用户的消息。本文提供详细的代码示例和解释,帮助你理解和实现这个功能。

实现步骤

以下是创建一个可开关的回声机器人的详细步骤:

  1. 定义全局变量控制回声状态

    首先,我们需要一个全局变量来控制机器人的回声状态。这个变量是一个布尔值,当设置为True时,机器人将开始回声;当设置为False时,机器人将停止回声。

    boolean = False
  2. 创建on_message事件监听器

    on_message事件监听器用于处理所有接收到的消息。在这个监听器中,我们需要检查全局变量的状态,并根据状态决定是否回声消息。

    @bot.event
    async def on_message(message: discord.Message):
        global boolean
        if boolean:
            if message.author.bot:
                return
            if message.content == "k!echo":
                boolean = False
                return
            if isinstance(message.channel, discord.TextChannel):
                await message.channel.send(message.content)
        else:
            pass

    代码解释:

    • global boolean: 声明使用全局变量boolean。
    • if boolean:: 检查全局变量boolean是否为True,如果是,则执行回声逻辑。
    • if message.author.bot:: 忽略来自机器人的消息,避免无限循环。
    • if message.content == "k!echo":: 如果用户输入 "k!echo",则将boolean设置为False,停止回声。
    • if isinstance(message.channel, discord.TextChannel):: 确保消息来自文本频道,避免在私聊等其他频道中回声。
    • await message.channel.send(message.content): 将消息内容发送到消息所在的频道。
  3. 创建/echo命令

    我们需要创建一个命令来启动和停止回声机器人。这里我们使用bot.tree.command创建一个名为/echo的命令。

    @bot.tree.command(name="echo")
    async def echo(interaction: discord.Interaction):
        global boolean
        boolean = True
        channel = interaction.channel
        await interaction.response.send_message('Bot will start echoing. Type "k!echo" to stop.')
        async def check_stop(msg):
            return msg.content == "k!echo" and msg.author.id == interaction.user.id
        try:
            while True:
                response = await bot.wait_for("message", check=check_stop, timeout=60.0)
                await channel.send(response.content)
                break
        except asyncio.TimeoutError:
            await interaction.response.send_message('Echoing stopped due to inactivity.')

    代码解释:

    • global boolean: 声明使用全局变量boolean。
    • boolean = True: 将全局变量boolean设置为True,启动回声。
    • channel = interaction.channel: 获取交互发生的频道。
    • await interaction.response.send_message('Bot will start echoing. Type "k!echo" to stop.'): 发送一条消息,告知用户机器人已启动回声。
    • check_stop(msg): 检查消息是否为停止指令("k!echo")并且是来自发起交互的用户。
    • bot.wait_for("message", check=check_stop, timeout=60.0): 等待用户发送停止指令,超时时间为60秒。
    • await channel.send(response.content): 将用户发送的停止指令内容发送到频道(实际上这里可以忽略,因为我们的目的是停止回声)。
    • asyncio.TimeoutError: 如果在指定时间内没有收到停止指令,则捕获TimeoutError异常,并发送一条消息告知用户回声已停止。

完整代码示例

以下是完整的代码示例,包含所有必要的代码:

import discord
import asyncio

intents = discord.Intents.default()
intents.message_content = True

bot = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(bot)

boolean = False

@bot.event
async def on_message(message: discord.Message):
    global boolean
    if boolean:
        if message.author.bot:
            return
        if message.content == "k!echo":
            boolean = False
            return
        if isinstance(message.channel, discord.TextChannel):
            await message.channel.send(message.content)
    else:
        pass

@tree.command(name="echo")
async def echo(interaction: discord.Interaction):
    global boolean
    boolean = True
    channel = interaction.channel
    await interaction.response.send_message('Bot will start echoing. Type "k!echo" to stop.')
    async def check_stop(msg):
        return msg.content == "k!echo" and msg.author.id == interaction.user.id
    try:
        while True:
            response = await bot.wait_for("message", check=check_stop, timeout=60.0)
            #await channel.send(response.content) # optional, not needed
            break
    except asyncio.TimeoutError:
        await interaction.followup.send('Echoing stopped due to inactivity.') # use interaction.followup.send for messages after the initial response

@bot.event
async def on_ready():
    await tree.sync()
    print(f'Logged in as {bot.user}')

bot.run('YOUR_BOT_TOKEN')

使用说明:

  1. 将YOUR_BOT_TOKEN替换为你的机器人令牌。
  2. 运行代码。
  3. 在Discord中使用/echo命令启动回声机器人。
  4. 输入任何消息,机器人将重复你的消息。
  5. 输入k!echo停止回声机器人。

注意事项

  • 全局变量的使用: 全局变量可能会导致代码难以维护和调试。在更复杂的应用中,可以考虑使用类或数据库来管理机器人的状态。
  • 错误处理: 代码中包含了asyncio.TimeoutError的错误处理,但还可以添加更多的错误处理,以提高代码的健壮性。
  • 权限: 确保机器人具有在频道中发送消息的权限。
  • 命令同步: 确保在使用命令之前,命令已经同步到 Discord 服务器。 这可以通过在 on_ready 事件中调用 tree.sync() 来完成。
  • interaction.response vs interaction.followup: 当命令执行时间超过 3 秒时,需要使用 interaction.followup.send 来发送后续消息,而不是 interaction.response.send_message,因为初始响应只能在 3 秒内发送。

总结

通过本文,你学习了如何使用discord.py创建一个简单的回声机器人。这个机器人可以根据用户的指令启动和停止回声,并且具有超时处理功能。你可以根据自己的需求扩展这个机器人,例如添加更多的命令、自定义回声消息等。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>