I'm fairly new to using buttons and i'm trying to do an embed with pagination for my help menu. This below code works as I want it, but after interacting with each of the buttons each time it gives me a "This interaction failed" error under the button.
if message.content.lower().startswith('.help'):
embed = discord.Embed(title="test", description="test", color=0x33f6dc)
embed.set_author(name="test")
embed.add_field(name="test", value="!test", inline=True)
embed2 = discord.Embed(title="test2", description="test2", color=0x33f6dc)
embed2.set_author(name="test2")
embed2.add_field(name="test2", value="!test2", inline=True)
pages = 2
currentpage = 1
page1 = await message.channel.send(embed=embed, components=
[
Button(style=ButtonStyle.blue, label="▶️", custom_id="next"),
]
)
while True:
try:
interaction = await client.wait_for("button_click", check=lambda inter: inter.custom_id == "next", timeout=300)
if interaction and currentpage != pages:
await page1.edit(embed=embed2, components=
[
Button(style=ButtonStyle.blue, label="◀️", custom_id="back"),
])
currentpage += 1
interaction2 = await client.wait_for("button_click", check=lambda inter: inter.custom_id == "back")
if interaction2 and currentpage > 1:
await page1.edit(embed=embed, components=
[
Button(style=ButtonStyle.blue, label="▶️", custom_id="next"),
])
currentpage -= 1
except asyncio.TimeoutError:
await page1.delete()
break
Related
I have this code:
#rob
#client.command()
#commands.cooldown(1,10800,commands.BucketType.user)
async def rob(ctx,member:discord.User = None):
if member == None:
em = discord.Embed(title='ERROR:', description='Please specify a member you want to rob!', color=0xff0000)
await ctx.send(embed = em)
return
await open_account(ctx.author)
await open_account(member)
bal = await update_bank(member)
if bal[0]<50:
em = discord.Embed(title='ERROR:', description="The member you try to rob doesn't have that much money!", color=0xff0000)
await ctx.send(embed = em)
return
if amount<0:
em = discord.Embed(title='ERROR:', description="Amount must be positive!", color=0xff0000)
await ctx.send(embed = em)
return
earnings = random.randrange(0, bal[100])
fine = random.randrange(0, bal[100])
em1 = discord.Embed(title='Succesfully robbed!', description=f"You robbed {earnings} coins!", color=0x00ff00)
em2 = discord.Embed(title='Caught!', description=f"You got caught! You paid a {fine} coins fine! ", color=0x00ff00)
yesorno = random.randrange(0, 1)
if yesorno == 1:
await ctx.send(embed = em1)
await update_bank(ctx.author,earnings)
await update_bank(member,-1*earnings)
else:
await ctx.send(embed = em2)
await update_bank(ctx.author,-1*fine)
This function's goal is to rob someone and take their money or give them a fine, but it doesn't work. It doesn't send em1 or em2, I don't know how to fix it. I tried many things, but it doesn't give an error!
What fixed it for me was changing the yesorno function. Changed it to:
yesorno = random.randrange(0, 2)
if yesorno == 1:
await ctx.send(embed = em1)
await update_bank(ctx.author,1*earnings)
await update_bank(member,-1*earnings)
else:
await ctx.send(embed = em2)
await update_bank(ctx.author,-1*fine)
await update_bank(member,1*fine)
I try to send a Message in a Server. This Server ID is logged in MongoDB and the Channel ID too. But everytime i'll try it, it does not working. Here's my Code:
The Error is the return console.log Text
//This is the guildMemberUpdate file
const client = require("../index.js")
const {MessageEmbed} = require("discord.js")
const {RED, GREEN, BLUE} = require("../commands/jsons/colors.json")
const Schema = require("../models/StatusTracker.js")
client.on("guildMemberUpdate", async(member) => {
const data = await Schema.findOne({Guild: member.guild.id})
let channel = member.guild.channels.cache.get(data.Channel)
if(!channel) return console.log("Es wurde kein Channels gefunden");
if(member.user.presence.status === "offline") {
let offlineEmbed = new MessageEmbed()
.setColor(RED)
.setDescription(member.user.toString() + " ist jetzt offline!")
.setAuthor(member.user.tag, member.user.avatarURL({ dynamic: true }))
channel.send(offlineEmbed)
} else if(member.user.presence.status === "dnd" || member.user.presence.status === "online" || member.user.presence.status === "idle"){
let onlineEmbed = new MessageEmbed()
.setColor(GREEN)
.setDescription(member.user.toString() + " ist jetzt online!")
.setAuthor(member.user.tag, member.user.avatarURL({ dynamic: true }))
channel.send(onlineEmbed)
}
})```
//This is the MongoDB File
"Guild": "851487615358337065",
"Channel": "859444321975009290"
The problem is that you're using the guildMemberUpdate event, but that only tracks nickname and role changes. The one that you're looking for is presenceUpdate. That'll trigger when any user goes offline etc.
Check the docs for more details: here
Note: You'll probably need to enable 'Presence intent' in 'Privileged Gateway Intents' in your bot's settings page for this to work. (https://discord.com/developers/applications)
I have imported everything needed for the command.
So, the issue here is, in the condition for executing the command (checking if the user said yes/no or something weird which terminates the command)
#commands.command()
#commands.has_permissions(manage_channels=True)
async def nuke(self, ctx,*, channel = None, reason = None):
if reason is None:
reason = "No reason was specified!"
if channel is None:
channel = ctx.channel
p = time.strftime(f'Today at %H:%M %p')
embei = discord.Embed(color=0xa3a3ff, title = ":warning: ALERT ALERT ALERT :warning: ", description=f"{ctx.author.mention} Are you sure you want to delete {ctx.channel.mention}? y/n")
await ctx.send(embed=embei)
msg = await self.client.wait_for('message', check=lambda message:message.author == ctx.author and message.channel.id == ctx.channel.id)
if msg.content.lower in ("y", "yes"):
embedis = discord.Embed(color=0xa3a3ff, title=f"Channel ({ctx.channel.name}) has been nuked :boom:", description=f"Nuked by: {ctx.author.name}#{ctx.author.discriminator} \n **Reason:** {reason}")
embedis.set_image(url = "https://66.media.tumblr.com/23dad7011515a9c21647fefb07e1c0e0/dd0cbd9bb94e2a45-1e/s640x960/a02fc34abff6953c59adafc190de6e5276969175.gif")
embedis.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.channel.delete(reason=reason)
channel = await ctx.channel.clone()
await channel.send(embed=embedis)
elif msg.content.lower in ("n", "no"):
embegs = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = f"{ctx.channel.mention} was not nuked!")
embegs.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embegs)
else:
embers = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = "No proper response was given, action was terminated")
embers.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embers)
The part with the issue
msg = await self.client.wait_for('message', check=lambda message:message.author == ctx.author and message.channel.id == ctx.channel.id)
if msg.content.lower in ("y", "yes"):
embedis = discord.Embed(color=0xa3a3ff, title=f"Channel ({ctx.channel.name}) has been nuked :boom:", description=f"Nuked by: {ctx.author.name}#{ctx.author.discriminator} \n **Reason:** {reason}")
embedis.set_image(url = "https://66.media.tumblr.com/23dad7011515a9c21647fefb07e1c0e0/dd0cbd9bb94e2a45-1e/s640x960/a02fc34abff6953c59adafc190de6e5276969175.gif")
embedis.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.channel.delete(reason=reason)
channel = await ctx.channel.clone()
await channel.send(embed=embedis)
elif msg.content.lower in ("n", "no"):
embegs = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = f"{ctx.channel.mention} was not nuked!")
embegs.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embegs)
else:
embers = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = "No proper response was given, action was terminated")
embers.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embers)
when I execute the command, it does ask me for the confirmation as expected, however, the reply here doesn't matter as it always executes the else statement. I thought the issue was with indentation and so I tried fixing that but that too didn't work. Does anyone know about the issue here I might be facing?
Extra: Before Adding user confirmation, the code was working absolutely fine! (It created a clone of the channel, sent the embed there saying it nuked the original channel, and deleted the original channel)
For this question of mine, the string.lower() is a method which I need to call, which was mentioned to me by Lukasz. I was using the string.lower() in the wrong way.
To Fix the problem I had, I declared two lists a and b
a=["y", "yes"]
b = ["n", "no"]
and changed
if msg.content.lower in ("y", "yes"):
elif msg.content.lower in ("n", "no"):
to
if msg.content in a:
elif msg.content in b:
and the issue was fixed.
I have no idea what I’m doing. I don’t code but my friend helped me out up to this part
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('This Bot is online!');
client.user.setActivity('Prefix +k')
});
client.on('message', msg=>{
if(msg.content === "+k Hello"){
msg.reply('Welcome!');
}
})
client.on('message', msg=>{
if(msg.content === "+k Credits"){
msg.reply('Pokemon DB for Info, MrTechGuy for code help!');
}
})
client.on('message', msg=>{
if(msg.content === "+k Credits"){
msg.reply('Pokemon DB for Info, MrTechGuy for code help!');
}
})
client.on('message', msg=>{
if(msg.content === "+k DAList"){
msg.reply('1 - Butterfree <:V:750540886680666282> <:grass:750540661396340826>, 2 = Butterfree <:VMAX:750540886701637743> <:grass:750540661396340826>,');
}
})
client.login('[REDACTED]');
Again, how would I add a hug command that targets the user, e.g. +k hug #user 1, my friend is out for the month and I do not know how to do it
response: #user 2 hugged #user 1 ! (gif here)
For this to work you will need to create a folder named "hug" and with images which are "gif".
if(message.content.startsWith('+k hug')) {
let user = msg.mentions.users.first(); // refers to the user you wish to mention
if (!user) {
let maxImageNumber1 = 7; // represents the number of images in the folder
let hug = Math.floor(Math.random() * (maxImageNumber1 - 1 + 1)) + 1;
let imageName1 = `${hug}.gif` // if the images you put are png/jpg just remove the ".gif" with either ".png" or ".jpg"
let imagePath1 = `/hug/${imageName1}` // folder name
let file1 = new Discord.MessageAttachment(imagePath1);
let embed1 = new Discord.MessageEmbed();
embed1.setImage(`attachment://${imageName1}`)
embed1.setDescription(`**${msg.author.username}** hugged their clone`)
embed1.setColor('RANDOM')
msg.channel.send({ files: [file1], embed: embed1 });
}
if (user) {
let maxImageNumber1 = 7; // represents the number of images in the folder
let hug = Math.floor(Math.random() * (maxImageNumber1 - 1 + 1)) + 1;
let imageName1 = `${hug}.gif` // if the images you put are png/jpg just remove the ".gif" with either ".png" or ".jpg"
let imagePath1 = `/hug/${imageName1}` // folder name
let file1 = new Discord.MessageAttachment(imagePath1);
let embed1 = new Discord.MessageEmbed();
embed1.setImage(`attachment://${imageName1}`)
embed1.setDescription(`**${msg.author.username}** hugged **${user.username}**`)
embed1.setColor('RANDOM')
msg.channel.send({ files: [file1], embed: embed1 });
}
}
Im assuming you are using discord.js v12
TIP:
I'd recommend you define your prefix with something like const prefix = '+k'; and when you want to make a command do this: if(message.content.startsWith(prefix + 'hug')){}
I am trying to make a poll command which adds the correct amount of reactions such as A B C D E etc.
I have already tried this but it was a simple yes or no poll command.
elif message.content.startswith('m/qpoll'):
question = message[8:]
await message.delete()
message = await message.channel.send(f"**New poll:** {question}")
await message.add_reaction('❌')
await message.add_reaction('✔️')
What i am trying to achieve is a command which adds A B C reactions if there is three possible answers and A B C D E if there is five possible answers etc.
The command the user has to use is preferred to be in this format:
m/poll "question" "answer 1" "answer 2" "answer 3"
The command needs to be under a on_message statement as the command package does not work as well for my bot.
A simple way to do it, without using discord.ext.commands :
elif message.content.startswith('m/qpoll'):
content = message.content[8:]
items = content.split(" ")
question = items[0]
answers = '\n'.join(items[1:])
await message.delete()
message = await message.channel.send(f"**New poll:** {question}\n{answers}")
reactions = ['A', 'B', 'C', 'D', 'E'] #replace the letters with your reactions
for i in range(len(items[1:]))
await message.add_reaction(reactions[i])
Here's the poll command I made for my bot
#commands.command()
async def poll(self, ctx):
"""
Conduct a poll (interactive)
?poll
"""
member = ctx.author
member: Member
maker = []
await ctx.send("```What is the Question ❓```")
em = ["🧪", "🧬", "🚀", "🖌️", "🧨"]
def mcheck(m):
return m.author == member
try:
msg = await self.bot.wait_for('message', timeout=20.0, check=mcheck)
maker.append(msg.content)
except TimeoutError:
return await ctx.send("```Poll timed out ⏳```")
await ctx.send("```How many options do you want?```")
try:
msg = await self.bot.wait_for('message', timeout=20.0, check=mcheck)
except TimeoutError:
return await ctx.send("```Poll timed out ⏳```")
i = int(msg.content)
if i > 5:
return await ctx.send("```A maximum of 5 options for polls```")
await ctx.send("```Enter your options ✔```")
for i in range(i):
try:
await ctx.send(f"```{i + 1}) ```")
msg = await self.bot.wait_for('message', timeout=20.0, check=mcheck)
maker.append(msg.content)
await msg.add_reaction("✅")
except TimeoutError:
return await ctx.send("```Poll timed out ⏳```")
poller = Embed(color=0x5EE34)
poller.title = maker[0]
des = ''
for j in range(1, len(maker)):
des += f"```{em[j - 1]} {maker[j]}```\n"
poller.description = des
pr = await ctx.send(embed=poller)
for j in range(i + 1):
await pr.add_reaction(em[j])
def reac_check(r, u):
return pr.id == r.message.id and r.emoji in em
eopt = {e: 0 for e in em}
while True:
try:
reaction, user = await self.bot.wait_for('reaction_add', timeout=20.0, check=reac_check)
e = str(reaction.emoji)
except TimeoutError:
await ctx.send("```Poll Finished ✅```")
break
if e in eopt.keys() and user != self.bot.user:
eopt[e] += 1
eopt = {k: v for k, v in sorted(eopt.items(), key=lambda item: item[1], reverse=True)}
most = next(iter(eopt))
loc = em.index(most)
poller.title = "Results 🏆"
poller.description = f"```Folks chose 📜\n{maker[loc + 1]}```"
return await ctx.send(embed=poller)
As a rule of thumb avoid using on_message to create commands. You can read about commands.Bot() in the docs.
That said you should be able adapt the above example to suit your needs.