首页 > 解决方案 > 如何使用 Discord.py 发送消息

问题描述

我试图制作一个 Discord Bot,但我一直在努力让 bot 向服务器发送消息。我编写了这段代码,它接收来自服务器的消息并将它们打印在终端中,如果有人可以用一种方法来回答这个问题,只需重复机器人发送的消息,那就太好了。


import discord


client = discord.Client()

token = 'My token'

# bot is ready
@client.event
async def on_ready():
    try:
        
        print(client.user.name)
        print(client.user.id)
        print('Discord.py Version: {}'.format(discord.__version__))
    
    except Exception as e:
        print(e)


@client.event
async def on_message(message):
    # print message content in terminal
    print(message.content)


client.run(token)

标签: pythondiscorddiscord.py

解决方案


每当有人向文本频道发送“生日快乐”时,此代码都会发送一条消息。

@client.event
async def on_message(message):
    if message.author == client.user:
            return
    if message.content.lower() == "happy birthday":
            await message.channel.send("happy Birthday!")
    # print message content in terminal
    print(message.content)

您可以以此为例。


推荐阅读