Issue Description
I would like to send LINE stickers after sending generated text from the OpenAI API using a LINE Bot. The flow is as follows:
The user enters a keyword in the LINE Bot (e.g., “doll”).
- send a request to the OpenAI API to generate a horror story related to the keyword.
- send the horror story back to LINE as a text message.
- want to send stickers after the text message.
I’m using the Messaging API.
https://developers.line.biz/ja/docs/messaging-api/sticker-list/
When I execute the code, steps 1, 2, and 3 are successful. However, the stickers are not being sent.
The execution environment is as follows:
- GitHub Codespaces
- JavaScript
"@line/bot-sdk": "^7.5.2",
"axios": "^1.4.0",
"express": "^4.18.2",
"line-bot-sdk": "^0.1.4",
"openai": "^3.2.1"
Problem/Error Occurring
When I run the code, the following error is displayed. The error occurs when trying to send the sticker message:
@xxxx ➜ /workspaces/xxxx/boot/02-line-bot (main) $ node horror2.js
Running Express server on port 3000...
Received: [
{
type: 'message',
message: { type: 'text', id: 'xxxx', text: 'tea' },
webhookEventId: 'xxxx',
deliveryContext: { isRedelivery: false },
timestamp: 1685232670580,
source: { type: 'user', userId: 'xxxx' },
replyToken: 'xxxx',
mode: 'active'
}
]
[
{
role: 'system',
content: 'You are a seasoned ghost storyteller. Please write a horror story using the keyword provided by the user.'
},
{ role: 'user', content: 'tea' }
]
Sticker message sending error: HTTPError: Request failed with status code 400
at HTTPClient.wrapError (/workspaces/xxxx/boot/02-line-bot/node_modules/@line/bot-sdk/dist/http.js:89:20)
at /workspaces/xxxx/boot/02-line-bot/node_modules/@line/bot-sdk/dist/http.js:19:88
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async HTTPClient.post (/workspaces/xxxx/boot/02-line-bot/node_modules/@line/bot-sdk/dist/http.js:33:21)
at async sendStickerMessage (/workspaces/xxxx/boot/02-line-bot/horror2.js:82:5)
at async handleEvent (/workspaces/xxxx/boot/02-line-bot/horror2.js:71:5)
at async Promise.all (index 0) {
statusCode: 400,
statusMessage: 'Bad Request',
originalError: [AxiosError: Request failed with status code 400] {
code: 'ERR_BAD_REQUEST',
config: {
transitional: [Object],
adapter: [Function: httpAdapter],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: [Object],
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'https://api.line.me/v2/bot/message/reply',
data: '{"messages":[{"type":"sticker","packageId":"446","stickerId":"2027"}],"replyToken":"xxxx","notificationDisabled":false}'
},
request: ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
strictContentLength: false,
_contentLength: 147,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: [TLSSocket],
_header: 'POST /v2/bot/message/reply HTTP/1.1rn' +
'Accept: application/json, text/plain, /rn' +
'Content-Type: application/jsonrn' +
'Authorization: Bearer xxxxrn' +
'User-Agent: @line/bot-sdk/7.5.2rn' +
'Content-Length: 147rn' +
'Host: api.line.mern' +
'Connection: keep-alivern' +
'rn',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: [Agent],
socketPath: undefined,
method: 'POST',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
joinDuplicateHeaders: undefined,
path: '/v2/bot/message/reply',
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: [Function: emitRequestTimeout],
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: true,
host: 'api.line.me',
protocol: 'https:',
_redirectable: [Writable],
[Symbol(kCapture)]: false,
[Symbol(kBytesWritten)]: 0,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype],
[Symbol(errored)]: null,
[Symbol(kHighWaterMark)]: 16384,
[Symbol(kUniqueHeaders)]: null
},
response: {
status: 400,
statusText: 'Bad Request',
headers: [Object],
config: [Object],
request: [ClientRequest],
data: [Object]
}
}
}
^C
@xxxx ➜ /workspaces/xxxx/boot/02-line-bot (main) $
Code
'use strict';
// ########################################
// Initialization and Configuration
// ########################################
// Load modules
const line = require('@line/bot-sdk');
const openai = require('openai');
const express = require('express');
const PORT = process.env.PORT || 3000;
// Configuration
const config = {
channelSecret: 'CHANNEL_SECRET',
channelAccessToken: 'CHANNEL_ACCESS_TOKEN'
};
// Create client
const client = new line.Client(config);
const gptConfig = new openai.Configuration({
organization: process.env.OPENAI_ORGANIZATION || "ORGANIZATION_ID",
apiKey: process.env.OPENAI_API_KEY || 'API_KEY',
});
const gpt = new openai.OpenAIApi(gptConfig);
const makeCompletion = async (userMessage) => {
const prompt = {
role: 'system',
content: 'You are a skilled ghost storyteller. Please write a ghost story using the keywords specified by the user.' // Enter the prompt
};
userMessage.unshift(prompt);
console.log(userMessage);
return await gpt.createChatCompletion({
model: 'gpt-3.5-turbo',
messages: userMessage,
temperature: 0.5,
n: 1
});
};
// Handle message events
async function handleEvent(event) {
// Ignore non-text message types
if (event.type !== 'message' || event.message.type !== 'text') {
return Promise.resolve(null);
}
const userMessage = [
{
role: 'user',
content: event.message.text
}
];
// Send a request to the ChatGPT API
try {
const completion = await makeCompletion(userMessage);
// Get the response
const reply = completion.data.choices[0].message.content;
// Send the reply to LINE
await client.replyMessage(event.replyToken, {
type: 'text',
text: reply
});
// Send a sticker message
await sendStickerMessage(event.replyToken);
} catch (error) {
// Output the error to the log if an error occurs
console.error('Error sending message:', error);
return Promise.resolve(null);
}
}
// Send a sticker message
async function sendStickerMessage(replyToken) {
try {
await client.replyMessage(replyToken, {
type: 'sticker',
packageId: '446', // Replace with the package ID of the sticker
stickerId: '2027' // Replace with the sticker ID
});
console.log('Sticker message sent');
} catch (error) {
console.error('Error sending sticker message:', error);
}
}
const app = express();
app.get('/', (req, res) => res.send('Hello LINE BOT! (HTTP GET)'));
app.post('/webhook', line.middleware(config), (req, res) => {
if (req.body.events.length === 0) {
res.send('Hello LINE BOT! (HTTP POST)');
console.log('Verification event received!');
return;
} else {
console.log('Received:', req.body.events);
}
Promise.all(
req.body.events.map((event) => {
if (event.type === 'message' && event.message.type === 'text') {
return handleEvent(event);
} else if (event.type === 'message' && event.message.type === 'sticker') {
return handleMessageEvent(event);
} else {
return null;
}
})
).then((result) => res.json(result));
});
app.listen(PORT);
console.log(`Running Express server on port ${PORT}...`);
Troubleshooting Steps Taken
I attempted troubleshooting with the help of ChatGPT, but I couldn’t identify the specific issue. Since I don’t have experience writing code, I couldn’t narrow down the areas that need to be fixed. I would appreciate any advice or key points to check.

