Node-gd's copy function is not recognized

Viewed 45

I inherited a Discord bot that uses node-gd to make banners with data a user inputs. When making the banner, I use the .copy function to place an image on top of the base image. However, when I run my code, it throws an error saying it's not a function.

Here's the relevant code (user.input is a number 1-5, and is ? by default):

   if (user.input != '?') {
    imgTemp = gd.createFromPng(`./img/INPUT_${user.input}.png`);
    imgTemp.copy(img, 213, 60, 0, 0, 37, 17);
}

And here's the error:

> /home/discordbots/Desktop/bots/splatoonBot/splatBot2.js:676
>             imgTemp.copy(img, 213, 60, 0, 0, 37, 17);
>                     ^ TypeError: imgTemp.copy is not a function
>     at generateBanner (/home/discordbots/Desktop/bots/splatoonBot/splatBot2.js:676:21)
>     at Client.<anonymous> (/home/discordbots/Desktop/bots/splatoonBot/splatBot2.js:894:25)
>     at Client.emit (events.js:315:20)
>     at MessageCreateAction.handle (/home/discordbots/Desktop/bots/splatoonBot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
>     at Object.module.exports [as MESSAGE_CREATE] (/home/discordbots/Desktop/bots/splatoonBot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
>     at WebSocketManager.handlePacket (/home/discordbots/Desktop/bots/splatoonBot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
>     at WebSocketShard.onPacket (/home/discordbots/Desktop/bots/splatoonBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:436:22)
>     at WebSocketShard.onMessage (/home/discordbots/Desktop/bots/splatoonBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
>     at WebSocket.onMessage (/home/discordbots/Desktop/bots/splatoonBot/node_modules/ws/lib/event-target.js:125:16)
>     at WebSocket.emit (events.js:315:20)
1 Answers

This is because gd.createFromPng returns a promise. It is not a class that contains the method copy. You can read more about this in the node-gd documentation.

So essentially:

if (user.input != '?') {
    // the "await" keyword lets you grab the actual value from the promise
    let imgTemp = await gd.createFromPng(`./img/INPUT_${user.input}.png`);
    // You can then implement the copy method on this newly returned value
    imgTemp.copy(img, 213, 60, 0, 0, 37, 17);
}

Hopefully this solves your problem.

Related