How to make my custom discord bot sends message - python

Im trying to make my custom bot sends a custom message using python
Me: ~repeat Hi
My Message deleted
custom-Bot: Hi
whenever I try using this I get error problems with this code specifically "client"
await client.delete_message(ctx.message)
return await client.say(mesg)
from discord.ext import commands
client = commands.Bot(command_prefix = '~') #sets prefix
#client.command(pass_context = True)
async def repeat(ctx, *args):
mesg = ' '.join(args)
await client.delete_message(ctx.message)
return await client.say(mesg)
client.run('Token')

client does not have an attribute called delete_message, to delete the author's message use ctx.message.delete. To send a message in the rewrite branch of discord.py, you use await ctx.send()
#client.command()
async def repeat(ctx, *args):
await ctx.message.delete()
await ctx.send(' '.join(args))

Related

Not able to DM or direct messages in discord.py-self latest version

i am not been able to send dm it gives me an error using module discord.py-self
here is the code
import discord
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('BOT IS RUNNING')
async def on_message(self, message):
if message.content.startswith('.hello'):
await message.channel.send('Hello!', mention_author=True)
for member in message.guild.members:
if (member.id != self.user.id):
user = client.get_user(member.id)
await user.send('hllo')
client = MyClient()
client.run('my token')
error
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 0)
In server it is only me and a offilne bot i trying to send a message to bot (as you can see in code)
I would try defining your bot like this:
import discord
from discord.ext import commands
## (Make sure you define your intents)
intents = discord.Intents.default()
# What I always add for example:
intents.members = True
intents.guilds = True
intents.messages = True
intents.reactions = True
intents.presences = True
## Define your bot here
client = commands.Bot(command_prefix= '.', description="Description.", intents=intents)
## Run bot here
client.run(TOKEN)
Then, instead of rendering a client on_message event, I'd instead just set it up like a command which will utilize the prefix as defined for the bot above.
#client.command()
async def hello(ctx):
user = ctx.author
await ctx.send(f"Hello, {user.mention}")
dm = await user.create_dm()
await dm.send('hllo')
Better practice: (in my opinion)
Use cogs to keep your code neat. Set up this command in an entirely different file (say within a /commands folder for instance):
/commands/hello.py
import discord
from discord.ext import commands
class HelloCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def hello(self, ctx):
user = ctx.author
await ctx.send(f"Hello, {user.mention}")
dm = await user.create_dm()
await dm.send('hllo')
Then import the cog into your main file:
from commands.hello import HelloCog
client.add_cog(HelloCog(client))
Hope this helps.

Discord.py, I can't receive message with #client.command()

I can't receive message with #client.command().
This is what look like my code:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='s!')
#client.command()
async def test(ctx):
print(ctx.author)
client.run('')
Thanks
Use ctx.channel.send() to send the message to the channel where the command was invoked from.
#client.command()
async def test(ctx):
ctx.channel.send(ctx.author.name)
The thing you are trying to do is the name of the author and printing out that.
If you want to send the message the user gave, you can do this:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = 's!')
#client.event
async def on_message(message):
author = message.author
# "!test" is the command of taking the message. Change with yours.
if message.content.startswith('!test'):
print(message.content)
await test(author, message) #sends to a new method which shows message in channel.
async def test(author, message):
final_message = message.content[5:] #Slicing of the !test part. You also need to do it.
await message.channel.send(final_message)
client.run('')
Here,
"!test" is the command of taking the message. Change with yours.
Slice the command part to show the exact message.
Example

Discordpy member history() function returning nothing

