Get message_id from Telegram message - node.js - javascript

I have a problem concerning a Telegram bot I am currently working on. I get messages from users in the following format:
update { update_id: 82618016,
message:
{ message_id: 363,
from: { id: 22303518, first_name: 'Steve', language_code: 'de-DE' },
chat: { id: 22303518, first_name: 'Steve', type: 'private' },
date: 1501501753,
text: 'j' } }
When I want to access the id of the chat I can do this without any problems by using
$.message.chat.id
As soon as a want to get the message_id or first_name I only get "undefined".
$.message.chat.first_name
$.message.message_id
Can anyone help me here? As far as I see it I understood the structure of the message correctly so I don't really know what's the problem here.
Thank you very much in advance
EDIT: I am adding a bit more of my code here:
The main code for the bot (including the webhook) is this:
initializeBot();
function initializeBot(){
const Telegram = require('telegram-node-bot');
const PingController = require('./controllers/ping');
const OtherwiseController = require('./controllers/otherwise');
const tg = new Telegram.Telegram('MY_TOKEN_IS_HERE', {
webhook: {
url: 'https://xxx.herokuapp.com',
port: process.env.PORT || 443,
host: '0.0.0.0'
}
})
tg.router.when(new Telegram.TextCommand('/ping', 'pingCommand'), new PingController())
.otherwise (new OtherwiseController());
}
When the OtherwiseController gets called the following code is called (I reduced it to the essentials to clarify the problem.
class OtherwiseController extends Telegram.TelegramBaseController {
handle($){
console.log($.message.chat.first_name);
console.log($.message.text);
console.log($.message.chat.id);
console.log($.message.message_id);
}
}
The console output for this message
update { update_id: 82618020,
message:
{ message_id: 371,
from: { id: 22303518, first_name: 'Steve', language_code: 'de-DE' },
chat: { id: 22303518, first_name: 'Steve', type: 'private' },
date: 1501509762,
text: 'hello' } }
would be:
undefined
hello
22303518
undefined

Use the below method to extract the keys of your json object, then you can access with an appropriate key:
Object.keys($.message.chat);

Related

Get User_ID from interactions in DiscordJS

I'm Currently Trying to get the user_id from the interaction.
This code will add command named 'test' that will give option 'testing' and when someone types '1' then it should show the channel_id that the command went from and also the user that did that command.
test.js :
module.exports = {
name: "test",
description: "example",
options: [
{
name: "testing",
description: "testing only.",
type: 3,
required: true,
},
],
async execute(_bot, say, interaction, args) {
let object1 = args[0].value;
if (object1 == '1') {
await say(interaction, 'Channel ID : ' + interaction.channel_id + '\nUser : '+ interaction.message.author.id);
}
else
{
return;
}
},
};
My Problem here that it's not getting the user.id in any way i have tried the following examples :
interaction.member.id;
interaction.user.id;
interaction.user_id;
interaction.member_id;
interaction.guildmember.id;
Noone of them works.
It should've been ;
interaction.member.user.id
Because it appeared in the log under member.

How do I create a text channel discord.js 14

I wanted to ask how to create channels in discord.js 14 (i tried to researched but found nothing) I want to make a simple text channel! :)) Also, with the stuff i found, it worked ( no errors) it just didnt create anything / post errors in debug log
It's literally under Discord.js documentation. Please, next time before asking a question read the docs.
https://discord.js.org/#/docs/discord.js/main/general/welcome
guild.channels.create({
name: "hello",
type: ChannelType.GuildText,
parent: cat[0].ID,
// your permission overwrites or other options here
});
//If the command is slash type
const { Permissions } = require("discord.js")
interaction.guild.channels.create({
name: "new-channel",
type: 'GUILD_TEXT',
permissionOverwrites: [
{
id: interaction.guild.id,
accept: [Permissions.FLAGS.VIEW_CHANNEL],
},
],
});
//If the command is message type
const { Permissions } = require("discord.js")
message.guild.channels.create({
name: "new-channel",
type: 'GUILD_TEXT',
permissionOverwrites: [
{
id: message.guild.id,
accept: [Permissions.FLAGS.VIEW_CHANNEL],
},
],
});

