Discord.py Reaction Events - discord

My bot sends an embed every time a new member joins. Then the bot adds the little 👋🏽 reaction to it. I want members to be able to welcome the new member by reacting. If they react, then they will be rewarded in some way. So onto my question, how would I make my bot watch for reactions for 60 seconds after the embed is sent, and what event would I use? I've found a few things in the documentation but none of which seem to make sense to me. A code example and explanation of how it works would be amazing. Thanks in advance!

In order to do this, you'd need to make use of the on_reaction_add event, assuming you already have all your imports:
#bot.event
async def on_member_join(member): # when a member joins
channel = discord.utils.get(member.guild.channels, name="welcome") #getting the welcome channel
embed = discord.Embed(title=f"Welcome {member.mention}!", color=member.color) #creating our embed
msgg1 = await channel.send(embed=embed) # sending our embed
await msgg1.add_reaction("👋🏽") # adding a reaction
#bot.event
async def on_reaction_add(reaction, user):
message = reaction.message # our embed
channel = discord.utils.get(message.guild.channels, name="welcome") #our channel
if message.channel.id == channel.id: # checking if it's the same channel
if message.author == bot.user: #checking if it's sent by the bot
if reaction.emoji.name == "👋🏽": #checking the emoji
# enter code here, user is person that reacted
I think this would work. I might have done the indentations wrong since I'm on another device. Let me know if there are any errors.

You can use the on_reaction_add() event for that. The 60 second feature might be complicated.
If you can get the user object from the joined user the on_reaction_add() event, you could check if the user joined less than 60 seconds ago.
You can check the time a user joined with user.joined_at, and then subtract this from the current time.
Here is how to check how many seconds a user is already on the server.
from datetime import datetime
seconds_on_server = (datetime.now() - member.joined_at).total_seconds()

A rather hacky solution is to retrieve the original user who joined through the message on which the reaction is added. Members have the joined_at attribute, which is a datetime object, with it you can just snap current datetime and subtract the former from it. The resulting is a timedelta object which you can use to calculate the time difference.

Related

Discord Autocode reaction reply bot (not reaction role bot)

I have been using autocode.com to create some Discord bots. I have very little programming experience and found autocode to be quite easy. However, I've tried asking a question on autocode's discord that no one seems to understand or is asking.
I am trying to create a bot that replies to reactions--but does not assign roles, but instead, provides a reply--either in thread or a DM to that user who uses that specific emoji reaction.
For example, this is what I am looking to do: if there is a bot message in #channelx, userX will react to that message with a pepperoni emoji and then a pizza bot will reply back with a message either in thread or DM such as, "Hi #userx, your pizza topping has been recorded and will be ready for pickup in 15 minutes, please visit this link.com to track your order".
Autocode has a bot that can react to reactions and assign roles but I can't seem to reverse engineer it give a reply, rather than assign roles.
I appreciate any assistance. Thanks!
What does autocode use? Python or node.js? If python, you can do something like this:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('message'):
await message.channel.send('hi')
If node.js, you can do something like this:
client.on('messageCreate', msg => {
if (msg.content === 'specific message') {
msg.reply(`response text`);
}
});
I was previously a Community Hero at the Autocode Discord server. Try finding another app through this, and if none are available, the thing to do would be looking through the API's. Here's one for messaging in general, here's one for responding, and here's one for dm-ing.
Let's say, for example, I'd be making it reply to a reaction through DM:
The first thing you do is make sure the event trigger is set to message.reaction.add. This is so that the code you will write is triggered whenever a reaction is added.
Make either a switch or if statement to change what happens depending on what reaction triggers the code. In this example, I'll just use an if statement for easy explanation.
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
if (context.params.event.emoji.id == '1234567890') {
await lib.discord.users['#0.2.1'].dms.create({
recipient_id: `${context.params.event.member.user.id}`,
content: `Hi <#${context.params.event.member.user.id}>, your pizza topping has been recorded and will be ready for pickup in 15 minutes, please visit this link.com to track your order`
});
}
What this does is check if the thing that triggered this event has the emoji id equaling '1234567890': If it does, then it follows into that if statement, and if it does not, it skips over it.
In the future, please stay patient in the Autocode Discord server; The ones who are helping are also community members, similar to here. You may always ask the same question every now and then.

Discord.py doesn't update on member remove

