Discord.py - How to run additional code after running client.run(token)? - discord.py

Seemingly simple question but I'm stuck on how to solve it.
I use discord.py to login to my account and I want to DM a user by inputting his user_id .
import discord
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
client = MyClient()
client.run('token')
async def send_message(user_id):
user = client.get_user(user_id)
await user.send('My message')
When I run this python file in my python shell, it would print the "Logged in as ..." success message and it would hang up. It wouldn't let me type any other command.
I simply want to run the send_message function with a unique user_id, so I can DM a particular user.
How do I do this?

That's because client.run is blocking, so any code below it won't be executed while the bot is running. The best way to avoid this problem is by moving the function somewhere above it, like in the client subclass.
I don't know exactly where you want to execute this function from, so I would suggest that you run it from on_ready for now.
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
await self.send_message(123456) # DM a user with id "123456" as soon as the bot is ready
async def send_message(self, user_id):
user = self.get_user(user_id)
await user.send('My message')
client = MyClient()
...
If you want to execute this command from Discord, here is a good walkthrough.

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 do i display a message if user puts a non existing sub command?

So I made a sub command that just sends a message back. I found that if the user types a non existing command it still displays the message from the sub command. It sounds confusing but here's an example.
User: ;id
Bot: This command help you find the name of anyone in the server!
User: ;id Slayer
Bot: Bob Miller
So while testing I found if the user sends some thing like ;id jgfjkag the bot still sends the original message for ;id which is "This command help you find the name of anyone in the server!". How would I make the bot send a specific message if the user trys to use a non existing sub command? Here's the code:
#commands.group()
async def id(self, ctx):
if ctx.invoked_subcommand is None:
await ctx.send("This command help you find the name of anyone in the server! ")
#id.command()
async def Slayer(self, ctx):
await ctx.send("Bob Miller")
#id.command()
async def Skel(self, ctx):
await ctx.send("John Dove")
Check ctx.subcommand_passed first:
#commands.group()
async def id(self, ctx):
if ctx.subcommand_passed is None:
await ctx.send("This command help you find the name of anyone in the server!")
elif ctx.invoked_subcommand is None:
await ctx.send(f"Subcommand '{ctx.subcommand_passed}' does not exist.")
This is my favorite method of doing it:
#commands.group(invoke_without_command=True)
async def group(self, ctx):
await ctx.send_help(ctx.command) # invokes the help command for the group
#group.command()
async def subcommand(self, ctx):
await ctx.send("You passed a valid subcommand!")
The invoke_without_command parameter, when set to true, will only call the command if there are no (valid) subcommands passed. This means that if the code inside if the group() function is called, you can safely assume that they didn't pass a subcommand (or passed an invalid one).
I also like to use ctx.send_help, since that will automatically list subcommands. You could replace this with something like:
await ctx.send("You didn't pass a valid subcommand!")
[EDIT]
More careful reading of your question revealed that the subcommand already has some functionality. This makes it more difficult, but this will work:
#commands.group(invoke_without_command=True, ignore_extra=False)
async def group(self, ctx):
await ctx.send("This is a group command!")
#group.error
async def on_group_error(self, ctx, error):
if isinstance(error, commands.TooManyArguments):
await ctx.send("You passed an invalid subcommand!")
#group.command()
async def subcommand(self, ctx):
await ctx.send("You passed a VALID subcommand!")
Here is what it would look like:
!group
Bot: This is a group command!
!group bla
Bot: You passed an invalid subcommand!
!group subcommand
Bot: You passed a VALID subcommand!
NOTE: The ignore_extra field raises the commands.TooManyArguments error, which then invokes the error handler allowing the bot to send the error message. Unfortunately, the default on_command_error hook will still be called. I would suggest ignoring the commands.TooManyArguments error inside of your main error handler to fix this.

Discord dm bot that can dm back

