welcome message code for multiple servers - discord.py

I recently started to learn discord.py and I wanted to add a welcome message for multi-channels and I found this post Discord.py welcome message for multiple servers I tried the code and seems to be working without any errors but I'm facing a problem creating a welcome message with this code because I don't have experience with discord.py I will have the code listed below and at the very bottom I will have the welcome code I tried if somebody can help it would be great
Thank you
#client.event
async def on_guild_join(guild):
#loads json file to dictionary
with open("welcome-message.json", "r") as f:
guildInfo = json.load(f)
guildInfo[guild.id] = guild.text_channels[0] #sets key to guilds id and value to top textchannel
#writes dictionary to json file
with open("welcome-message.json", "w") as f:
json.dump(guildInfo, f)
#allows server members to set channel for welcome messages to send to
#client.command()
async def welcomeMessage(ctx):
with open("welcome-message.json", "r") as f:
guildInfo = json.load(f)
guildInfo[ctx.message.guild.id] = ctx.message.channel.id #sets channel to send message to as the channel the command was sent to
with open("welcome-message.json", "w") as f:
json.dump(guildInfo, f)
# welcome code
#client.event
async def on_member_join(ctx, message):
with open("welcome-message.json", "r")as f:
guildInfo = json.load(f)
channel = guildInfo[ctx.message.guild.id]
embed = discord.Embed(title="Welcome ""!",
description=f"We're so glad you're here !", color=discord.Color.green())
await channel.send(embed=embed) ```

You have to specify the member intent to receive on_member_join events. You can do this while creating your bot object by adding an intent option:
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents=intents, other_options)
Note
If your bot is verified you require the SERVER MEMBERS INTENT which you can request on the bot page of your application.
Also:
On this line here:
embed = discord.Embed(title="Welcome ""!", it will error out as there are quotes in a quoted string, if you want to keep those quotes switch the quotes to single quotes (')

Related

How do you send a private message on_ready aka on a #client.event. Discord.py

I had multiple attempts.
# One of the attempts
ch = client.get_user(USERID)
await ch.send("IDK")
#Another
client = discord.Client()
#client.event
async def on_ready():
user = "#name"
user = discord.Member
await user.send(user, "here")
#Another
client = discord.Client()
#client.event
async def on_ready():
user = discord.utils.get(client.get_all_members(), id='USERID')
if user is not None:
await client.send(user, "A message for you")
else:
await client.send(user, "A message for you")
#Another
#client.event
async def on_ready():
ch = client.get_all_members()
await ch.send("Hello")
# Another
ch = client.start_private_message(USERID)
await ch.send("IDK")
As you can see I messed with the variables because I noticed that you can send a message by channel like this
channel = client.get_channel(CHANNELID)
await channel.send("Something)
But that doesn't work with get_user. Thanks in advance also sorry how bad my post/code is.
Allow me to inform you on what is wrong with the pieces of code you have provided.
await client.send(user, "A message for you") is older syntax, and has not been used since the v1.0 migration.
client.get_all_members() shouldn't be used in this case, as you are only getting all the members the bot shares a server with rather than a single user.
client.start_private_message(USERID) does not exist as far as I have read, and therefore we can assume that this wouldn't work.
My recommendation would be to use one of the two methods I will detail.
The first method would be to use client.fetch_user(), which sends a request to the Discord API instead of its internal cache (as the second method will). The only problem you will face with this method is if you retrieve too many users in a small amount of time, which will get you ratelimited. Other than that, I recommend this method.
The second method is to get a server through client.get_guild() and getting your user through there via guild.get_member(). This method will require the user to be in its cache, however, so this shouldn't be your go-to method in my opinion.
Do view both of these methods in the code below.
#client.event
async def on_ready():
# Method 1: Using fetch
user = await client.fetch_user(USER_ID)
await user.send("A message!")
# Method 2: Using 'get'
guild = client.get_guild(GUILD_ID)
user = guild.get_member(USER_ID)
await user.send("A message!")
Other Links:
Send DM to specific User ID - Stackoverflow
DM a specific user - Stackoverflow
Sending DM through python console (Fetch user) - Stackoverflow
DPY v1.0 Migration - Discord.py Documentation

How to auto update channel name using Discord.py

I am trying to understand how to automatically update a specific voice channels name in Discord. Looking through the API and around the site, I have found this:
#client.command()
async def emoivb(ctx, channel: discord.VoiceChannel, new_name):
await channel.edit(name=new_name)
However, I need it not as a command.
Example: Each time a person sends a specific message, the channel will increment its integer name by +1
Create a json file to store the number of messages with name message and use the following code
#client.listen()
async def on_message(message):
channel_id="channel which is to be edited"
channel=await client.fetch_channel(channel_id)
with open('message.json',"r") as f:
messages=json.load(f)
try:
x=messages[str(message.guild.id)]
x=x+1
messages[str(message.guild.id)]=x
with open('message.json',"w") as f:
json.dump(messages,f,indent=4)
await channel.edit(name=str(x))
except:
messages[str(message.guild.id)]=1
with open('message.json',"w") as f:
json.dump(messages,f,indent=4)
await channel.edit(name=str(1))

Discord bot repeating the command but not an event in discord.py

I want to ask something.I got stuck on something.I wanted to add some new features to my bot such as swear words so that making cleaner server.I finished my code and tried to give command which is !dc greetings(!dc is my command_prefix btw).My bot sent 'Hi everyone' message for 7 times.That 7 times is same number as the number of swear words in "Badwords.txt".By looking these,that repeating issue is related to this file handling codes(or not idk).Interesting thins is when I write swear word into server's chatbox,bot send only one "Please do not use this word ever" message.So How can i prevent bot not to repeat for many times?Thank you
import discord
from discord.ext import commands
intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True,presences=True)
client = commands.Bot(command_prefix="!dc ", intents=intents)
#Below command gets repeated 7 times everytime.That number is same as the number of swear words in "Badwords.txt"
#client.command(aliases=["sayHi"])
async def greetings(ctx):
await ctx.send('Hi everyone')
#My purpose in the below codes is countering profanity
with open("Badwords.txt", "r", encoding="utf-8") as f:
word = f.read()
badwords = word.split(",")
#In the below event,bot sends message only 1 time for 1 message
#client.event
async def on_message(message):
msg = message.content
for x in badwords:
if x in msg:
await message.delete()
await message.channel.send("Please do not use this word ever")
else:
await client.process_commands(message)
client.run(Token)
I would take the await client.process_commands(message) out of the else statement. I have also moved the with open inside the on message event so everything a message is sent, it will open the file to check if the message contained a bad word.
import discord
from discord.ext import commands
intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True,presences=True)
client = commands.Bot(command_prefix="!dc ", intents=intents)
#client.command(aliases=["sayHi"])
async def greetings(ctx):
await ctx.send('Hi everyone')
#client.event
async def on_message(message):
msg = message.content
with open("Badwords.txt", "r", encoding="utf-8") as f:
word = f.read()
badwords = word.split(",")
for x in badwords:
if x in msg:
await message.delete()
await message.channel.send("Please do not use this word ever")
else:
return
await client.process_commands(message)
client.run(Token)
await client.process_commands(message) was taken out of the else statement because, with your current code, the bot would only process the commands if the message did NOT contain a bad word. But we need it to process the commands every time a message is sent.

How to welcome new members in a specific "welcome" text channel discord.py?

I want to make a command for my bot in which we can configure the welcome message the bot can send. So, the configuration works like so: nb welcome <#channel_where_welcome_msg_to_be_shown> <#channel_to_be_mentioned_in_the_welcome_msg>.
The expected output being an embed where it is written
Hello <member>! Pls go to <#channel_to_be_mentioned_in_the_welcome_msg> to choose your roles.
Here is my code:
#client.command(aliases = ["welcome"])
async def _welcome(ctx, channel : discord.TextChannel, roles : discord.TextChannel = None):
global channel_welcome
global role_welcome
channel_welcome = channel
if roles != None:
role_welcome = roles
else:
role_welcome = None
await ctx.send("Ok, welcome message configured!")
#client.event
async def on_member_join(member):
global channel_welcome
global role_welcome
pfp = member.avatar_url
if role_welcome == None:
embedVar = discord.Embed(title="WELCOME!",description = "{}, you are welcome to this server!" . format(member.mention), color = 0xff9900)
embedVar.set_thumbnail(url = pfp)
await client.getchannel(channel_welcome).send(embed = embedVar)
else:
embedVar = discord.Embed(title="WELCOME!",description = "{}, you are welcome to this server! Go to {} to assign yourself some roles." . format(member.mention, role_welcome.mention), color = 0xff9900)
embedVar.set_thumbnail(url = pfp)
await client.getchannel(channel_welcome).send(embed = embedVar)
So, the welcome command is the configuration command. As you can see, the roles argument is optional and the user can use it if he/she wants.
Whenever I run the code and someone joins the server, it doesn't send the message or raises any error.
Any suggestions of how to fix this?
The reason why the bot does not react when a user joins, is probably because you did not define the appropriate intents for the bot.
First of all, you need to go to the Discord Developer Portal and enable the Server Members Intent
Now in the code, you need to define the intents
import discord
from discord.ext import commands
intents = discord.Intents().default()
intents.members = True
client = commands.Bot(prefix = "your_prefix", intents = intents)
This will allow the bot to listen to the on_member_join events.

How do I set a in Discord.py a command without Prefix only with certain word to which bot replies and also bot replies to thaat only in dm with bot

Discord.py, how to set a command, without Prefix, only with certain word to which bot replies, and also bot replies to that command while Dm with the bot.
Remember about the errors for example, bot object has no attribute on_message, etc, errors.
You can write a function to pass to command_prefix that will check for one prefix in servers and another (or none) in private messages:
from discord.ext import commands
def command_prefix(bot, message):
if message.guild is None:
return ''
else:
return '$'
bot = commands.Bot(command_prefix=command_prefix)
#bot.command(name='hello')
async def hello(ctx):
await ctx.send("Hello")
bot.run("TOKEN")
If you are using this in a cog.
#commands.Cog.listener()
async def on_message(self,message):
await message.send("Hello!")
or in the main.py
#bot.event
async def on_message(message):
await message.send("Hello!")
Please reply back if you have an error with this.
message.guild will return None if the message is in dms.

Resources