Samlinuxgeek
Samlinuxgeek

Reputation: 13

How to make a Discord.py ping cmd

I tried lots of other peoples solutions and they didn't work. So, how do I get a ping command that shows the ping in MS?

This is my code and I get no errors whatsoever, tough it just doesn't reply to my CMD.

import os
from keep_alive import keep_alive
from discord.ext import commands
import time
import random
    
bot = commands.Bot(
    command_prefix="!",  # Change to desired prefix
    case_insensitive=True  # Commands aren't case-sensitive
)
    
bot.author_id = 777526936753799189 
   
@bot.event 
async def on_ready():  
    print("I'm in")
    print(bot.user)  
    
@bot.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Hi {member.name}, welcome to my Discord server!'
    )
    
@bot.event
async def on_message(message):
    if '!test' in message.content.lower():
        await message.channel.send('heyo')
    
@bot.command()
async def ping(ctx):
    await ctx.channel.send(f"{client.latency}")
    
@bot.command()
async def test(ctx, arg):
    await ctx.send(arg)
   
    
extensions = [
    'cogs.cog_example'  
]
    
if __name__ == '__main__':
    for extension in extensions:
        bot.load_extension(extension)
    
    keep_alive()  
    token = os.environ.get("DISCORD_BOT_SECRET") 
    bot.run(token)

To simplify stuff, here is the command I used to get the ping response.

@bot.command()
async def ping(ctx):
    await ctx.channel.send(f"{client.latency}")

Upvotes: 0

Views: 800

Answers (1)

Bagle
Bagle

Reputation: 2346

To put it simply, you've defined your bot as bot. Therefore, you should replace client.latency with bot.latency

@bot.command()
async def ping(ctx):
    await ctx.send(f"{bot.latency}")

But if you would prefer a different way, you can do this instead:

@bot.command()
async def ping(ctx):
    start = time.perf_counter()
    msg = await ctx.send("Ping..")
    end = time.perf_counter()
    duration = (end - start) * 1000
    await msg.edit("Pong! {:.f}ms".format(duration))

Also, there's a chance your other command(s) might not be working either due to your on_message event. If they're not, you need to process the commands.

@bot.event
async def on_message(message):
    if '!test' in message.content.lower():
        await message.channel.send('heyo')
    await bot.process_commands(message)

Upvotes: 4

Related Questions