discord.py new invite link - python

i'm trying to make it so when ever you do the invite command it will make a brand new invite to the server with unlimited uses and never expires, this is the current code i've made but doesn't work and i'm struggling to work-out why, I've looked online and found nothing I hope you guys can all help :)
#bot.command(pass_context=True)
async def invite(ctx):
invitelinknew = await bot.create_invite(destination = ctx.message.channel, xkcd = True, max_uses = 100)
embed=discord.Embed(title="Discord Invite Link", description=invitelinknew, color=0xf41af4)
embed.set_footer(text="Discord server invited link.")
await bot.say(embed=embed)

I am assuming you want the bot to send the invite link directly to the chat because of the line: await bot.say(embed=embed).
First of all, I'm not sure setting the variable to embed is a good idea because this name might already be in use (not 100% sure though).
I believe that the issue with your code is the last line where the bot sends the message. Since there is no traceback, this is hard to tell for sure but I think replacing it with: await bot.send_message(ctx.message.channel, embed=embed) should fix your problem.
I would change the code to something like this instead:
#bot.command(pass_context=True)
async def invite(ctx):
invitelinknew = await bot.create_invite(destination = ctx.message.channel, xkcd = True, max_uses = 100)
embedMsg=discord.Embed(color=0xf41af4)
embedMsg.add_field(name="Discord Invite Link", value=invitelinknew)
embedMsg.set_footer(text="Discord server invited link.")
await bot.send_message(ctx.message.channel, embed=embedMsg)
Feel free to comment if this doesn't solve your problem.

Related

Welcome message not being sent in discord.py

So I made a new server and made a custom bot for it recently, but the welcome message doesn't really seem to work... It is also supposed to give a particular role to the member who joined but I removed that code and the current code still doesn't work.
Sadly, the command prompt gives no errors. I have no idea what to do now.
Here is the code -
#commands.Cog.listener()
async def on_member_join(self, member):
#GETTING THE GUILD, CHANNEL AND ROLE
channel = self.client.get_channel(828481599057166356)
name = member.name
#CREATING THE WELCOME EMBED
welcomeem = discord.Embed(title = f"Hey there {member.name}!", description = f"Welcome to {chanenl.guild.name}! Have a fun time here in TigerNinja's server!")
welcomeem.add_field(name="1. Rules", value = f"{name}, before you start having fun here, make sure to check <#752474442650878002> and read all rules as they will come in handy in the server!", inline=False)
welcomeem.add_field(name="2. Self-roles", value = f"{name}, be sure to check out <#776293478594379797> and get all roles you want!", inline=False)
welcomeem.add_field(name="2. Help", value = f"{name}, need help with this bot then type `t.help`. If you need help relating to something else, contact the mods via dms, but don't ping them!!", inline=False)
#SENDING THE PING, EMBDE AND ADDING ROLE
await channel.send(f"Welcome, {member.mention}!")
await channel.send(embed=welcomeem)
(I am using cogs btw)
Did you set up this command as bot event? Before adding such command you should add
#bot.event (or whatever name you gave to discord.Client in your code + .event, it might be useful to share more of your code, just be careful not to include your token or any private information).
For more info, look into this post, I believe it is the answer you are looking for:
Discord.py on_member_join not working, no error message
Following the dicord.py docs:
channel = guild.get_channel(828481599057166356)
should be:
channel = client.get_channel(828481599057166356)
EDIT:
I found something else:
welcomeem = discord.Embed(title = f"Hey there {member.name}!", description = f"Welcome to {chanenl.guild.name}! Have a fun time here in TigerNinja's server!")
you misspelled "channel" in {chanenl.guild.name}

Trying to make discord.py bot say something when its gets mentioned, doesnt respond

When someone mentions the bot, I want it to respond saying, "Hey! I've been mentioned. My prefix is >. You can type >help to see my commands." I have the code written out but the bot does not respond at all when it gets mentioned. I do not get any errors when I run it or mention the bot. How do I get this to work? My code is below. Thanks in advance.
#bot.event
async def on_message(message):
if message.author.id == bot.user.id:
return
msg_content = message.content.lower()
mention = ['#830599839623675925', '#Ultimate Bot']
if any(word in msg_content for word in mention):
await message.channel.send("Hey! I've been mentioned. My prefix is `>`. You can type `>help` to see my commands.")
else:
await bot.process_commands(message)
You can use the mentioned_in() method.
So in this case it would be;
#bot.event
async def on_message(message):
if message.author.id == bot.user.id: return
if bot.user.mentioned_in(message):
await message.channel.send("Hey! I've been mentioned.")
await bot.process_commands(message)
Some things to note:
Hard-coding in values such as in your mention variable is bad practice. It makes it much harder to maintain your code, and when your project gets bigger you may question what the purpose of these seemingly random strings are referring to. For example, if you were to change the name of the bot, or to transfer your code to a new bot, going through your entire codebase and picking out and changing these values would be far from ideal.
I don't know about the rest of your application, but you probably don't want process_commands() to be in the else statement. For example, if the user mentions the bot in their message, but are using a command, the command will be blocked because you are not triggering process_commands().
Hope this answers your question
You could instead just check if bot.user is in the message mentions.
You can also check if the bot display name was used.
if bot.user in message.mentions or (message.guild and message.guild.me in message.mentions):
print("bot was mentioned")
elif message.guild and message.guild.me.display_name in message.content:
print("bot name was used")

How to program a discord.py bot to dm me when a command is used by another person?

