How to prevent discord bot to send message automatically? - discord

My discord bot is sending a message automatically everyday at 4am . I don't know why . Here is the code :
let embed = new Discord.MessageEmbed()
.setTitle("Hello")
.setColor(0x36393f)
.setDescription(
`\`\`\`${table(membersLimited, {
border: getBorderCharacters(`void`),
})}\`\`\``
)
.setTimestamp();
guild.channels.cache
.get(guildData.config.channels.announcements)
.send(embed);
I can't figure out why my bot send this message every day automatically to ALL the server where it is invited in.
Any idea ?

This thread is useful, after you define the cronjon, simply do <cron name>.stop();
var cron = require('cron').CronJob;
var j = cron.scheduleJob(unique_name, '*/1 * * * * *',()=>{
//Do some work
});
// for some condition in some code
let my_job = cron.scheduledJobs[unique_name];
my_job.stop();

Related

How can I change the permissions of a specific role of a channel in discord.py

I'm trying to make a command that takes a channel name as input (or argument) and locks that channel but for only the students in the channel. Here's the code:
# bot.GUILD = bot.get_channel(guild_id) [In on_ready method in bot class]
#bot.command()
async def lock(ctx, channel_name):
user_dm = await bot.create_dm(ctx.author)
channels = await bot.GUILD.fetch_channels()
roles = await bot.GUILD.fetch_roles()
channels = list(filter(lambda c: c.name.lower() == channel_name.lower(), channels))
student_roles = list(filter(lambda r: r.name.endswith("students"), roles))
# print(channels, roles) [This works fine]
if channels:
for channel in channels:
for role in student_roles:
await channel.set_permissions(role, send_messages=False)
await user_dm.send(f"✅ {channel_name} has been locked!")
else:
await user_dm.send(f"❌ {channel_name} does not exist!")
I don't know why it's not sending any message to my dm. Because it's an if-else statement so at least I get a message from the bot whether positive or negative but that doesn't happen. And yes my bot has the necessary permissions. I really hope you can help me with this 😕🥺

How to index into the channel.members list and take out the name? Closed

So I'm trying to get the names of all the people in a voice channel, but the bot returns a list like so:
[<Member id=704069756717629472 name='Eedward' discriminator='8402' bot=False nick=None guild=<Guild id=807690875802878003 name='lfg testing' shard_id=None chunked=True member_count=3>>]
Is there any way I can take that "name" part out of the list? Or is there a better way to do something like this? This is my code:
#client.command()
async def lfg(ctx, game, *,extra=None):
if not ctx.message.author.voice:
await ctx.send(f"{ctx.author.name}, you need to connect to a voice channel first to use this command.")
return
else:
channel = ctx.message.author.voice.channel
link = await channel.create_invite(max_age = 300)
members = len(ctx.message.author.voice.channel.members)
members1 = ctx.message.author.voice.channel.members
max_ = channel.user_limit
if max_ == 0:
max_ = 'None'
if max_ == 'None':
p = f'{members}, No Limit'
else:
p = f"{members} out of {max_}"
em = Embed(color=discord.Color.gold())
em.add_field(name='LFG Request', value=f"**{ctx.author.mention} is looking for a group in voice channel `#{channel}`**:\n\n**Game: {game}**\n\n**Extra Info:** {extra}\n\n**Connected Users:**{(members1)} ({p})\n\n**VC Invite: [Click here to join]({link})**")
em.set_footer(text=f'Type !lfg (message) to create this embed | This LFG request was made by {ctx.author.name}')
await ctx.send(embed=em)
Sorry if it's a bit hard to read, thanks in advance! :D (Btw I'm trying to display the names of the users in the vc in the "Connected Users" section of the embed)
Edit: I figured it out, for those who want the code, here it is:
members = len(ctx.message.author.voice.channel.members)
count = 0
members1 = ""
for _ in range(int(members)):
members1 += f"{ctx.message.author.voice.channel.members[count].mention}"
count += 1
try adding .name to the member. This should get the name from the member.

how to trigger a command from another file

