尝试使用 Discord.py 重写向特定频道发送消息但它不起作用

ila*_*avy 4 python python-3.6 discord.py-rewrite

我目前正在开发一个不和谐的机器人,我正在尝试在用户升级后使用 Discord.py 重写向特定频道发送消息,但我收到此错误:

   await channel.message.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")
AttributeError: 'NoneType' object has no attribute 'message'

Run Code Online (Sandbox Code Playgroud)

这是所有的代码:

import discord
from discord.ext import commands

import json
import asyncio

class Levels(commands.Cog):
    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author == self.bot.user:
            return

        author_id = str(message.author.id)
        bot = commands.Bot(command_prefix='!')

        if author_id not in self.users:
            self.users[author_id] = {}
            self.users[author_id]['level'] = 1
            self.users[author_id]['exp'] = 0

        self.users[author_id]['exp'] += 1

        if author_id in self.users:
            if self.lvl_up(author_id):
                channel = bot.get_channel('636399538650742795')
                await channel.message.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")

    def __init__(self, bot):
        self.bot = bot

        with open(r"cogs\userdata.json", 'r') as f:
            self.users = json.load(f)

            self.bot.loop.create_task(self.save_users())

    async def save_users(self):
        await self.bot.wait_until_ready()
        while not self.bot.is_closed():
            with open(r"cogs\userdata.json", 'w') as f:
                json.dump(self.users, f, indent=4)

            await asyncio.sleep(5)


    def lvl_up(self, author_id):
        author_id = str(author_id)
        current_xp = self.users[author_id]['exp']
        current_lvl = self.users[author_id]['level']
        if current_xp >= ((3 * (current_lvl ** 2)) / .5):
            self.users[author_id]['level'] += 1
            return True
        else:
            return False

Run Code Online (Sandbox Code Playgroud)

我真的不确定这里的问题是什么,但如果有人知道这个问题,如果你能让我知道我如何纠正这个问题,我将不胜感激。

感谢阅读,我一直在努力解决这个问题好几个小时。

编辑:仍然有问题。

Cha*_*ton 8

我能够使用本指南发送消息:https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-send-a-message-to-a-specific-channel 我的代码使用的是:

channel = client.get_channel(12324234183172)
await channel.send('hello')
Run Code Online (Sandbox Code Playgroud)


小智 7

你得到,AttributeError因为channel是无。

要修复它,您需要像这样从频道 ID 中删除引号:

channel = bot.get_channel(636399538650742795)
Run Code Online (Sandbox Code Playgroud)

这在这里描述:https : //discordpy.readthedocs.io/en/latest/migrating.html#snowflakes-are-int


我还在下一行看到另一个错误。在channel没有任何message属性了。我认为你需要像这样修复它:

await channel.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")
Run Code Online (Sandbox Code Playgroud)

  • 我已经复制了十几次频道ID,机器人也可以访问这个频道,因为它也可以在频道中接收命令和发送消息 (2认同)