The title is my problem. Here is the code I'm using:
const voiceChannel = message.guild.channels.find(channel => channel.name === args[0]);
if (!voiceChannel || voiceChannel.type !== 'voice') {
return message.reply(`I couldn't find the voice channel ${args[0]}.`);
}
await voiceChannel.join();
let connection = message.guild.voiceConnection;
connection.on('speaking', (user, speaking) => {
if(speaking) {
const receiver = connection.createReceiver();
const stream = receiver.createPCMStream(user);
receiver.on('opus', (user, buffer) => {
console.log('got some data');
});
stream.on('data', chunk => {
console.log(chunk.length);
});
}
});
Nothing prints in the console, so I guess the stream and voice receiver just aren't receiving any data. Also, I've looked at lots of posts and lots of people use this code and it works for them. If anybody knows why this is happening please help!!
Thanks in advance.
It's a bit late to answer but might help someone else.
You must send a silent frame first.
const { Readable } = require('stream');
class Silence extends Readable {
_read() {
this.push(Buffer.from([0xF8, 0xFF, 0xFE]));
}
}
Once the connection is established with the voice channel you can do something like this:
connection.on('ready', ()=>{
connection.play(new Silence(), { type: 'opus' });
})
For more details, you can visit this page
Related
I have a raw event:
this.on('raw', packet => {
if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
const channel = this.channels.cache.get(packet.d.channel_id);
if (channel.messages.cache.has(packet.d.message_id)) return;
channel.messages.fetch(packet.d.message_id).then(message => {
const emoji = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
const reaction = message.reactions.cache.get(emoji);
if (reaction) reaction.users.cache.set(packet.d.user_id, this.users.cache.get(packet.d.user_id));
if (packet.t === 'MESSAGE_REACTION_ADD') {
this.emit('messageReactionAdd', reaction, this.users.cache.get(packet.d.user_id));
}
if (packet.t === 'MESSAGE_REACTION_REMOVE') {
this.emit('messageReactionRemove', reaction, this.users.cache.get(packet.d.user_id));
}
});
});
This event spams continuously when one reaction is added, I want to make it so if you react it will run once. How can I do this?
You should not use the raw event past discord.js version 12. As there are some issues when your bot grows.
Instead use Partials as explained in the offical Discord.js Guide
const Discord = require('discord.js');
const client = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
client.on('messageReactionAdd', async (reaction, user) => {
// When we receive a reaction we check if the reaction is partial or not
if (reaction.partial) {
// If the message this reaction belongs to was removed the fetching might result in an API error, which we need to handle
try {
await reaction.fetch();
} catch (error) {
console.error('Something went wrong when fetching the message: ', error);
// Return as `reaction.message.author` may be undefined/null
return;
}
}
// Now the message has been cached and is fully available
console.log(`${reaction.message.author}'s message "${reaction.message.content}" gained a reaction!`);
// The reaction is now also fully available and the properties will be reflected accurately:
console.log(`${reaction.count} user(s) have given the same reaction to this message!`);
});
Source and more information: https://discordjs.guide/popular-topics/reactions.html#listening-for-reactions-on-old-messages
I need some help with PubSub...
I need to send a message to a topic every time someone accept cookies in my website. This message should contain the encodedURL that contains the services accepted.
I have this script:
const topicName = "myTopic";
const data = JSON.stringify({
encodeConsentURL:""
});
// Imports the Google Cloud client library
const { PubSub } = require("#google-cloud/pubsub");
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function publishMessageWithCustomAttributes() {
// Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)
const dataBuffer = Buffer.from(data);
// Add two custom attributes, origin and username, to the message
const customAttributes = {};
const messageId = await pubSubClient
.topic(topicName)
.publish(dataBuffer, customAttributes);
console.log(`Message ${messageId} published.`);
console.log(customAttributes);
}
publishMessageWithCustomAttributes().catch(console.error);
This code works, it sends the message, what I'm finding very hard to do is how to set everything right for running this code in my cookie script. In my cookie script I have a function that writes the cookie, in the same function I would like to send the message, is this possible? Thanks in advance!
It is a bit late, but I don't get it, if you already have a working cookie script and a working publish script, isn't it just about putting them together?
If you still need help I'll be happy to help you
Something like
const runEverything = async () => {
try {
await checkCookiesThing()
await publishMessage()
} catch (e) {
console.error(e)
}
}
I've been trying to create a Discord bot. A lot of interactions are done through reactions, and I've been aware of the fact that only cached messages triggered the messageReactionAdd event. So I picked the following piece of code that is supposed to emit the packets corresponding to reactions added to "old" (not cached) messages. But it seems to completely block any packets concerning reactions adding because now none is emitted. Is there something that I've been doing wrong ?
Thanks.
My "raw.js" file :
module.exports = {
run: (client, packet) => {
// We don't want this to run on unrelated packets
if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
// Grab the channel to check the message from
const channel = client.guilds.cache.get(packet.d.guild_id).channels.cache.get(packet.d.channel_id);
const messageID = packet.d.message_id;
// There's no need to emit if the message is cached, because the event will fire anyway for that
if (channel.messages.has(messageID)) return;
// Since we have confirmed the message is not cached, let's fetch it
channel.messages.fetch(messageID).then(message => {
// Emojis can have identifiers of name:id format, so we have to account for that case as well
const emoji = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
// This gives us the reaction we need to emit the event properly, in top of the message object
const reaction = message.reactions.get(emoji);
// Adds the currently reacting user to the reaction's users collection.
if (reaction) reaction.users.set(packet.d.user_id, client.users.get(packet.d.user_id));
// Check which type of event it is before emitting
if (packet.t === 'MESSAGE_REACTION_ADD') {
client.emit('messageReactionAdd', reaction, client.users.get(packet.d.user_id));
}
if (packet.t === 'MESSAGE_REACTION_REMOVE') {
client.emit('messageReactionRemove', reaction, client.users.get(packet.d.user_id));
}
});
}
};
My "event fetcher" :
const fs = require('fs')
fs.readdir('./events/', (err, files) => {
if (err) return console.error(err);
files.forEach((file) => {
const eventFunction = require(`./events/${file}`);
if (eventFunction.disabled) return;
const event = eventFunction.event || file.split('.')[0];
const emitter = (typeof eventFunction.emitter === 'string' ? client[eventFunction.emitter] : eventFunction.emitter) || client;
const { once } = eventFunction;
try {
emitter[once ? 'once' : 'on'](event, (...args) => eventFunction.run(client, ...args));
} catch (error) {
console.error(error.stack);
}
});
});
From the discord.js discord server's #faq channel:
Bug:
β’ 'messageReactionAdd' does not fire despite proper partials enabled
PR: https://github.com/discordjs/discord.js/pull/4969 (merged, waiting for release)
Temporary fix is to ensure the addition of GUILD_MEMBER partial in the client definition
new Discord.Client({
partials: ['USER', 'GUILD_MEMBER', 'CHANNEL', 'MESSAGE', 'REACTION'],
});
So, I need a way to forward a message sent in the bot's dm to a specific channel in my server.
this is the code that I got so far:
execute(message, args) {
if(message.channel.type == "dm"){
let cf = args.join(' ')
const cfAdm = message.guild.channels.cache.get('767082831205367809')
let embed = new discord.MessageEmbed()
.setTitle('**CONFISSΓO**')
.setDescription(cf)
.setColor('#000000')
const filter = (reaction, user) => ['π', 'π'].includes(reaction.emoji.name);
const reactOptions = {maxEmojis: 1};
cfAdm.send(embed)
.then(function (message) {
message.react('π')
.then(() => message.react('π'))
/**** start collecting reacts ****/
.then(() => message.awaitReactions(filter, reactOptions))
/**** collection finished! ****/
.then(collected => {
if (collected.first().emoji.name === 'π') {
const cfGnr = message.guild.channels.cache.get('766763882097672263')
cfGnr.send(embed)
}
})
});
}
else {
message.delete()
message.channel.send('Send me this in the dm so you can stay anon')
.then (message =>{
message.delete({timeout: 5000})
})
}
}
But for some reason that I can't seem to understand, it gives me this error:
TypeError: Cannot read property 'channels' of null
If anyone can help me, that would be greatly apreciated.
Thanks in advance and sorry for the bad english
The error here is that you are trying to call const cfAdm = message.guild.channels.cache.get('ID') on a message object from a Direct Message channel ( if(message.channel.type == "dm"){)
DMs don't have guilds, therefore message.guild is null and message.guild.channels does not exist.
You will need to first access the channel some other way. Luckily, Discord.js has a way to access all channels the bot can work with* (you don't need to muck around with guilds because all channels have unique IDs):
client.channels.fetch(ID) or client.channels.cache.get(ID)
(I have not tested this but it seems fairly straight forward)
*See the link for caveats that apply to bots in a large amount of servers.
I searched it up and got a code with readline where it looks like this:
const Disc = require('discord.js');
const client = new Disc.Client();
const token = 'token'
const readline = require('readline');
client.login(token);
client.on('message', function(message){
if(message.channel.type === 'dm'){
console.log("[" + message.author.username + "]: " + message.content)
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('REPLY TO ' + message.author.username + ': ', (answer) => {
message.author.send(`${answer}`);
rl.close();
});
}
});
But it doesn't work helpp
This is a topic I just did recently actually, so I'll walk you through it and give you some code to go along with it.
First, I would like to say when your making a post, include a clear question. From what it sounds like, your asking for a bot that logs dms to the console, or responds to them. I will just answer both questions.
The easiest way to check for a DM is to see if the message channel type is DM. Check here for more info on the channel class. You can check if a channel is a certain type by doing this:
if (message.channel.type === 'dm'){ } // change dm to the type you want
This will have to go in your on message function, so right now, if you're following along, the code would look like this:
bot.on('message', async message => {
if (message.channel.type === 'dm'){ }
});
From there it's simply adding code to the inside of the if statement. You will always want a return statement inside of it just incase nothing happens, so it doesn't try to do anything in the channels.
For what you want, this will log the DM to the console and reply to it, if it is equal to a certain message.
bot.on('message', async message => {
if (message.channel.type === 'dm'){
console.log(message.content);
if(message.content === "something"){
return await message.channel.send("Hi!");
}
return;
}
});
This should do what you want, if you have any questions, comment it on here and I'll respond as soon as possible :)
edit:
bot.on('message', async message => {
if (message.channel.type === 'dm'){
console.log(`${message.author.username} says: ${message.content}`);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(`REPLY TO ${message.author.username}: `, (answer) => {
message.author.send(`${answer}`);
rl.close();
});
}
});