I am trying to create a music bot, but i have an issue with the loop command, I want to trigger loop.js when the user clicks on a certain react emoji on the playing menu, for now, the command runs independently in both play.js and loop.js. The reason I want to do this is because in case a user selects the reaction and then does the command itself, the bot would say the opposite if it was either on or off.
Here is my loop.js
module.exports = {
name: "loop",
aliases: ['l'],
description: "Toggle music loop",
execute(message) {
const queue = message.client.queue.get(message.guild.id);
if (!queue) return message.reply("There is nothing playing.").catch(console.error);
if (!canModifyQueue(message.member)) return;
let loopembed = new MessageEmbed()
.setTitle("Loop settings")
.setDescription(`Loop is now ${queue.loop ? "**on**" : "**off**"}`)
.setColor(message.guild.me.displayColor)
.setFooter(`Action performed by ${message.author.tag}`)
// toggle from false to true and reverse
queue.loop = !queue.loop;
return queue.textChannel
.send(loopembed)
.catch(console.error);
}
};
And here is my loop reaction command from play.js
case "🔁":
reaction.users.remove(user).catch(console.error);
if (!canModifyQueue(member)) return;
queue.loop = !queue.loop;
queue.textChannel.send(`Loop is now ${queue.loop ? "**on**" : "**off**"}`).catch(console.error);
break;
I'm trying to make loop.js run instead of it being run independently in case of the reacted emoji.
Thank you for helping in advance

How to create a "TempMute" command?

How to create a TempMute command for discord.js which supports the command handler from An Idiot's Guide.
I understand you need to use .addRole(), but I have no idea how to create it with a timer. The range of the timer needs to be from 60 to 15 minutes.
If you want an action to be executed after some time, you need to use setTimeout(). Here's an example:
// If the command is like: -tempMute <mention> <minutes> [reason]
exports.run = (client, message, [mention, minutes, ...reason]) => {
// You need to parse those arguments, I'll leave that to you.
// This is the role you want to assign to the user
let mutedRole = message.guild.roles.cache.find(role => role.name == "Your role's name");
// This is the member you want to mute
let member = message.mentions.members.first();
// Mute the user
member.roles.add(mutedRole, `Muted by ${message.author.tag} for ${minutes} minutes. Reason: ${reason}`);
// Unmute them after x minutes
setTimeout(() => {
member.roles.remove(mutedRole, `Temporary mute expired.`);
}, minutes * 60000); // time in ms
};
This is just a pseudo-code, you'll need to parse the arguments and get the role.

Channel API closes a channel

First off, thank you #Moishe for the very useful API. I'm having a little timeout problem, maybe someone knows the answer. Here's how I open the channel:
var openChannel = function () {
var channel = new goog.appengine.Channel($('#token').val());
var socket = channel.open();
socket.onopen = function () {};
socket.onmessage = function (m) {
var message = JSON.parse(m.data);
// do stuff
};
socket.onerror = function (error) { alert(error); };
socket.onclose = openChannel;
};
openChannel();
This works fine, I post my messages and they go to the other clients pretty quickly. But if I stay on the page for roughly 15 minutes, the server loses track of my channel. In dev, it throws an error (which I saw was a known bug: http://www.mail-archive.com/google-appengine#googlegroups.com/msg44609.html). But in prod, it still ignores messages on that channel after about 15 minutes.
We fixed it by adding a setInterval(getSomeUrl, everyMinute) to the page, but we'd rather not have to do that. I noticed in Moishe's last commit for the trivia game sample that he took out a keep-alive. I didn't understand how he replaced it, and what he meant by onopen is reliable:
http://code.google.com/p/trivia-quiz/source/browse/trunk/src/index.html
Update: Server side code is
class Home(BaseHandler):
def get(self):
self.checkUser()
if self.user:
userId = self.user.user_id()
token = channel.create_channel(userId)
chatClients[userId] = token
self.model['token'] = token
players = self.checkChatRoom()
self.model['users'] = players
self.model['messages'] = map(lambda k:db.get(k), self.chat_room.messages) # TODO: Replace this line and the next with a query
self.model['messages'] = sorted(self.model['messages'], key=lambda m: m.timestamp, reverse=True)
self.writeTemplate('index.html')
BaseHandler is just a base class I use for all my GAE handlers, it provides checkUser which redirects if the user isn't logged in, and it provides writeTemplate which takes what's in self.model and writes it in a template. It's just a proof of concept, so no cache or anything else other than what's above.

Resources