【问题标题】:Await is only valid in async function Canvas Discord JSAwait 仅在异步函数 Canvas Discord JS 中有效
【发布时间】:2020-07-31 03:28:22
【问题描述】:

我对编码很陌生,并按照在线教程介绍了如何使用画布进行图像处理,但我收到此错误,抱歉打扰!任何帮助表示赞赏

if (message.author.bot) return;
    msg = message.content.toLowerCase();
    if(msg.includes("test")) {
        const sayMessage = message.content.split(' ').slice(2).join(' ')

        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);

        ctx.font = applyText(canvas, sayMessage);
        ctx.fillStyle = '#ffffff';
        ctx.fillText(sayMessage, 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({ format: 'jpg' }));
        ctx.drawImage(avatar, 25, 25, 200, 200);

        const attachment = new Discord.MessageAttachment(canvas.toBuffer(), 'test.png');

        channel.send(attachment);
    } 

【问题讨论】:

    标签: javascript canvas discord discord.js


    【解决方案1】:

    您很可能需要将async 添加到您的.onMessage 事件中。它应该看起来像这样:

    bot.on('message', async message => {
        //do your commands here
    })
    
    

    注意message => {} 部分前面的async。 这就是允许您在 onMessage 事件中使用 await 的原因。

    【讨论】:

    • 所以我猜如果我使用“客户端”代替,我会用它代替机器人吗?
    • 是的,没错! ^^
    【解决方案2】:

    正是错误所说的。等待任何其他函数的函数必须是异步函数。

    例如:

    async function wait() {
        await somefunction() // correct because function is async
    }
    

    然而

    function wait() {
        await somefunction() // error
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 2020-09-11
      • 2021-08-10
      • 1970-01-01
      • 2020-09-07
      • 2019-09-12
      • 1970-01-01
      • 2022-06-18
      • 2020-12-07
      相关资源
      最近更新 更多