在函数内部直接向 Discord 客户端发送消息

时间:2021-02-12 03:29:22

标签: python function discord discord.py

我试图让我的代码检查列表中的两个字符串是否相等。如果它们不相等,则应直接向不和谐客户端发送消息。如果是,它应该继续执行该功能。我收到一条错误消息,指出“NoneType”对象没有发送属性。如果我复制这些行:

channel = bot.get_channel(123456789)
    await channel.send("Message")

然后删除 await 并将其粘贴到函数之外,我没有收到错误消息。我假设我的全局声明有问题,但我不确定。有人可以帮忙吗?

bot = commands.Bot(command_prefix='!')

# instantiating discord client
token = "redacted"
client = discord.Client()


@tasks.loop(seconds=5.0)
async def scrape():
    global linksAndTitles
    global pbe_titles
    global currPatch
    global allTitles
    global recentPatches
    global currTemp
    temp = []

    URL = "redacted"
    page = urlopen(URL)
    soup = BeautifulSoup(page, 'html.parser')
    pbe_titles = soup.find_all('redacted', attrs={'redacted': 'redacted'})
    for tags in pbe_titles:
        temp.append(tags.text.strip())
    tempCurr = '\n'.join(str(line) for line in temp[:1])
    if tempCurr != currTemp:
        channel = bot.get_channel(123456789)
        await channel.send("Message")

是最后两行给我抛出了错误。

2 个答案:

答案 0 :(得分:0)

错误 'NoneType' object has no attribute 'send' 的意思是您的 channel 变量没有从 bot.get_channel(123456789) 获取任何通道,这就是 channel 的值变为 None 的原因.我在代码方面没有发现任何错误,因此问题一定出在您传入的频道 ID 上。确保正确复制所需频道的 ID,然后将其粘贴到 channel = bot.get_channel(id)线。

答案 1 :(得分:0)

你的问题似乎是你在 botclient 之间的混合,一个例子说明了这一点,你在代码的开头定义了两者,但它们都不能很好地作为一对。您应该坚持使用一个,这就是它无法读取 ID 的原因,因为 bot 只是 bot = commands.Bot(command_prefix='!'),它没有连接到 discord.client 您的客户端被定义为 client = discord.Client()

这是问题会发生的线路,

如果您查看代码的顶部,您会看到 bot 仅定义为 command_prefix='!'

channel = bot.get_channel(123456789)

因此,通过使用一个,在本例中为 client,它们都应该像这样定义,

client = commands.Bot(command_prefix = '!')

这意味着您的其余代码应该使用 client,这里包含在您的代码中,

token = "redacted"
client = commands.Bot(command_prefix = '!')


@tasks.loop(seconds=5.0)
async def scrape():
    global linksAndTitles
    global pbe_titles
    global currPatch
    global allTitles
    global recentPatches
    global currTemp
    temp = []

    URL = "redacted"
    page = urlopen(URL)
    soup = BeautifulSoup(page, 'html.parser')
    pbe_titles = soup.find_all('redacted', attrs={'redacted': 'redacted'})
    for tags in pbe_titles:
        temp.append(tags.text.strip())
    tempCurr = '\n'.join(str(line) for line in temp[:1])
    if tempCurr != currTemp:
        channel = client.get_channel(123456789)
        await channel.send("Message")

但是,如果您仍然想使用 bot,请记住坚持使用它,而在您的代码中不需要使用相反的方法。希望这对你有用。还要确保您在代码底部正确运行机器人令牌