I am making a discord bot that changes a voice channels' name when a user joins or leaves to the amount of members on the server. My issue is that when a user leaves, it doesn't update. Any help is appreciated.
#bot.event
async def on_raw_member_remove(member):
channel = discord.utils.get(member.guild.channels, id=973603264639668248)
await channel.edit(name=f'Member Count: {member.guild.member_count}')
The right event for this would be on_member_remove.
You can also get the channel in a much easier way and edit it.
See a possible new code:
#bot.event
async def on_member_remove(member: discord.Member):
channel = bot.get_channel(Channel_ID_here)
await channel.edit(name=f"Member Count: {len(member.guild.members)}")
The reason it doesn't work is because you are using on_raw_member_remove
You should be using on_member_leave as the member is not getting removed.

Avoid rate limit for changing voice channel name discord js 13

I'm trying to create a slash command using discord.js v13 to change the names of voice channels. I am using this code to do this :
module.exports = {
data: new SlashCommandBuilder()
.setName('name')
.setDescription('Set name for your voice channel')
.addStringOption(option => option.setName('name').setDescription('Enter your name').setRequired(true)),
async execute(interaction) {
const name = interaction.options.getString('name');
if (!interaction.member.voice.channel) await interaction.reply('Error not in a voice channel!');
else {
await interaction.member.voice.channel.setName(name);
await interaction.reply('Done!');
}
},
};
This code is fine and makes the job done. But as you know I can change the voice channel's name only 2 times per 10 minutes because of the limit rate. So if a user tries to change the voice channel's name for the third time, I won't get any error on the console, and discord js will queue this request for later and will do it after 10 minutes. But the user gets this error on discord: This interaction failed.
I want to check if there was a rate limit for my request, and if is, don't send the request and just reply to the user. Is this possible?
There is no inherent functionality that is able to handle the situation in the way you want it to, but the problem is soluble using regular old JavaScript. For example, you could use an integer to indicate how many times the command has been used and use setTimeout() to decrement it 10 minutes after the command was called. That way you can check if the int is equal to 2 in which case you skip the .setName().
There are undoubtedly other ways to implement the same or similar behavior, but, to answer your question, unfortunately the discordjs/voice library does not provide any simple way to do it.

How to your Discord account creation and add it to an embed?

I am wondering how to your Discord account creation. I would also like to know how to put it in a embed. Yes I do know how to make an embed, but how to insert it.
By Discord account creation, I will assume you are referring the User#createdAt property - which returns a Date object containing when the user account was created.
Note 1. You can convert a Date object to a pretty time string by calling Date.toUTCString(), or similar methods (see here)
Adding it to an embed seems pretty straightforward to me.
By then, your code should look like:
const user = getSomeUserHere() //for example, you can do message.author to get the User object of the message's author
const createdDate = user.createdAt
const embed = new Discord.MessageEmbed()
.setTitle("This user was created at")
.setDescription(`${createdDate.toUTCString()}`);
message.channel.send(embed) //or however you plan to send this embed

Is there a way to pm an author and use the wait_for command to capture the value they type in?

I'm writing a discord bot using python to log options trade. What I'm looking to do with my bot is when a user type execute a command, !opentrade, the bot would private message the user with a series of questions. The bot would then capture the answer in a series of variables and use that to process the answer. Is this possible or does it have to be in the channel where the command is called. Additionally, is it by default multithread, meaning 2 or 3 people can call that command at the same time and it would fud up the answer
I have the following thus far and it isn't working:
async def opentrade(ctx):
def check(author):
def inner_check(message):
if message.author != author:
return False
try:
int(message.content)
return True
except ValueError:
return False
return inner_check
try:
await ctx.author.send('Enter the underlying: ')
underlying = await client.wait_for('message', check=check(ctx.author), timeout=30)
print (underlying)
except Exception as err:
await ctx.channel.send("Something went wrong: {}".format(err))
thanks
What I'm looking to do with my bot is when a user type execute a command, !opentrade, the bot would private message the user with a series of questions. The bot would then capture the answer in a series of variables and use that to process the answer. Is this possible or does it have to be in the channel where the command is called.
Possible. You need to put the whole logic into the coroutine that executes the command.
Additionally, is it by default multithread, meaning 2 or 3 people can call that command at the same time and it would fud up the answer
If you implement the checks properly it won't fud the answer. In your code you already implemented the logic that checks for the author so noone else can change it def check(author).
When executing the commands multiple times by different users it will also not fud the answer since the threads are independent.
You should extend this check so it checks for a message in a DM channel. The way your check is written now the caller can DM the bot or respond in a guild text channel.
I'm not sure what's saved in the ctx variable but I'm certain it has a message attribute.
Try await ctx.message.author.send(). If you are running into an error provide the error log.

Resources