I've been trying to get my own message history using the member.history() method. But all i get is an empty asyncIterator that doesn't have anything in it.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = ".",intents=discord.Intents.all())
#client.event
async def on_ready():
print('Bot is ready')
#client.command()
async def test(ctx):
me = ctx.guild.get_member_named("Slade")
print(me)
async for message in me.history(limit=5):
print(message)
client.run("token would go here")
The only thing the code above prints is the ready message and my own discord name and tag.
What am i doing wrong?
Figured out the problem. For some reason both member.history() and user.history() function return private DM's with the bot not the guild message history.
Do the following
messages = await channel.history(limit=5).flatten()
this will return a list of messages.
So your function will be:
#client.command()
async def test(ctx):
me = ctx.guild.get_member_named("Slade")
print(me)
messages = []
for channel in ctx.guild.channels:
message = await channel.history(limit=5).flatten()
messages.append(message)
for message in messages:
print(message[0].content)
```
This returns for you 5 messages of every channel in your server.

Verification using Python Discord

I'm making a bot with python and I need help with two things.
Making a welcome message for users that include mentioning the user and mentioning the channel
Making a command that will remove the role "Unverified" and add 4 other roles. I also need it to send a message in the verification channel to make sure the person has been verified and send an embed in general chat telling the user to get self roles.
Well you could try
import discord
from discord.ext import commands
from discord.utils import get
client = commands.Bot(command_prefix=".")
confirmEmoji = '\U00002705'
#client.event()
async def on_ready():
print("[Status] Ready")
#client.event()
async def on_member_join(ctx, member):
channel = get(ctx.guild.channels,name="Welcome")
await channel.send(f"{member.mention} has joined")
#client.command()
async def ConfirmMessage(ctx):
global confirmEmoji
message = await ctx.send("Confirm")
await message.add_reaction(emoji=confirmEmoji)
def check(reaction, user):
if reaction.emoji == confirmEmoji:
return True
else:
return False
while True:
try:
reaction, user = await client.wait_for("reaction_add", check=check, timeout=10)
roleToRemove = get(ctx.guild.roles,name="unverified")
memberToRemoveRole = get(ctx.guild.members,name=user.display_name)
await memberToRemoveRole.remove_roles(roleToRemove)
Now all you have to do is go to the channel and enter .ConfirmMessage

Python - DM a User Discord Bot

I'm working on a User Discord Bot in Python .If the bot owner types !DM #user then the bot will DM the user that was mentioned by the owner.
#client.event
async def on_message(message):
if message.content.startswith('!DM'):
msg = 'This Message is send in DM'
await client.send_message(message.author, msg)
The easiest way to do this is with the discord.ext.commands extension. Here we use a converter to get the target user, and a keyword-only argument as an optional message to send them:
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix='!')
#bot.command(pass_context=True)
async def DM(ctx, user: discord.User, *, message=None):
message = message or "This Message is sent via DM"
await bot.send_message(user, message)
bot.run("TOKEN")
For the newer 1.0+ versions of discord.py, you should use send instead of send_message
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix='!')
#bot.command()
async def DM(ctx, user: discord.User, *, message=None):
message = message or "This Message is sent via DM"
await user.send(message)
bot.run("TOKEN")
Since the big migration to v1.0, send_message no longer exists.
Instead, they've migrated to .send() on each respective endpoint (members, guilds etc).
An example for v1.0 would be:
async def on_message(self, message):
if message.content == '!verify':
await message.author.send("Your message goes here")
Which would DM the sender of !verify. Like wise, you could do:
for guild in client.guilds:
for channel in guild.channels:
channel.send("Hey yall!")
If you wanted to send a "hi yall" message to all your servers and all the channels that the bot is in.
Since it might not have been entirely clear (judging by a comment), the tricky part might get the users identity handle from the client/session. If you need to send a message to a user that hasn't sent a message, and there for is outside of the on_message event. You will have to either:
Loop through your channels and grab the handle based on some criteria
Store user handles/entities and access them with a internal identifier
But the only way to send to a user, is through the client identity handle which, in on_message resides in message.author, or in a channel that's in guild.channels[index].members[index]. To better understand this, i recommend reading the official docs on how to send a DM?.
I used this command in the past and it in my opinion it works the best for me:
#bot.command(pass_context=True)
async def mall(ctx, *, message):
await ctx.message.delete()
for user in ctx.guild.members:
try:
await user.send(message)
print(f"Successfully DMed users!")
except:
print(f"Unsuccessfully DMed users, try again later.")
#bot.command()
async def dm(ctx, user: discord.User, *, message=None):
if message == None:
message = "Hi!"
embed = make_embed(title=f"Sent by {user}", desc=message)
await user.send(embed=embed)
await ctx.send("Message sent!")```
I have noticed that each code I put into my code lines they don't work completely, so I added my own bit to them and bam it works! When adding this to your bot's code, don't forget to add the bot's name where it says bot name here. It will only DM the person who sent it, but you can change what it says each day for a surprise for everyone that used the command. It works every time for me.
#client.command()
async def botdm(ctx):
await ctx.message.author.send('hi my name is *bot name here* and i am a bot!')

Categories

Resources