Discord.py- 如何在 ping 时使机器人消息成为服务器前缀?

时间:2021-03-16 10:37:58

标签: python discord.py bots

我希望我的机器人在 ping(提到)时发送该特定服务器的前缀。

我用谷歌搜索过,但没有用 (https://velero.io/docs/v1.5/restic/)

它停止执行其他命令等

这是我的代码

import random
import json
from discord.ext import commands
import numpy
from urllib.request import urlopen as url
from discord.ext.commands import cooldown, BucketType
#testbot
def get_prefix(client, message):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    
    return prefixes[str(message.guild.id)]

bot = commands.Bot(command_prefix = get_prefix)

@bot.event
async def on_ready():
    print(f'bots up')

@bot.event
async def on_guild_join(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    
    prefixes[str(guild.id)] = '.'
    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@bot.event
async def on_guild_remove(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    
    prefixes.pop(str(guild.id))
    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@bot.command()
async def setprefix(ctx, prefix):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    
    prefixes[str(ctx.guild.id)] = prefix
    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)
    await ctx.send(f'prefix set to: {prefix}')

@bot.command(description='check bot ping type .ping')
async def ping(ctx):
    await ctx.send(f'{round(bot.latency*1000)}ms')
@bot.event
async def on_message(message):
    if bot.user.mentioned_in(message):
        print("pinged")
        await message.channel.send('My prefix here is {0} '.format(bot.command_prefix))


bot.run('token')

改为向我发送此消息

1 个答案:

答案 0 :(得分:1)

您可以使用 on_message 事件来检查何时提及您的机器人。

@bot.event
async def on_message(message):
    if bot.user.mentioned_in(message) and message.mention_everyone is False:
        prefix= get_prefix
        await message.channel.send(f"My prefix is {bot.command_prefix}")

     await bot.process_commands(message) # This line makes your other commands work.

最后一行可能是您对使用 on_message 事件后命令停止工作的解决方案。