I can't log in to send messages to the chat

Asked Sep 30, 2024·4 replies·Last activity 1 year ago·Open in Discord ↗
Archived from the original community forum
Things may have changed since it was written. Still stuck? Ask the community on Discord.

Hello!
I'm making a quiz app - guess the bird.
On command in the chat, Nightbot sends a request to the VPS server, where the app node.is should send a link to the picture of the bird to the chat.
And here's the problem with printing a message to the chat.

I'm trying to get authorization for the application and send messages to the chat on YouTube..

//api.nightbot.tv/oauth2/authorize?response_type=code&client_id=689ce560727f86682b3179&redirect_uri=http://localhost:4000&scope=commands%20channel_send%20channel

I get the code but in the end the scope = me

{"access_token":"*****a0b5f8431a84340a","token_type":"bearer","expires_in":2592000,"refresh_token":"ec10bb8619e31e983a79e913","scope":"me"}
And in the end I can't type a message in the chat through the application.
Where to look, please tell me.
I only hope for your help. GPT doesn't know anything.

function sendMessageToChat(message) {
const nightbotWebhookUrl = 'https://api.nightbot.tv/1/channel/send';
// Отправляем сообщение в чат с помощью вебхука
axios.post(nightbotWebhookUrl, null, {
params: {
message: message // Отправляем сообщение как параметр запроса
},
headers: {
'Authorization': `Bearer X`, // Подставь свой токен
'Content-Type': 'application/x-www-form-urlencoded' // Указываем тип контента
}
})
.then(response => {
console.log('Сообщение успешно отправлено в чат Nightbot');
})
.catch(error => {
console.error('Ошибка при отправке сообщения в чат:', error.response ? error.response.data : error.message);
});
}

4 replies

Hiya, what's the issue, are you getting any error messages?

Yes, I get a message that there is no authorization. In the end, I decided not to use a token at all and just send a message to the chat.
The message is sent, but the link is not active. And I wanted people from the chat to follow the link and write in the chat what kind of bird it is.
I'm struggling with how to make the link active.
I use this code.

// Отправка ссылки на изображение птички
app.get('/birdgame', (req, res) => {
currentBird = getRandomBird(); // Обновляем текущую птичку при каждом запросе
const host = req.hostname; // Получаем имя хоста
const port = req.socket.localPort; // Получаем порт, на котором работает сервер
// Формируем строку сообщения вместо объекта
//const message = `<a href="http://${host}:${port}/photo/${currentBird.image}">Отгадай, какая это птица!</a>`;
//const message = `http://${host}:${port}/photo/${currentBird.image}`;
//const message = `http://${host}:${port}/photo/${currentBird.image} Отгадай, какая это птица!`;
const message = `http://${host}:${port}/photo/${currentBird.image}`.trim();
// Отправляем строку, а не JSON
res.send(message);
//res.json({
// imageURL: `http://${host}:${port}/photo/${currentBird.image}`, // Формируем ссылку с портом
// message: 'Отгадай, какая это птица!'
//});
});
Maybe I don't need to get a token to write a message in the chat.
Now I would like to understand why the link in the chat is not active.
The code shows that I tried different options.
Maybe it's the night bot that doesn't allow you to insert links without authorization. I haven't figured it out yet(.

Here's an example with axios from chat gpt:

const axios = require('axios');
const qs = require('qs');
// Replace with your client credentials
const clientId = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
// Obtain OAuth token using Client Credentials Grant with `channel_send` scope
async function getAccessToken() {
const tokenUrl = 'https://api.nightbot.tv/oauth2/token';
const data = {
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
scope: 'channel_send', // Ensure you request the `channel_send` scope
};
try {
const response = await axios.post(tokenUrl, qs.stringify(data), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
return response.data.access_token;
} catch (error) {
console.error('Error fetching access token:', error.response ? error.response.data : error.message);
}
}
// Example function to send a message as Nightbot
async function sendMessage(accessToken, message) {
const nightbotApiUrl = 'https://api.nightbot.tv/1/channel/send';
try {
const response = await axios.post(
nightbotApiUrl,
{ message },
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
console.log('Message sent successfully:', response.data);
} catch (error) {
console.error('Error sending message:', error.response ? error.response.data : error.message);
}
}
// Example usage
(async () => {
const accessToken = await getAccessToken();
if (!accessToken) return;
const message = 'Hello from Nightbot via Client Credentials!';
await sendMessage(accessToken, message);
})();