Discord bot DM与指定服务器频道双向转发问题排查
Discord 双向转发Bot 问题修复代码
已修复问题说明
- 转发循环问题:服务器频道转发到DM的逻辑新增过滤机器人自身发送的消息,避免机器人发去服务器的消息被二次回传到DM
- 多消息丢失问题:启动时预先缓存目标用户DM频道ID,避免每次转发都调用API导致的阻塞丢包;同时简化空消息判断逻辑,避免异常触发提前返回
修复后完整代码
import discum import config bot = discum.Client(token=config.token, log=False) # 全局缓存目标用户DM频道ID,避免重复请求API cached_dm_channel_id = None @bot.gateway.command def on_message(resp): global cached_dm_channel_id if resp.event.ready_supplemental: try: user = bot.gateway.session.user print(f"Forwarding bot started. Logged in as {user['username']}#{user['discriminator']}") guilds = bot.gateway.session.guilds for guild_id, guild in guilds.items(): bot.gateway.request.lazyGuild(guild_id, {1: [[0, 99]]}, typing=True, threads=False, activities=True, members=[]) # 启动时预先创建DM频道并缓存ID if not cached_dm_channel_id: cached_dm_channel_id = bot.createDM([config.user_to_dm_channel_id]).json()["id"] except Exception as e: return if resp.event.message: message = resp.parsed.auto() # 简化空内容/纯空格消息判断,避免原双重否定逻辑误判 if not message.get('content', '').strip(): return try: # 指定用户DM转发到服务器指定频道,保留原有过滤逻辑 if str(message['channel_id']) == str(config.dm_channel_id) and str(message['author']['id']) != str(config.bot_account_user_id): bot.sendMessage(str(config.from_dm_channel_id), message['content'].strip()) # 服务器指定频道转发到用户DM,新增过滤机器人自身消息,使用缓存DM ID elif str(message['channel_id']) == str(config.to_dm_channel_id) and str(message['author']['id']) != str(config.bot_account_user_id) and str(message['author']['id']) != str(config.user_to_dm_channel_id): bot.sendMessage(cached_dm_channel_id, message['content'].strip()) except Exception as e: # 调试时可打开下方注释排查错误 # print(f"转发异常:{str(e)}") pass bot.gateway.run()
内容的提问来源于stack exchange,提问作者bmwturbopeek
相关产品推荐
相关产品推荐