i can't assign a role to an user, via my code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
const Discord = require("discord.js");
require('dotenv').config();
module.exports = {
name: "manuallyverify",
description: "Manually verifies an User.",
limits: {
owner: false,
permission: ["MANAGE_ROLES"],
cooldown: "10s",
},
options: [
{
name: "user",
description: "The User that will be affected by this action.",
type: 6,
required: true,
}
],
run: (client, interaction) => {
let member = interaction.options.getUser("user").toString()
let role = interaction.guild.roles.cache.find(role => role.id == process.env.verified_role_id)
let embed = new Discord.MessageEmbed()
.setTitle(":white_check_mark: ・ Manually Verified the User.")
.addFields(
{
name: "User affected",
value: interaction.options.getUser("user").toString(),
inline: true,
},
{
name: "Role given",
value: `${role}`,
inline: true,
}
)
.setColor("#95eda4");
try {
interaction.guild.member.roles.cache.add(role)
interaction.reply({ embeds: [embed] });
} catch (e) {
interaction.reply({content:`I encountered an error: ${e}`, ephemeral: true});
}
},
};
so, this is my code, i'm making a simple verification bot that will be a template on github , but when i run the command, it gives me this error:
TypeError: Cannot read properties of undefined (reading 'roles')
so, i guess the error is because something is undefinited between interaction.guild, or guild.member. i didnt code for a while so i'm probably missing / forgetting something
also, sorry if my framework is bad
edit: i got this code to work thanks to a guy in the comments, so, thanks for coming here and have a good day
There isn't any property called interaction.guild.member and I assume what you are trying to do is to add the role to the user provided. Therefore, what you could do is use interaction.options.getMember("user") to get the user in the option and then add the role to that GuildMember. A small example:
const Discord = require("discord.js");
require('dotenv').config();
module.exports = {
name: "manuallyverify",
description: "Manually verifies an User.",
limits: {
owner: false,
permission: ["MANAGE_ROLES"],
cooldown: "10s",
},
options: [
{
name: "user",
description: "The User that will be affected by this action.",
type: 6,
required: true,
}
],
run: (client, interaction) => {
let memberToAddRole = interaction.options.getMember("user")
let role = interaction.guild.roles.cache.find(role => role.id == process.env.verified_role_id)
let embed = new Discord.MessageEmbed()
.setTitle(":white_check_mark: ・ Manually Verified the User.")
.addFields(
{
name: "User affected",
value: memberToAddRole.user.toString(),
inline: true,
},
{
name: "Role given",
value: `${role}`,
inline: true,
}
)
.setColor("#95eda4");
try {
memberToAddRole.roles.cache.add(role)
interaction.reply({ embeds: [embed] });
} catch (e) {
interaction.reply({content:`I encountered an error: ${e}`, ephemeral: true});
}
},
};
Note: the code you provided was a bit inefficient and redundant in some parts, so I have changed that accordingly
The error message tells you exactly where and what your issues is. The error message indicates that roles is undefined, so either interaction.guild.roles or interaction.guild.member.roles is undefined.

Interaction has already been acknowledged

