How do i make my discord.py bot go through a text file and if a user says a word in that file it will delete that message + how to make uptime command - discord

I want my discord.py bot to go through a text file and if a user says a word in that file it will delete that message
elif msg.content == '***':
await msg.channel.send("Dont curse")
await msg.delete()
that is my code but i want to replace *** with a text document
And also another question i have some issues with an uptime command
async def on_ready():
print("Bot is running")
activity = discord.Game(name="!test", type=3)
await client.change_presence(status=discord.Status.idle, activity=activity)
channel = client.get_channel(944665750453497886)
myid = '<#516236429689618467>'
await channel.send("I am online "+myid)
#Uptime code starts
global startdate
startdate = datetime.now()
#client.command()
async def uptime(ctx):
now = datetime.now()
uptime = startdate - now
uptime = uptime.strftime('%d/%h/%M')
await ctx.send(f'Uptime: {uptime}')

Related

Stop 2 consecutive uses discord.py

I am making a discord bot in which an auction could take place.So I want someone to bid only once unless someone bids after him/her.
`async def bid(ctx):
embed1=discord.Embed(description= f'Bid has been placed by {ctx.author}', title='bid placed')
await ctx.send(embed=embed1)
`
That's what I have so far made.
You could put the author id in a variable:
bidderid = 0 #this will reset whenever your bot restarts
#client.command()
async def bid(ctx):
global bidderid
if ctx.author.id != bidderid: #if it is not the same bidder
bidderid = ctx.author.id
embed1=discord.Embed(description= f'Bid has been placed by {ctx.author}', title='bid placed')
await ctx.send(embed=embed1)
else: #if it is the same bidder
await ctx.send('You cannot bid twice in a row!') #replace with whatever message
note: It doesn't have to be the id, you could store ctx.author instead, idea is the same

How do I create a timestamp in an embed with pycord?

