使用 discord.py 向指定频道发送消息时出错

Error when sending an message to specified channel using discord.py

我 运行 在有人加入我的不和谐时尝试向指定频道发送消息时遇到问题。 我得到这个错误:

Ignoring exception in on_member_join
Traceback (most recent call last):
  File "C:\Users\Timo\Anaconda3\envs\Discord\lib\site-packages\discord\client.py", line 270, in _run_event
    await coro(*args, **kwargs)
  File "C:/Users/Timo/PycharmProjects/Discord/Bot 1/Main.py", line 30, in on_member_join
    channel = Bot.get_channel("649275309396590626")
TypeError: get_channel() missing 1 required positional argument: 'id'

我使用的是 v1.2.5 版本。 这是代码:

@client.event
async def on_member_join(member):
    channel = Bot.get_channel("649275309396590626")
    await channel.send(f"{member} ist dem Server beigetreten!")

这是机器人变量:

import discord
from discord.ext import commands
from discord.ext.commands import Bot

client = Bot(command_prefix=".")

我将其编辑为:

@client.event async def on_member_join(member): channel = client.get_channel("649275309396590626") await channel.send(f"{member} ist dem Server beigetreten!")

现在我有这个错误:

File "C:/Users/Timo/PycharmProjects/Discord/Bot 1/Main.py", line 31, in on_member_join await channel.send(f"{member} ist dem Server beigetreten!") AttributeError: 'NoneType' object has no attribute 'send'

我发现问题了,我设置了一个字符串作为ID 而不是一个整数。 现在代码如下所示:

@client.event
async def on_member_join(member):
    channel = client.get_channel(649275309396590626)
    await channel.send(f"{member} ist dem Server beigetreten!")

client.get_guild(id) 函数需要整数输入。如果未正确给出或 id 无效,该函数将 return 一个 None 值。当您尝试使用 NoneType 对象发送内容时,您会导致错误。作为 NoneType 对象没有“发送”功能。

我建议阅读文档:https://discordpy.readthedocs.io/en/latest/api.html?highlight=get_guild#discord.Client.get_guild