I am currently having an issue with my /help command, the way my /help command works is it sends a nice fancy embed with a selectmenu that you can select different pages. That all works fine the issue comes when if I were to do /help and get the embed then do /help again and interact with the second embed it will crash and give the error "Interaction has already been acknowledged" Here is my code.
const generalHelp = { // Creates generalHelp embed.
color: 0x901ab6,
title: 'join our support server!',
url: 'https://discord.gg/MUwJ85wpKP',
author: {
name: 'Help Menu',
icon_url: 'https://cdn.discordapp.com/attachments/937276227692150815/937552170520301588/Letter_Z.png',
},
description: 'Select an option to view the commands I have!',
fields: [
{
name: ':tada: Fun Commands',
value: 'Shows all the bots varying fun commands in a nice little page for easy viewing.',
inline: true,
},
{
name: ':tools: Admin Commands',
value: 'Shows all the bots varying admin commands in a nice little page for easy viewing.',
inline: true,
},
/*{
name: '\u200b',
value: ' \u200b ',
inline: false,
},*/
],
}
const adminHelp = { // Creates moderationHelp embed.
color: 0x901ab6,
author: {
name: 'Help Menu',
icon_url: 'https://cdn.discordapp.com/attachments/937276227692150815/937552170520301588/Letter_Z.png',
},
description: 'Here are the commands!',
fields: [
{
name: 'Prefix: `/`',
value: '\u200b',
},
{
name: ':tools: Admin Commands',
value: '`toggle`, `settings`'
},
]
}
const funHelp = { // Creates funHelp embed.
color: 0x901ab6,
author: {
name: 'Help Menu',
icon_url: 'https://cdn.discordapp.com/attachments/937276227692150815/937552170520301588/Letter_Z.png',
},
description: 'Here are the commands!',
fields: [
{
name: 'Prefix: `/`',
value: '\u200b',
},
{
name: ':tada: Fun Commands',
value: '`ping`, `poll`',
},
]
}
const row = new MessageActionRow() // Creates MessageActionRow with name row.
.addComponents(
new MessageSelectMenu()
.setCustomId('select')
.setPlaceholder('Select an option')
.addOptions([
{
label: '🎉 Fun Commands',
description: '',
value: 'first_option',
},
{
label: '🔨 Admin Commands',
description: '',
value: 'second_option',
},
])
)
await interaction.reply({ embeds: [generalHelp], components: [row]}) // Displays general help embed
And here is my code that handles the interactions.
interaction.client.on('interactionCreate', interaction => { // Detects which value is selected.
if(!interaction.isSelectMenu()) return
if (interaction.values[0] === 'first_option') // Checks if values[0] is = to first_option to display gameHelp embed.
{
interaction.update({embeds: [funHelp]}) // Updates bots interaction embed
}
if (interaction.values[0] === 'second_option') // Checks if values[0] is = to second_option to display musicHelp embed.
{
interaction.update({embeds: [adminHelp]}) // Updates bots interaction embed
}
else // If values[0] is anything else display error message to console. (PM2 will auto restart bot if error happens.)
{
return//console.log('Help Menu Select Menu Error!') // Logging to PM2 console.
}
})
If someone could help me fix it that would be great <3
Its because you already .reply()-ed to the interaction, so the interaction is already acknowledged with that.
To solve this you can use .editReply():
interaction.reply({ content: 'This is my first reply!' });
interaction.editReply({ content: 'This my edited second reply!' });
For anyone still looking for an answer the reason this happens is because the first time it works 100% fine because there is no update and is a fresh interaction. However when you try and update it which also counts as an interaction. Putting your interactionCreate code into an event handler solves this issue.
module.exports = {
name: 'interactionCreate',
execute(interaction) {
//console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
if (!interaction.isSelectMenu() && interaction.isCommand()) return
if (interaction.customId !== 'select') return
switch (interaction.values[0]) {
case 'first_option':
interaction.update({embeds: [funHelp], ephemeral: true})
break
case 'second_option':
interaction.update({embeds: [adminHelp], ephemeral: true})
break
default:
return
}
},
};

what is the use of resize:detect azure chatbot node js

I would like to know why we have resize:detect option in renderwebchat function for azure chat bot.Can someone explain me whats the outcome or whats the use of this option.
window.WebChat.renderWebChat({
renderMarkdown: markdownIt.render.bind(markdownIt),
directLine: window.WebChat.createDirectLine({
token: '#ViewData["DirectLineToken"]'
}),
user: {
id: 'test#xx.com,test#xx.com',
name: 'You',
OverrideBlockAccess: '#ViewData["OverrideBlockAccess"]',
LoggedInUserEmail: '#Html.Raw(ViewData["LoggedInUserEmail"])',
UserEmail: '#Html.Raw(ViewData["UserEmail"])'
},
bot: { id: 'HPICEBoTAPP' },
resize: 'detect',
userId: '#Html.Raw(ViewData["UserEmail"])',
styleOptions: styleOptions
}
You can see the properties that can be passed to renderWebChat here: https://github.com/microsoft/BotFramework-WebChat/blob/master/docs/API.md
Notice that there is no user, bot, or resize property.

Categories

Resources