I would like my sent msg log which is an embedded msg to have a timestamp, so it would have a footing like bot_name • Today at 10:48 PM
Here is my current code,
#bot.event
async def on_message(ctx):
if ctx.author.bot: return
else:
log_msg = bot.get_channel(1023451687857442828)
embed = discord.Embed(
title = "Sent Message",
description = f"""This message was sent by{ctx.author.mention}, in {ctx.channel}\n**Message:** "{ctx.content}" """,
color = discord.Colour.green(),
)
embed.set_author(name=ctx.author)
embed.set_footer(text="bot_name")
await log_msg.send(embed=embed)```
You could do the following:
(remaining of your code)
now = datetime.now() # Gets your current time as a datetime object
embed.set_footer(text=f'bot_name • Today at {now.strftime("%H:%M")}') # Set your embed footer with the formatted time
await log_msg.send(embed=embed) # Sends your footer (already present in your original code)
If you don't have it imported already, you'll have to import datetime from datetime, or import datetime and do datetime.datetime.now() instead of just datetime.now()
You can use ctx.message.created_at to add a timestamp. That would look like this in the context of your code:
#bot.event
async def on_message(ctx):
if ctx.author.bot: return
else:
log_msg = bot.get_channel(1023451687857442828)
embed = discord.Embed(
title = "Sent Message",
description = f"""This message was sent by{ctx.author.mention}, in {ctx.channel}\n**Message:** "{ctx.content}" """,
color = discord.Colour.green(),
# message created at code below
timestamp = ctx.message.created_at
)
embed.set_author(name=ctx.author)
embed.set_footer(text="bot_name")
await log_msg.send(embed=embed)
Hope this helps

AttributeError: 'Context' object has no attribute 'guild_icon'

I am trying to set up a command to print the information of the server the bot is in. The code below gives the error AttributeError: 'Context' object has no attribute 'guild_icon'
#commands.command()
async def serverinfo(self,ctx):
name = str(ctx.guild.name)
description = str(ctx.guild.description)
owner = str(ctx.guild.owner)
id = str(ctx.guild.id)
region = str(ctx.guild.region)
memberCount = str(ctx.guild.member_count)
embed = discord.Embed(
title=name + " Server Information",
description=description,
color=discord.Color.blue()
)
embed.set_thumbnail(ctx.guild_icon)
embed.add_field(name="Owner", value=owner, inline=True)
embed.add_field(name="Server ID", value=id, inline=True)
embed.add_field(name="Region", value=region, inline=True)
embed.add_field(name="Member Count", value=memberCount, inline=True)
await ctx.send(embed=embed)
When trying to find the solution I tried to change the code to be
#commands.command()
async def serverinfo(self,ctx):
name = str(ctx.guild.name)
description = str(ctx.guild.description)
owner = str(ctx.guild.owner)
id = str(ctx.guild.id)
region = str(ctx.guild.region)
memberCount = str(ctx.guild.member_count)
embed = discord.Embed(
title=name + " Server Information",
description=description,
color=discord.Color.blue()
)
embed.set_thumbnail(ctx.guild.icon)
embed.add_field(name="Owner", value=owner, inline=True)
embed.add_field(name="Server ID", value=id, inline=True)
embed.add_field(name="Region", value=region, inline=True)
embed.add_field(name="Member Count", value=memberCount, inline=True)
await ctx.send(embed=embed)
But then I get the error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: set_thumbnail() takes 1 positional argument but 2 were given
Could someone tell me what I have done wrong and point me in the right direction?
Problem 1
ctx.guild_icon does not exist, you fix this in your second code by using ctx.guild.icon
Problem 2
discord.Embed.set_thumbnail takes in a named argument for the image.
In fact, it doesn't take in an image at all, but rather a url
Solution
To solve your issue, you should use the following:
embed.set_thumbnail(url=ctx.guild.icon.url)
More info
discord.ext.commands.Context
discord.Embed.set_thumbnail

Getting the users total invites in Discord.py

I am trying to add a command to my bot which replies with the total people the user has invited to the server
My code:
if message.content.startswith('!invites'):
totalInvites = message.guild.invites
await message.channel.send("You have invited: " + totalInvites + " members to the server")
The bot replies with:
You have invited: <bound method Guild.invites of <Guild id=server_id_goes_here name='my bot' shard_id=None chunked=True member_count=12>> members to the server
What is it that I am doing wrong?
You've almost got the right idea!
on_message event usage:
#bot.event
async def on_message(message):
if message.content.startswith('!invites'):
totalInvites = 0
for i in await message.guild.invites():
if i.inviter == message.author:
totalInvites += i.uses
await message.channel.send(f"You've invited {totalInvites}
member{'' if totalInvites == 1 else 's'} to the server!")
Command decorator usage:
#bot.command()
async def invites(ctx):
totalInvites = 0
for i in await ctx.guild.invites():
if i.inviter == ctx.author:
totalInvites += i.uses
await ctx.send(f"You've invited {totalInvites} member{'' if totalInvites == 1 else 's'} to the server!")
First I'm iterating through each invite in the guild, checking who created each one. If the creator of the invite matches the user that executed the command, it then adds the number of times that invite has been used, to a running total.
You don't need to include the {'' if totalInvites == 1 else 's'}, that's just for the odd case that they've invited 1 person (turns member into the plural - members).
References:
Guild.invites - the code originally didn't work because I forgot this was a coroutine (had to be called () and awaited).
Invite.uses
Invite.inviter
commands.command()
F-strings Python 3.6+

(Discord.py) Send a dm or is to all members of all servers

I begin the dev for 2 days and i want to create a command in the dm of the bot ">
#bot.event
async def on_message(message):
if message.content.startswith('><dmall'):
name = message.content.split(" ")[1]
if(name == "all"):
for member in message.guild.members:
try:
await member.send("test")
except discord.Forbidden:
print("[DM]" + name + "à bloqué ses dm")
else:
member = discord.utils.get(message.guild.members, name=name)
NOTE: PLEASE DO NOT ABUSE THIS, IT IS A BANNABLE OFFENSE ON DISCORD'S TOS
# an alternative to putting your commands in an on_message event:
#bot.command()
async def dmall(ctx):
for m in bot.get_all_members():
await m.send("Hello! This is a DM :)")
print("Done!")
# error handler
#bot.event
async def on_command_error(ctx, error):
if isinstance(error, discord.ext.commands.errors.Forbidden):
print(f"[DM] {ctx.author} has DMs disabled.")
else:
print(error)
References:
Client.get_all_members()
discord.on_command_error()
Exceptions

Resources