Twitch bot multiple channels but message only at 1 - javascript

So my bot is connected to 3 channels and if all 3 channels are online how can bot only work on First channel if he's going offline so swap to next channel
const tmi = require('tmi.js'),
{ channel, username, password } = require('./settings.json');
const options = {
options: { debug: true },
connection: {
reconnect: true,
secure: true
},
identity : {
username,
password
},
channels: [
'#Pok1',
'#Pok2',
'#Pok3',
]
};
const client = new tmi.Client(options);
client.connect().catch(console.error);
client.on('connected', () => {
client.say(channel, ``);
});
client.on('message', (channel, user, message, self) => {
if(self) return;
if(user.username == 'asd' && message === "zxc") {
client.say(channel, 'abc');
}
});

To say something in a channel you use client.say(channel, message);.
So if you only want to say something in only one channel, you would have to save the channel somewhere:
const TALK_CHANNEL = '#Pok_X';
client.on('message', (channel, user, message, self) => {
if(self) return;
if(user.username == 'asd' && message === "zxc") {
client.say(TALK_CHANNEL, 'abc');
}
Handling the channel swapping would look like this:
const USERNAME = 'asd';
const CHANNELS = ['#pok1', '#pok2', '#pok3', ];
let current_channel = null;
let last_joined_channel = null;
// From docs:
// Username has joined a channel. Not available on large channels and is also sent in batch every 30-60secs.
client.on("join", (channel, username, self) => {
if (username != USERNAME || !CHANNELS.includes(channel))
return;
last_joined_channel = channel;
if (current_channel === null)
current_channel = channel;
});
// user left a channel
client.on("part", (channel, username, self) => {
if (username != USERNAME || !CHANNELS.includes(channel))
return;
current_channel = last_joined_channel;
last_joined_channel = null;
});
client.on('message', (channel, user, message, self) => {
if(self)
return;
if(user.username == USERNAME && message === "zxc" && current_channel != null) {
client.say(current_channel, 'abc');
}

Related

Discord.js: Add role to message sender

i am trying to make a discord.js bot that adds a role to a user when they type: +rolename .
This is what I have come up with:
const { Client } = require("discord.js");
const { config } = require("dotenv");
const fs = require('fs');
const client = new Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION']
});
config({
path: __dirname + "/.env"
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setStatus('online');
client.user.setActivity('me getting developed', { type: "WATCHING"})
.then(() => console.log('bot status set'))
.catch(console.error);
});
client.on("message", (message) => {
if (message.content.startsWith("+")) {
var args = message.content.split(' ');
if (args.length == 1) {
console.log(`message is created -> ${message}`);
const { guild } = message;
var passrole = args[0];
var roleid = passrole.substring(1);
var role = message.guild.roles.cache.find((role) => {
return role.name == roleid;
});
console.log('role found')
var authoruser = message.author.id;
if (!role) {
message.reply('this role does not exist')
console.log('role does not exist')
return;
}
console.log(target)
authoruser.roles.add(role)
console.log("role added")
} else {
message.reply('invalid argument length passed')
return;
}
} else {
return;
}
});
client.login(process.env.TOKEN);
When running the code i get the following error:
TypeError: Cannot read property 'add' of undefined
This doesn't happen when I use this code and type +test #DiscordName#0001:
const { Client } = require("discord.js");
const { config } = require("dotenv");
const fs = require('fs');
const client = new Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION']
});
config({
path: __dirname + "/.env"
})
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setStatus('online');
client.user.setActivity('me getting developed', { type: "WATCHING"})
.then(presence => console.log('bot status set'))
.catch(console.error);
});
client.on("message", (message) => {
let target = message.mentions.members.first();
if (message.content.startsWith("+")) {
var args = message.content.split(' ');
if(args.length == 2){
console.log(`message is created -> ${message}`);
const { guild } = message;
var passrole = args[0]
var roleid = passrole.substring(1);
var role = message.guild.roles.cache.find((role) => {
return role.name == roleid;
})
console.log('role found')
if (!role) {
message.reply('role does not exist')
console.log('role does not exist')
return;
}
console.log(target)
target.roles.add(role)
console.log("role added")
} else {
message.reply('invalid argument length passed')
return;
}
} else {
return;
}
});
client.login(process.env.TOKEN);
My question is: How can I add the role to the message author.
Thanks in advance
The problem is that your authoruser is the users id (= string) not the member. You cannot add roles to users. Also if you get the role's id and not the name of the role you can add the role with the role's id.
client.on("message", message =>{
if (message.content.startsWith("+")) {
var args = message.content.split(' ');
if (args.length !== 1) {
message.reply('invalid argument count passed');
return;
}
if (!message.member ||!message.guild) {
message.reply('can only be used in guilds');
return;
}
console.log(`message is created -> ${message}`);
const { guild } = message;
var passrole = args[0];
var roleid = passrole.substring(1);
// If you get the role's id then you won't need this
var role = message.guild.roles.cache.find((role) => role.name == roleid);
if (!role) {
message.reply('this role does not exist');
console.log('role does not exist');
return;
}
console.log('role found');
console.log(target);
message.member.roles.add(role);
// If you get the role's id use this:
message.member.roles.add(roleid);
console.log('role added');
});

Need help adding a role to a user. (discord.js)

When I'm online the bot gives me a role, as soon as I go offline the bot removes that role from me.
When it removes the role, I want the bot to give the role to a specific user. How can I do that?
I have my current code below:
client.on('presenceUpdate', (oldPresence, newPresence) => {
const member = newPresence.member;
if (member.id === 'user.id') {
if (oldPresence.status !== newPresence.status) {
var gen = client.channels.cache.get('channel.id');
if (
newPresence.status == 'idle' ||
newPresence.status == 'online' ||
newPresence.status == 'dnd'
) {
gen.send('online');
member.roles.add('role.id');
} else if (newPresence.status === 'offline') {
gen.send('offline');
member.roles.remove('role.id');
}
}
}
});
You could get the other member by its ID. newPresence has a guild property that has a members property; by using its .fetch() method, you can get the member you want to assign the role to. Once you have this member, you can use .toles.add() again. Check the code below:
// use an async function so we don't have to deal with then() methods
client.on('presenceUpdate', async (oldPresence, newPresence) => {
// move all the variables to the top, it's just easier to maintain
const channelID = '81023493....0437';
const roleID = '85193451....5834';
const mainMemberID = '80412945....3019';
const secondaryMemberID = '82019504....8541';
const onlineStatuses = ['idle', 'online', 'dnd'];
const offlineStatus = 'offline';
const { member } = newPresence;
if (member.id !== mainMemberID || oldPresence.status === newPresence.status)
return;
try {
const channel = await client.channels.fetch(channelID);
if (!channel) return console.log('Channel not found');
// grab the other member
const secondaryMember = await newPresence.guild.members.fetch(secondaryMemberID);
if (onlineStatuses.includes(newPresence.status)) {
member.roles.add(roleID);
secondaryMember.roles.remove(roleID);
channel.send('online');
}
if (newPresence.status === offlineStatus) {
member.roles.remove(roleID);
secondaryMember.roles.add(roleID);
channel.send('offline');
}
} catch (error) {
console.log(error);
}
});

i want to make the command that makes changes in the roles work in dm's in javasript

I made a bot that verifies people with API and stores the data in mongoose but I want the code to work in discord DMS but I have no clue how to make it give roles in a specific server when the command is run in DMS this is my code:
const fetch = require('node-fetch')
const ignSchema = require('../schemas/ign-schema')
const mongo = require('../mongo')
module.exports = {
commands: ['verifyme'],
minArgs: 0,
maxArgs: null,
expectedArgs: "<minecraft name>",
callback: async(message, arguments, text) => {
const playerName = arguments.join(' ')
fetch(`https://api.hypixel.net/player?key=MYAPIKEY&name=${playerName}`)
.then(response => response.json())
.then(async data => {
player = data
const target = message.author
const author2 = message.author.tag
const uuid = data["player"]["uuid"]
const discordid = data["player"]["socialMedia"]["links"]["DISCORD"]
let verifyRole = message.guild.roles.cache.find(role => role.name === '[Verified]');
let memberTarget = message.guild.members.cache.get(target.id);
const guildId = message.guild.id
const userId = message.author.id
const UUID = uuid
const _id = UUID
if (discordid == author2) {
await mongo().then(async mongoose => {
try {
const results2 = await ignSchema.findOne({
_id,
})
const {
UUID,
userData,
discordName
} = results2
if (UUID == uuid) {
if (author2 == discordName) {
if (message.member.roles.cache.some(role => role.name === "[Verified]")) {
message.reply('you are already verified')
} else {
memberTarget.roles.add(verifyRole)
message.reply('welcome back')
}
} else {
message.reply(`you already used this minecraft account to verify ${discordName}, if you want to change this please contact <#390929478790152192>`)
mongoose.connection.close()
return
}
} else {}
} catch {
const userData = {
timestamp: new Date().getTime(),
}
await mongo().then(async(mongoose) => {
try {
await ignSchema.findOneAndUpdate({
_id
}, {
UUID,
discordName: author2,
HypixelName: playerName,
userId: userId,
guildId: guildId,
$push: {
userData: userData
},
}, {
upsert: true
})
memberTarget.roles.add(verifyRole)
message.reply('you are succesfully verified')
} finally {
mongoose.connection.close()
}
})
}
})
} else {
message.reply(`change your linked discord account in hypixel from ${discordid} to ${author2},`)
}
console.log(`${discordid}`)
})
},
}
and this is the error I get:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roles' of null
If there is more than one server the bot is in, this is not possible without making major assumptions as to the guild they are in.
If there is only one server, message.guild.roles can be changed to client.guilds.cache.get('your_servers_id').roles.

Cannot set permissions on newly created channel

I want to make my bot able to create private tickets. It can create the channel just fine, but when I try to set the permissions on that channel, it says that #everyone is the only role (therefore having default permissions). Also, the console doesn't report any error messages.
To clarify, I can't get the bot to apply permissions to a channel.
const client = new discord.Client();
const config = require("./config.json");
var userTickets = new Map();
client.login(config.token);
client.on("ready", () => {
console.log(client.user.username + "has logged in.")
});
client.on("message", message => {
if(message.author.bot) return;
if(message.content.toLowerCase() === "?crearticket" && message.channel.id === "729851516667691058") {
if(userTickets.has(message.author.id) || message.guild.channels.cache.some(channel =>
channel.name.toLowerCase() === message.author.username + "-ticket")) {
message.author.send("ยกYa tienes un ticket!");
}
else {
let guild = message.guild;
message.guild.channels.create(`${message.author.username}-ticket`, {
type: "text",
permissionsOverwrites: [
{
id: message.author.id,
allow: ["VIEW_CHANNEL"]
},
{
id: message.guild.id,
deny: ["VIEW_CHANNEL"] //This is the part I mentioned.
},
{
id: "729481759955222538",
allow: ["VIEW_CHANNEL"]
},
],
}).then(ch => {
console.log("Creado el canal" + ch.name)
userTickets.set(message.author.id, ch.id);
console.log(userTickets);
}).catch(err => console.log(err));
}
}
else if(message.content.toLowerCase() == "?closeticket"){
if(userTickets.has(message.author.id)) {
if(message.channel.id === userTickets.get(message.author.id)) {
message.channel.delete("Cerrando Ticket")
.then(channel => {
console.log("Eliminado el canal " + channel.name);
userTickets.delete(message.author.id);
})
.catch(err => console.log(err));
}
}
}
});
Change permissionsOverwrites to permissionOverwrites (you had an extra s).
Happy coding!

How to delete all user inputs except one command in specific channel?

I was working on a discord bot and for a verification channel. I want users to type only the /verify command: every message or command except /verify they type should get deleted automatically. How can I do this?
Current code:
if (command === "verify") {
if (message.channel.id !== "ChannelID") return;
let role = message.guild.roles.find(rol => rol.name === 'Member')
const reactmessage = await message.channel.send('React with ๐Ÿ‘Œ to verify yourself!');
await reactmessage.react('๐Ÿ‘Œ');
const filter = (reaction, user) => reaction.emoji.name === '๐Ÿ‘Œ' && !user.bot;
const collector = reactmessage.createReactionCollector(filter, {
time: 15000
});
collector.on('collect', async reaction => {
const user = reaction.users.last();
const guild = reaction.message.guild;
const member = guild.member(user) || await guild.fetchMember(user);
member.addRole(role);
message.channel.send(`Verification Complete.. ${member.displayName}. You have got access to server. `)
});
message.delete();
}
You can add a check at the top of your client.on('message') listener:
client.on('message', message => {
let verified = !!message.member.roles.find(role => role.name == 'Member');
// ... command parsing ect...
if (!verified && command == 'verify') {...}
else if (verified) {
// other commands...
}
});

Categories