如何仅通过参数与Bot Token实现无轮询的Discord消息发送?
直接用Discord REST API实现无轮询消息发送
核心思路
Discord提供了完整的REST API,无需依赖SDK的网关客户端(即不需要轮询),直接通过HTTP请求就能发送消息。你只需要传递可JSON序列化的参数(Bot Token、频道ID、消息内容),在消费端调用API即可完成发送。
实现步骤
- 准备可序列化参数:
bot_token(机器人令牌)、channel_id(目标频道数字ID)、content(消息内容) - 调用Discord消息创建API端点:
POST https://discord.com/api/v10/channels/{channel_id}/messages - 请求头携带Bot认证信息:
Authorization: Bot {bot_token} - 请求体以JSON格式传递消息内容
代码示例
同步版本(使用requests)
import requests def send_discord_message(bot_token, channel_id, content): api_url = f"https://discord.com/api/v10/channels/{channel_id}/messages" headers = { "Authorization": f"Bot {bot_token}", "Content-Type": "application/json" } payload = {"content": content} response = requests.post(api_url, headers=headers, json=payload) response.raise_for_status() # 抛出HTTP错误便于排查问题 return response.json() # 使用示例 send_discord_message("your_bot_token_here", 1153xxxxxxxxxxx49, "message here!")
异步版本(使用aiohttp)
适合异步架构的项目:
import aiohttp import asyncio async def send_discord_message(bot_token, channel_id, content): api_url = f"https://discord.com/api/v10/channels/{channel_id}/messages" headers = { "Authorization": f"Bot {bot_token}", "Content-Type": "application/json" } payload = {"content": content} async with aiohttp.ClientSession() as session: async with session.post(api_url, headers=headers, json=payload) as response: response.raise_for_status() return await response.json() # 使用示例 async def main(): await send_discord_message("your_bot_token_here", 1153xxxxxxxxxxx49, "message here!") asyncio.run(main())
关键注意事项
- 权限验证:确保Bot在目标频道拥有
SendMessages权限,否则会返回403错误 - API版本:示例使用v10版本,Discord会定期更新API版本,需注意官方文档的版本变更
- 请求限流:Discord API有频率限制,遇到429错误时需根据响应头
Retry-After字段进行重试 - 参数合法性:频道ID必须是有效数字ID,消息内容不能违反Discord内容政策
内容的提问来源于stack exchange,提问作者RingGoose
相关产品推荐
相关产品推荐

