【问题标题】:Unsure as to how to have a bot send a message when a member joins a Discord Server不确定当成员加入 Discord 服务器时如何让机器人发送消息
【发布时间】:2020-12-30 11:40:17
【问题描述】:

首先,我尝试用谷歌搜索,但永远找不到答案,所以我在 stackoverflow 上。因此,我正在尝试向我的不和谐机器人添加问候效果,但似乎无法发送消息。我知道机器人没有发送消息,因为使用 message.channel.send 时未定义“消息”,但我不知道这样做的正确方法。

错误:

Traceback (most recent call last):
  File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "<string>", line 20, in on_member_join
NameError: name 'message' is not defined`)
import discord


bot = discord.Client() 

@bot.event
async def on_ready():
    print('Logged in')
    print("Username: %s" % (bot.user.name))
    print("Userid: %s" % (bot.user.id))

@bot.event
async def on_member_join(member):
    print(f'{member} has joined the server')
    await message.channel.send('{member} has joined the server'.format(message))

@bot.event
async def on_member_remove(member):
    print(f'{member} has left the server')
    await message.channel.send('{member} has left the server'.format(message))

bot.run(Token)

【问题讨论】:

  • 您要将消息发送到哪个频道?
  • @PatrickHaugh 如何让机器人发送带有 ID 的频道名称(例如 #test 与该频道的实际“链接”)?编辑:我还需要检查消息发送到哪个频道。我试图让机器人检查一个字符串,比如“foo”是否在消息中,以及除#bar 之外的任何频道中。也很抱歉提出要求
  • @DartRuffian,假设您要提及一个频道,如果您查看我之前的回答,您可以执行channel.mention,这将发送一个可点击的频道名称,重定向到该频道。
  • @Jawad 是的,在我发布它后不久,我确实弄明白了(我没有在 id 频道 id 之前使用“#”)。

标签: python discord.py discord.py-rewrite


【解决方案1】:

使用get_channel 获取您的#welcome 频道,将其分配给一个变量,然后发送欢迎消息。

@client.event
async def on_member_join(member):
    channel = client.get_channel(730064641857683581)  # Replace with your Welcome channel ID
    await channel.send(f"{member} has joined the server")

【讨论】:

    【解决方案2】:

    错误是正确的。如果 message 未定义,message.channel.send 将永远无法工作,但事实并非如此。 message 是一些discord.py 函数的参数,但不是on_member_joinon_member_remove,因为这些不会发生在特定通道中。您必须预先指定将消息发送到哪个频道。

    【讨论】:

    • 我知道它永远不会起作用,因为 message 不会被定义;但是我不知道也找不到定义它的正确方法。
    猜你喜欢
    • 2020-01-22
    • 2018-07-27
    • 2021-01-28
    • 1970-01-01
    • 2022-01-23
    • 2021-08-19
    • 2021-01-19
    • 2020-10-16
    • 2021-01-08
    相关资源
    最近更新 更多