Stop 2 consecutive uses discord.py - discord

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

Related

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

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

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}')

How to have discord.py bot look for a message from a specific user recently?

I have a bot in writing in python and I want to incorporate a number game into the bot. The game code is below. (nl is a variable to say os.linesep)
secret_number = random.randint(0, 100)
guess_count = 0
guess_limit = 5
print(f'Welcome to the number guessing game! The range is 0 - 100 and you have 5 attempts to guess the correct number.')
while guess_count < guess_limit:
guess = int(input('Guess: '))
guess_count += 1
if guess > secret_number:
print('Too High.', nl, f"You have {guess_limit - guess_count} attempts remaining.")
elif guess < secret_number:
print('Too Low.', nl, f"You have {guess_limit - guess_count} attempts remaining.")
elif guess == secret_number:
print("That's correct, you won.")
break
else:
print("Sorry, you failed.")
print(f'The correct number was {secret_number}.')
So I want to be able to use that in the discord messaging system. My issue is that I need the bot to scan the most recent messages for a number from that specific user that initiated the game. How could I do so?
To simplify my question how can I say this:
if message from same message.author = int():
guess = that^
The solution here would be to wait_for another message from that user. You can do this with:
msg = await client.wait_for('message', check=message.author == PREVIOUS_SAVED_MSG_AUTHOR_AS_VARIABLE, timeout=TIMEOUT)
# You don't really need a timeout but you can add one if you want
# (then you'd need a except asyncio.TimeoutError)
if msg.content == int():
guess = msg
else:
...

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