当机器人加入服务器时发送消息

Send a message when the bot joins a server

每次当机器人被邀请到服务器时,我都想发送一条消息。然后它应该这样写:"Hello this is my discord bot"

到目前为止我有这段代码,它没有产生任何错误,但也没有发送消息。

@bot.event
async def on_server_join(ctx):
    for guild in bot.guilds:
        for channel in guild.text_channels:
            if channel.permissions_for(guild.me).say:
                await ctx.message.channel.send('Hello! \n')
                break

您的代码中有几个错误。下面的版本只是在它刚刚加入的服务器的 #general 文本通道中打招呼(而不是它所属的每个服务器的每个文本通道)。以下代码用于重写分支。

from discord.utils import find

@client.event
async def on_guild_join(guild):
    general = find(lambda x: x.name == 'general',  guild.text_channels)
    if general and general.permissions_for(guild.me).send_messages:
        await general.send('Hello {}!'.format(guild.name))