How to make a ping command in discord.py? - discord.py

I used a couple of tricks and they don't work.
For example:
#client.command()
async def ping(ctx):
await ctx.send('Pong! {0}'.format(round(bot.latency, 1)))
Please help!

I used this code:
async def ping(ctx):
if round(client.latency * 1000) <= 50:
embed=discord.Embed(title="PING", description=f":ping_pong: Pingpingpingpingping! The ping is **{round(client.latency *1000)}** milliseconds!", color=0x44ff44)
elif round(client.latency * 1000) <= 100:
embed=discord.Embed(title="PING", description=f":ping_pong: Pingpingpingpingping! The ping is **{round(client.latency *1000)}** milliseconds!", color=0xffd000)
elif round(client.latency * 1000) <= 200:
embed=discord.Embed(title="PING", description=f":ping_pong: Pingpingpingpingping! The ping is **{round(client.latency *1000)}** milliseconds!", color=0xff6600)
else:
embed=discord.Embed(title="PING", description=f":ping_pong: Pingpingpingpingping! The ping is **{round(client.latency *1000)}** milliseconds!", color=0x990000)
await ctx.send(embed=embed)
Make sure you do #client.command() at the top, I removed it because I use a different command handler. Obviously, I decided to make it fancy by color coding it, and putting everything in embeds. If you want a simple command that returns a ping, and only a ping, try this:
async def ping(ctx):
await ctx.send(f"{client.latency}")
It can't really get much simpler than that. If that doesn't work, try:
async def ping(ctx):
await ctx.channel.send(f"{client.latency}")
As always, don't forget to add #client.command() at the top.

Related

is there another command should i use?

So, I can't use the "?roast" command and "?roast #(user)" at the same time...
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.dnd, activity=discord.Game(' "?" Booe'))
print('Bot is ready to play!')
#client.command()
async def roast(ctx, member:discord.Member):
roast_messages = [
f'{ctx.message.author.mention}You are useless as the UEUE in Queue {member.mention}',
]
await ctx.send(random.choice(roast_messages))
There is always a way to solve that , discord gives us a way like this
#client.command()
async def roast(ctx, member:discord.Member=None):#None is if nothing is given then its None
if member == None:
member = ctx.author
roast_messages = [
f'{ctx.message.author.mention}You are useless as the UEUE in Queue {member.mention}',]
await ctx.send("imagine roasting yourself")#Your Choice Absolutely :)
await ctx.send(random.choice(roast_messages))
here if the member isnt specified , the function is called taking member as none , later gives the none value to the ctx.author itself (dont try to write ctx.author instead of none in the async def roast it gives error as ctx aint defined. also i forgot your roast messages wont make sense then so make sure to edit them too TY :)

Command to spam something discord-bot

so basically I am trying to make a spam command for my discord bot, which takes in a custom message to spam. Here's the code:
#client.command(name='spam')
async def spam(ctx):
global stop
stop = 0
content = ctx.message.content[11:]
if ctx.author.guild_permissions.administrator or ctx.author.id in admins:
if lock == 1:
await ctx.send('Jesus bot is currently locked.')
elif lock == 0:
await ctx.send('Beginning spam..')
while not stop:
await ctx.send(content)
else:
await ctx.send('Sorry, but you do not have admin permissions in this server, or you are not a verified admin.')
For some reason, whenever I try to use this command, the bot doesn't respond. I'm not sure why this happens, and could use some help please.
Picture of bot not responding:
I have a spam command, but I only use it to mess around with my friends. I would not recommend using this as a public command, as you may get rate limited or banned for abuse or something like that. Anyway here is the code I have used for it.
#commands.command()
#commands.is_owner()
# If you want to use admin only, use this below
# #commands.has_permissions(administrator=True)
async def spam(self, ctx, amount, *, word):
int(amount)
await asyncio.sleep(2)
print(f"Starting to spam {word} in {ctx.guild.name}")
await ctx.message.delete()
await ctx.send(f"{ctx.author.mention}\nPlease note that this will clog up the bot's reaction time")
await asyncio.sleep(3)
count = 0
counting=True
while counting:
await ctx.send(word)
count = count + 1
if count == amount:
await asyncio.sleep(2)
await ctx.send("Spam complete")
print(Fore.GREEN + "Spam complete")
counting = False
At the top of your code, make sure you import asyncio as time.sleep will cause the whole bot to pause. Also the Fore.GREEN stuff is just colorama (import colorama).
Try using tasks instead of asyncio. It is made for such repetetive operations and it is easier and nicer because it is made by discord and is included in discord.ext. Something like this:
from discord.ext import tasks
#client.command(name='spam')
async def spam(ctx):
#get message and do all the ifs that you have there
spamLoop.start()
#client.command(name='stopSpam')
async def spamStop(ctx):
# stop the loop
spamLoop.cancel()
#tasks.loop(seconds=1)
async def spamLoop():
print("The message")
Actually quite a simple way of adding spam
import asyncio
#bot.command(name='spam', help= "Spam to your heart's delight")
async def spam(ctx, thing, amount):
count = 0
while count < int(amount):
await ctx.send(thing)
count += 1
if count < amount:
await asyncio.sleep(1)

