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

无需Discord事件触发,实现AI驱动的Discord消息主动发送

实现AI脚本主动触发Discord机器人发送消息

针对你的需求,核心是让AI脚本能主动触发Discord机器人发送消息,而非依赖Discord平台的事件(如消息、成员加入等)。可以通过异步消息队列+后台任务的方式实现,以下是具体方案:

1. 修改Discord机器人代码

通过asyncio.Queue创建全局消息队列,机器人启动后运行后台任务持续监听队列,AI脚本只需将待发送的消息内容和目标频道ID放入队列即可触发发送:

import discord
import asyncio
import secretss

# 全局消息队列,用于AI脚本传递待发送的消息
message_queue = asyncio.Queue()

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

async def message_sender_task():
    """后台任务:持续监听消息队列,发送消息到指定频道"""
    await client.wait_until_ready()
    while not client.is_closed():
        # 从队列取出消息元组:(频道ID, 消息内容)
        channel_id, content = await message_queue.get()
        try:
            channel = client.get_channel(channel_id)
            if channel:
                await channel.send(content)
            else:
                print(f"未找到ID为 {channel_id} 的频道")
        except Exception as e:
            print(f"发送消息失败:{str(e)}")
        finally:
            # 标记队列任务完成
            message_queue.task_done()

@client.event
async def on_ready():
    print(f'{client.user} 已连接到Discord!')
    # 启动后台消息发送任务
    client.loop.create_task(message_sender_task())

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    await message.channel.send('hello')

# 供AI脚本调用的接口函数
def trigger_discord_message(channel_id: int, content: str):
    if client.loop.is_running():
        # 跨线程安全地向异步事件循环提交任务
        asyncio.run_coroutine_threadsafe(
            message_queue.put((channel_id, content)),
            client.loop
        )
    else:
        print("Discord机器人未启动,无法发送消息")

client.run(secretss.discordkey)

2. AI脚本中调用触发

在你的AI脚本中,只需导入机器人脚本中的trigger_discord_message函数,当AI生成响应后直接调用即可:

# AI脚本示例代码
from your_discord_bot_file import trigger_discord_message

# 假设AI生成了响应内容
ai_response = "这是AI生成的回复内容"
# 指定目标Discord频道ID(需替换为实际频道ID)
target_channel_id = 123456789012345678

# 触发机器人发送消息
trigger_discord_message(target_channel_id, ai_response)

3. 多进程场景适配(可选)

如果AI脚本和Discord机器人脚本是独立进程运行,上述同进程队列无法生效,可改用进程间通信方案:

  • 使用Redis消息队列:AI脚本向Redis队列写入消息,机器人脚本监听Redis队列并发送消息
  • 使用本地Socket通信:AI脚本通过Socket发送消息指令,机器人脚本接收后执行发送操作

注意事项

  • 确保Discord机器人拥有目标频道的「发送消息」权限
  • 频道ID需为整数类型,可通过Discord开启开发者模式后复制获取
  • asyncio.run_coroutine_threadsafe用于确保非异步线程向事件循环提交任务的线程安全性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 12:30:13