【问题标题】:How to make a Discord.py ping cmd如何制作 Discord.py ping cmd
【发布时间】:2021-05-05 05:05:16
【问题描述】:

我尝试了很多其他人的解决方案,但都没有奏效。 那么,如何获得在 MS 中显示 ping 的 ping 命令?

这是我的代码,我没有收到任何错误,但它只是不回复我的 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)

为了简单起见,这里是我用来获取 ping 响应的命令。

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

【问题讨论】:

    标签: python api discord discord.py ping


    【解决方案1】:

    简单地说,您已将您的机器人定义为机器人。因此,您应该将client.latency 替换为bot.latency

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

    但如果您更喜欢不同的方式,您可以这样做:

    @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))
    

    此外,由于您的on_message 事件,您的其他命令也可能无法正常工作。如果不是,则需要处理命令。

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

    【讨论】:

    • 我现在收到此错误,SyntaxError: f-string: empty expression not allowed  KeyboardInterrupt
    • 哎呀,不小心在 ping 命令中添加了一个 f 字符串。我会编辑答案?
    猜你喜欢
    • 2019-07-23
    • 2020-11-14
    • 2021-08-19
    • 2021-01-13
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多