discord.py moving people to different voice channels

channel_a = bot.get_channel(780743421442260993)
#bot.command()
async def Movee(ctx):
i = 0
while i < len(participant):
if type(participant[i]) != str:
await participant[i].move_to(channel_a)
i += 1
I want to move people to another voice chat room,
but using this code, people are just disconnected from voice chat room.
I've already checked if the channel ID is correct...
If you know the solution, I would appreciate it if you could let me know.
channel = []
#bot.event
async def on_ready():
channel_a = bot.get_channel(780743421442260993)
channel.append(channel_a)
#bot.command()
async def setChA(ctx):
channel[0] = bot.get_channel(ctx.message.author.voice.channel.id)
await ctx.send("Done")
#bot.command()
async def Move(ctx):
i = 0
while i < len(participant):
if type(participant[i]) != str:
await participant[i].move_to(channel[0])
i += 1
It work very well change as above.
I think it's caused by the way the async function works.
It will probably work well without using list.
I post it for someone who will have the same problem as me.
Also I always welcome anyone who knows a better way :D

How could I reset a command cooldown from an error function

I have a question. It seems that I have no idea how to reset a command cooldown, not in the actual command itself.
#bot.command()
#commands.cooldown(1,900,type=commands.BucketType.member)
async def rob(ctx, left: discord.Member):
guild=ctx.author.guild
server_members=guild.members
if left in server_members:
print('found user')
random_chance = random.randint(0,1)
if random_chance == 1:
print('robbery successful')
else:
await ctx.channel.send('Robbery not successful lol noob')
else:
await ctx.channel.send('That person is not in this server... :sob:')
#rob.error
async def roberror(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.channel.send('You have to supply me with someone to rob.. noob')
elif isinstance(error, commands.BadArgument):
await ctx.channel.send('You have to provide me with a valid person..')
elif isinstance(error, commands.CommandOnCooldown):
await ctx.channel.send(f'Chill. Your on cooldown. Try again in {math.ceil(error.retry_after)} seconds')
else:
raise error``` I would like to have it reset the command cooldown in the roberror function. Can anyone help me with this?
A command's cooldown can be reset with the reset_cooldown attribute, then pass the command context as a parameter. Heres a example using it,
rob is the command identifier then reset_cooldown is the attribute. This example would reset the cooldown of the command
rob.reset_cooldown(ctx)
It seems you would like to put this when the "rob" command was unsuccessful, you can just add it like this:
else:
await ctx.channel.send('Robbery not successful lol noob')
rob.reset_cooldown(ctx)
You can find more information in the documentation: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html

How do I take in user input in discord.py

This may be kinda dumb but I'm trying to make a purge command but theres always something wrong with it. Can anyone help please?
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('p!purge'):
numberoftimes = input(int('How many times: '))
await message.channel.purge(limit=str(numberoftimes))
I'll start with answering your question, then I'll clarify on a better way to create a purge command. To answer your question, there is no need to make an input() statement. Rather, this is how you make an input prompt with a Discord bot:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('p!purge'):
await message.channel.send('How many messages do you want to purge?')
while True:
numberoftimes = client.wait_for('message') # This means, the client is waiting for a message
if numberoftimes.author == message.author: # Make sure that the person responding is the person who did the command
limit = int(numberoftimes.content) # If its a string, it will be treated as a word. You want to purge a "number" of messages
await message.channel.purge(limit=limit+1)
That's how you would purge messages in a channel. But, the way you are creating this command can be made simpler. You can use the command decorator, which is the "standard" way of doing things:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='p!')
#client.command()
#commands.has_permissions(manage_messages=True)
async def purge(ctx, limit):
limit = int(limit)
await ctx.channel.purge(limit=limit + 1)

Resources