I want to create a command that people can use to send suggestions to me. They'd use the command "!suggest", followed by their input, and the bot privately dms that whole message to me. However I am struggling with making the bot dm me instead of the author of the command.
if message.content.startswith('!suggest'):
await message.author.send(message.content)
The problem here lies with the author part in the code- instead of dming me every time, it will dm the person who typed the command, which is useless to me. How can I replace 'author' with my discord ID, to make it dm me and only me with the message? I've asked this before and all answers have not worked for me. These are the solution's I've gotten that did not work:
message.author.dm_channel.send("message"), but that is the same problem, it does not get rid of the author issue.
me = await client.get_user_info('MY_SNOWFLAKE_ID')
await client.send_message(me, "Hello!")
This code also did not work for me. The user that it is dming is the same each time, so I have no need to run the get_user_info in the first place. And whenever the second line runs, I get an error code because the MyClient cannot use the send_message attribute.
Your code is from the old discord version. It has been changed in the discord.py rewrite. I also recommend you to use discord.ext.commands instead of using on_message to read commands manually.
As for the dm, simply use
your_id = 123456789012345678
me = client.get_user(your_id)
await me.send("Hello")
Note that it requires members intents enabled. Use await fetch_user(your_id) if you don't have it enabled. Also, note that there might be also rate-limiting consequences if multiple users use commands simultaneously.
Docs:
get_user
fetch_user
User.send
#client.command()
async def suggest(ctx, message = None):
if message == None:
await ctx.send("Provide a suggestion")
else:
await ctx.{your_id}.send("message")
Please don't mind the indent
You can dm a user by doing this:
user = client.get_user(your_id_here)
await user.send('work!')
FAQ : https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-send-a-dm
if you want the full code here it is:
#client.command()
async def suggest(ctx, *, suggest_text):
user_suggestor = ctx.author
user = client.get_user(user_id) # replace the user_id to your user id
if suggest_text == None:
await ctx.send("Enter your suggestion! example : !suggest {your suggest here}")
else:
await user.send(f"{user_suggestor.name} sent an suggestion! \nSuggestion : {suggest_text}") # the \n thing is to space
thank me later :D

Sending an Embed in channel with permission using Discord.py raises exceptions

First of all I am sorry if I'm doing something wrong. This is my first question.
I am currently trying to create a Discord Bot using Python.
Edit: Though the answer of one person helped me a lot, my question remains, because I still have the "await coro" exception and another one was thrown after I corrected the old mistake. I've updated the code and the exceptions. Thanks for your help!
When I'm trying to send an embed when the bot joins the server, I get two exceptions. Since I don't have 50 servers, I replaced the on_member_join(self) with a simple function call when something is written in a channel:
File "...\Python\Python39\lib\site-packages\discord\client.py"
await coro(*args, **kwargs)
TypeError: on_message() missing 1 required positional argument: 'ctx'
Though I watched videos and searched on stackoverflow, I still don't understand ctx completely. That's probably the reason I'm making this mistake. If you could help me correct the code or even explain what ctx is (is it like "this" in java?), that'd be great!
Here's the code of the two functions trying to send an embed:
import discord
from discord.utils import get
from discord.ext import commands
Bot_prefix = "<" #Later used before every command
class MyClient(discord.Client):
async def Joining_Server(ctx, self):
#Get channel by name:
channel = get(ctx.guild.text_channels, name="Channel Name")
#Get channel by ID:
channels_Ids = get(ctx.guild.text_channels, id=discord.channel_id)
embed = discord.Embed(title="Thanks for adding me!", description="Try")
fields = [("Prefix", "My prefix is <. Just write it in front of every command!", True),
("Changing prefix", "Wanna change my prefix? Just write \"<change_prefix\" and the prefix you want, such as: \"<change_prefix !\"", True),
("Commands", "For a list of the most important commands type \"<help\"", False),
("Help", "For more help, type \"<help_All\" or visit:", True)]
for channels in self.channel_Ids:
if(commands.has_permissions(write=True)):
channel_verified = channels.id
await ctx.channel_verified.send(embed)
async def on_message(message, self, ctx):
if message.author == client.user:
return
if message.content == "test":
await MyClient.Joining_Server(ctx, self)
Thank you for helping me! Again: I'm sorry if I'm doing something wrong, it's my first question. Please ask if you need something. Feedback would also be very helpful.
I think you simply want to compare the content of the message to the "test" string
if message.author == client.user:
return
if message.content == "test":
await MyClient.Joining_Server()

I am trying to make a invite command, that dms the user, within a cog(discord.py)

I am trying to make a invite command that when run, will DM the user a invite link to the server. This is the code:
#commands.command(brief='A one time server invite',pass_context=True)
async def serverinvite(self, ctx):
invitelink = await ctx.channel.create_invite(max_age = 90, max_uses=1, unique=True)
await ctx.send(invitelink)
But I am having 2 issues. 1) When the command is in my cog, the cog will not load. 2)I cant figure out how to make it DM the invite link
Any help would be greatly appreciated.
Thanks!
First of all, here are the official docs which can answer your query pretty well.
Constructing a cog
Loading a cog using extensions
Creating an instant invite
Sending a DM
now that you are trying to create an instant invite, your bot will require permissions to create an instant invite, if the bot is lacking permissions, this is not gonna work. Another way is to create a permanent invite link, and send it to the user on use of command (it will also help to stop flooding the invites section of server).
#commands.command(brief='A one time server invite',pass_context=True)
async def serverinvite(self, ctx):
invitelink = await ctx.channel.create_invite(max_age = 90, max_uses=1, unique=True)
await ctx.author.send(invitelink)
the reasons that are stopping the bot on creating an invite can be...
lack of permissions to create an invite
the cog is not loaded using extensions

Categories