I am trying to make a donation bot, where in the channel when a person types !donate the bot will Dm them.
I got all that down but I am trying to make so that the person decides on how to donate like !cashapp, !paypal, etc., in the dms. It would send them that specific way to send money, for example once the bot Dms the use user what service they would like to pay with and the user says !cashapp it will send another message with my cashtag, or if they say !paypal it would send my paypal link.
Here's a simple example:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = "!")
#client.command()
async def donate(ctx, paymentMethod: str):
if (paymentMethod.lower() == "paypal"):
await ctx.send("PayPal link: ...")
elif (paymentMethod.lower() == "cashapp"):
await ctx.send("Cashapp Link: ...")
else:
await ctx.send("The provided payment method is not available.")
#donate.error
async def donate_error(ctx, error):
if isinstance(error, commands.errors.MissingRequiredArgument):
await ctx.send("Incorrect use of command!")
client.run("your bot token here")
Usage:
!donate {payment method} - Without the '{}'
Check the documentation for more information.
You can use user.send to send a message to the user dm and use it in the same way as ctx.send and channel.send.
await ctx.author.send("paypal link: ...") # ctx.author is the member that call the command
And 2 command will have different function so you just need to write both of them in a different way.
If you planning to make it into 1 command you can use if else check
#client.command(pass_context=True)
async def steam(ctx):
if ctx.author.send():
await ctx.send("you not boster")
else:
await ctx.author.send(random.choice(list(open('steam.txt'))))
i want if someone send a dm
its not Returns a dm
someone know how to do this?

How to make a Reaction role command with discord.py

So I'm trying to make a Reaction role via discord.py but i don't know how to do it. Also there is no tutorial on YT, I want the bot to send a message and react to that message so the user when react to that get the role.
Okay,
This uses cogs and a bot instead of a client.
message = await ctx.send(" Click the ✅ reaction to verify yourself")
This piece sends the message (You can change it to whatever you want).
if not get(ctx.guild.roles, name="Verified"):
perms = discord.Permissions()
perms.general()
perms.text()
perms.voice()
await ctx.guild.create_role(name="Verified", permissions=perms, colour=discord.Colour(0x00bd09))
This piece will just check whever the role exists or not. If it doesnt it will create one.
await message.add_reaction("✅")
This adds this reaction to the message(So the user doesnt have to scroll around for it). If you dont want the bot have the role, you can add a check (If the user is a bot or not) in the on_raw_reaction_add() function.
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
guild = self.bot.get_guild(payload.guild_id)
role = discord.utils.get(guild.roles, name="Verified")
await payload.member.add_roles(role, reason="Verified Self", atomic=True)
This is the function to check when someone adds a reaction to the message. We want to use on_raw_reaction_add() instead of on_reaction_add() because the second one check the cache for adding a reaction, and if the thing isnt in chache it wont work. Thus the 1st one is less probable to create problems.
Here's the whole piece.
from discord.ext import commands
from discord.utils import get
import discord
from discord.ext.commands import has_permissions, CheckFailure
class Verification(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command(name='generate_verification', help='Generates verification message')
async def generate_verification(self, ctx):
message = await ctx.send(" Click the ✅ reaction to verify yourself")
verification_message_id = message.id
# Check if Verification role already exists
if not get(ctx.guild.roles, name="Verified"):
perms = discord.Permissions()
perms.general()
perms.text()
perms.voice()
await ctx.guild.create_role(name="Verified", permissions=perms, colour=discord.Colour(0x00bd09))
await message.add_reaction("✅")
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
guild = self.bot.get_guild(payload.guild_id)
role = discord.utils.get(guild.roles, name="Verified")
await payload.member.add_roles(role, reason="Verified Self", atomic=True)
def setup(bot):
bot.add_cog(Verification(bot))
If you're creating a verification command, then you probably would like to store the amount of verification messages sent in a file. This would stop people from generating the message a lot of times. To this you also probably want a command to clear the data from the file, so if the adming wants to create the message again he just needs to clear the file.

Discord Bot sending more than one message

So I am creating a simple bot that detects when somebody joins a server and when somebody leaves the server.
I added a command to show people's avatars, but any time I do it, or when somebody joins or leaves, it sends the message more than once.
I've searched and I can't find the problem.
Can you guys help me?
Here's my code
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="?")
#client.event
async def on_ready():
print("Ready")
#client.event
async def on_member_join(member):
channel = discord.utils.get(member.guild.text_channels, name="entradas")
await channel.send(f"{member} is new on the server, everyone say hi")
show_avatar = discord.Embed(color = discord.Color.blue())
show_avatar.set_image(url="{}".format(member.avatar_url))
await channel.send(embed=show_avatar)
#client.event
async def on_member_remove(member):
channel = discord.utils.get(member.guild.text_channels, name="saidas")
await channel.send(f"{member} left the server, press F to pay respects")
#client.command()
async def avatar(ctx, member: discord.Member):
show_avatar = discord.Embed(color = discord.Color.blue())
show_avatar.set_image(url="{}".format(member.avatar_url))
await ctx.send(embed=show_avatar)
You should check if you are running 2 bots.
If you are running your bot on Linux with screen, simply check with
screen -ls
on windows, just check the task-manager and look under something like Python.
It's btw possible to have the same bot running twice.

Resources