创建一个基于 Discord.py 的回声机器人

DDD
发布: 2025-07-18 16:08:14
原创
347人浏览过

创建一个基于 discord.py 的回声机器人

本文将指导你如何使用 Discord.py 库创建一个简单的回声机器人。该机器人可以通过特定命令启动,并开始重复用户发送的消息,直到用户发出停止命令或超时。我们将通过设置全局变量、使用 on_message 事件和 bot.wait_for 函数来实现此功能,并提供代码示例和注意事项。

实现步骤

  1. 设置全局变量:

    首先,我们需要一个全局变量来控制机器人的回声状态。我们将使用一个布尔变量 boolean,其初始值为 False,表示回声功能关闭。当用户启动回声功能时,将其设置为 True。

    boolean = False
    登录后复制
  2. 监听消息事件 (on_message):

    使用 on_message 事件来监听频道中的消息。当 boolean 为 True 时,机器人将重复用户发送的消息。为了避免重复机器人自身的消息,我们需要检查消息的作者是否为机器人。

    @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
    登录后复制

    代码解释:

    Giiso写作机器人
    Giiso写作机器人

    Giiso写作机器人,让写作更简单

    Giiso写作机器人 56
    查看详情 Giiso写作机器人
    • @bot.event 装饰器用于注册一个事件监听器。
    • async def on_message(message: discord.Message) 函数会在收到任何消息时被调用。
    • message.author.bot 检查消息是否由机器人发送。
    • message.content == "k!echo" 检查消息内容是否为停止命令。
    • isinstance(message.channel, discord.TextChannel) 确保消息来自文本频道,避免在私聊中触发。
    • await message.channel.send(message.content) 将消息内容发送到相同的频道。
  3. 创建回声命令 (echo command):

    使用 bot.tree.command 创建一个命令,用于启动和停止回声功能。

    @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.')
    登录后复制

    代码解释:

    • @bot.tree.command(name="echo") 创建一个名为 "echo" 的斜杠命令。
    • boolean = True 启动回声功能。
    • await interaction.response.send_message('Bot will start echoing. Type "k!echo" to stop.') 向用户发送确认消息。
    • bot.wait_for("message", check=check_stop, timeout=60.0) 等待用户发送停止命令。
    • check_stop 函数检查消息内容是否为停止命令,并且消息作者是否为发起命令的用户。
    • asyncio.TimeoutError 处理超时情况,如果用户在 60 秒内没有发送停止命令,则停止回声功能。

完整代码示例

import discord
from discord.ext import commands
import asyncio

# 替换为你的机器人 token
TOKEN = 'YOUR_BOT_TOKEN'

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

bot = commands.Bot(command_prefix='!', intents=intents)

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
    await bot.process_commands(message) # 确保其他命令也能正常工作

@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.')

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)

bot.run(TOKEN)
登录后复制

注意事项:

  • 确保已安装 discord.py 库。可以使用 pip install discord.py 命令安装。
  • 将 YOUR_BOT_TOKEN 替换为你的机器人 token。
  • 此代码使用斜杠命令,需要在机器人启动后同步命令。
  • bot.process_commands(message) 在 on_message 事件中是必要的,以确保其他命令也能正常工作。
  • 可以根据需要调整超时时间。

总结

通过使用全局变量、on_message 事件和 bot.wait_for 函数,我们成功创建了一个基于 Discord.py 的回声机器人。该机器人可以通过特定命令启动,并重复用户发送的消息,直到用户发出停止命令或超时。 这个教程提供了一个基础框架,你可以根据自己的需求进行扩展和修改,例如添加更多的命令、自定义回声行为等。

以上就是创建一个基于 Discord.py 的回声机器人的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号