如何开发Discord机器人:接收WebSocket消息并转发至频道
实现方案
1. 安装必要依赖
首先安装项目所需的Python库:
pip install discord.py websockets
2. 编写核心代码
下面是完整的实现代码,包含Discord机器人初始化、WebSocket连接、消息处理和发送逻辑:
import discord import asyncio import websockets import json from discord.ext import commands # 配置信息 DISCORD_TOKEN = "你的Discord机器人令牌" TARGET_CHANNEL_ID = 123456789012345678 # 替换为目标频道ID WEBSOCKET_URL = "ws://example.com" # 替换为你的WebSocket服务器地址 # 启用必要的Intents intents = discord.Intents.default() intents.message_content = True # 需启用此权限才能发送频道消息 # 初始化机器人 bot = commands.Bot(command_prefix="!", intents=intents) target_channel = None @bot.event async def on_ready(): global target_channel target_channel = bot.get_channel(TARGET_CHANNEL_ID) if not target_channel: print(f"无法找到ID为{TARGET_CHANNEL_ID}的频道") await bot.close() return print(f"已登录为 {bot.user},目标频道: {target_channel.name}") # 启动WebSocket连接任务 asyncio.create_task(websocket_client()) async def websocket_client(): while True: try: async with websockets.connect(WEBSOCKET_URL) as websocket: print("已连接到WebSocket服务器") async for message in websocket: # 处理接收到的消息 await process_websocket_message(message) except Exception as e: print(f"WebSocket连接出错: {e},5秒后尝试重连") await asyncio.sleep(5) async def process_websocket_message(raw_message): if not target_channel: return try: # 解析JSON消息 parsed_data = json.loads(raw_message) # 格式化输出内容,可根据需求自定义 formatted_message = f"收到WebSocket消息:\n```json\n{json.dumps(parsed_data, indent=2, ensure_ascii=False)}\n```" await target_channel.send(formatted_message) except json.JSONDecodeError: # 如果不是JSON格式,直接发送原始消息 await target_channel.send(f"收到非JSON格式消息:\n{raw_message}") except Exception as e: print(f"处理消息时出错: {e}") # 启动机器人 bot.run(DISCORD_TOKEN)
3. 关键部分说明
- Intents配置:Discord要求必须启用对应Intents才能操作频道和消息,根据实际需求调整权限。
- WebSocket重连机制:
websocket_client函数通过循环实现断开自动重试,保障服务稳定性。 - 消息处理:
process_websocket_message函数负责解析JSON和格式化输出,你可以根据业务需求修改逻辑,比如提取特定字段、生成Discord Embed消息等。
WebSocket连接示意图
┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐ │ WebSocket服务器 │──────▶│ Discord机器人 │──────▶│ Discord目标频道 │ │ (ws://example.com)│ │ │ │ │ └───────────────────┘ └───────────────────┘ └───────────────────┘
内容的提问来源于stack exchange,提问作者OmerFI
相关产品推荐
相关产品推荐

