如何在Discord中查找包含表情符号的指定名称频道?
解决Discord.js中带表情符号的频道查找问题
看起来你遇到了两个核心问题:一是精确匹配频道名在带表情时失效,二是想实现模糊匹配(只要包含指定关键词即可),还有乱码显示的疑惑。下面一步步帮你解决:
1. 从精确匹配改为模糊匹配(包含指定关键词)
原来的代码用===做严格相等匹配,这就要求频道名必须完全和你写的welcome一致,带表情自然匹配不上。我们可以改成检查频道名是否包含目标关键词,有两种可靠的方式:
方法A:直接使用includes(简单直接)
如果你的代码环境能正确识别Discord返回的表情符号(比如你在代码里写的表情和频道名的表情编码一致),直接用includes就能实现模糊匹配:
// 查找名称包含"welcome"的频道,不管前后有没有表情 const channel = member.guild.channels.find(ch => ch.name.includes('welcome'));
方法B:移除表情后再匹配(更稳定)
如果遇到表情编码不一致的情况(比如你看到的乱码问题),可以先把频道名里的所有表情符号移除,再检查是否包含关键词。用Unicode正则表达式可以轻松实现:
const channel = member.guild.channels.find(ch => { // 移除所有Unicode表情符号,然后去除首尾空格 const cleanChannelName = ch.name.replace(/\p{Emoji}/gu, '').trim(); // 检查清理后的名称是否包含目标关键词 return cleanChannelName.includes('welcome'); });
这里的/\p{Emoji}/gu正则会匹配所有Unicode标准的表情符号,g表示全局替换,u启用Unicode模式确保正确解析表情字符。
2. 关于乱码的解释
你看到的≡ƒô£welcome≡ƒô£是显示编码不兼容导致的:Discord返回的频道名是Unicode格式的表情符号,但你的记事本/终端用了不支持Unicode的编码(比如Windows-1252),所以把表情显示成了乱码。但在代码中,ch.name存储的是正确的Unicode字符串,你完全不需要处理这些乱码字符,直接操作原始的name字段即可。
修改后的完整代码
把原来的查找频道代码替换成上面的方法,完整代码如下:
// 这里用方法B的稳定版本,也可以换成方法A const channel = member.guild.channels.find(ch => { const cleanChannelName = ch.name.replace(/\p{Emoji}/gu, '').trim(); return cleanChannelName.includes('welcome'); }); if (!channel) return; const canvas = Canvas.createCanvas(700, 250); const ctx = canvas.getContext('2d'); const background = await Canvas.loadImage('./wallpaper.jpg'); ctx.drawImage(background, 0, 0, canvas.width, canvas.height); ctx.strokeStyle = '#74037b'; ctx.strokeRect(0, 0, canvas.width, canvas.height); // Slightly smaller text placed above the member's display name ctx.font = '28px sans-serif'; ctx.fillStyle = '#ffffff'; ctx.fillText('Welcome to the server,', canvas.width / 2.5, canvas.height / 3.5); // Add an exclamation point here and below ctx.font = applyText(canvas, `${member.displayName}!`); ctx.fillStyle = '#ffffff'; ctx.fillText(`${member.displayName}!`, canvas.width / 2.5, canvas.height / 1.8); ctx.beginPath(); ctx.arc(125, 125, 100, 0, Math.PI * 2, true); ctx.closePath(); ctx.clip(); const avatar = await Canvas.loadImage(member.user.displayAvatarURL); ctx.drawImage(avatar, 25, 25, 200, 200); const attachment = new Discord.Attachment(canvas.toBuffer(), 'welcome-image.png'); channel.send(`Welcome to the server, ${member}!`, attachment);
如果要查找levels频道,只需要把cleanChannelName.includes('welcome')里的welcome改成levels就行啦。
内容的提问来源于stack exchange,提问作者Root Android




